-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathphone.value-object.ts
82 lines (70 loc) · 2.44 KB
/
phone.value-object.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import { Result, ValueObject } from "rich-domain";
import MobilePhone from "./mobile.value-object";
import HomePhone from "./home.value-object";
import { ddd } from "./ddd.list";
export class Phone extends ValueObject<string> {
protected static readonly MESSAGE: string = 'Invalid Phone Number';
toCall: () => string;
number: () => string;
value: () => string;
ddd: () => ddd;
isMobile: () => boolean;
isHome: () => boolean;
uf: () => string;
toPattern: () => string;
/**
*
* @returns DDD only as number
* @example 11
*/
public static ddd(phone: string): ddd {
const value = this.util.string(phone).removeSpecialChars();
return parseInt(value.slice(0, 2)) as ddd;
}
public static removeSpecialChars(cell: string): string {
const value = this.util.string(cell).removeSpecialChars();
return this.util.string(value).removeSpaces();
}
public static addMask(cell: string): string {
if (this.isMobile(cell)) return MobilePhone.addMask(cell);
return HomePhone.addMask(cell);
}
public static isValid(phone: string): boolean {
return this.isValidProps(phone);
}
public static isValidProps(phone: string): boolean {
return this.isHome(phone) || this.isMobile(phone);
}
public static isMobile(phone: string): boolean {
return MobilePhone.isValid(phone);
};
public static isHome(phone: string): boolean {
return HomePhone.isValid(phone);
};
/**
*
* @param value value as string
* @returns instance of MobilePhone or HomePhone or throw an error
*/
public static init(value: string): MobilePhone | HomePhone {
const isValid = this.isValidProps(value);
if (!isValid) throw new Error(this.MESSAGE);
const isMobile = this.isMobile(value);
if (isMobile) return MobilePhone.init(value);
return HomePhone.init(value);
}
/**
*
* @param value Brazilian Mobile or Home phone number
* @example (XX) 9XXXX-XXXX or (XX) 3XXX-XXXX
* @returns Result of MobilePhone or HomePhone
*/
public static create(value: string): Result<MobilePhone | HomePhone | null> {
const isValid = this.isValidProps(value);
if (!isValid) return Result.fail(this.MESSAGE);
const isMobile = this.isMobile(value);
if (isMobile) return MobilePhone.create(value);
return HomePhone.create(value);
}
}
export default Phone;