|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Bdf\Form\Phone; |
|
4
|
|
|
|
|
5
|
|
|
use Bdf\Form\Child\ChildBuilder; |
|
6
|
|
|
use Bdf\Form\ElementBuilderInterface; |
|
7
|
|
|
use Bdf\Form\Phone\Transformer\PhoneNumberToStringTransformer; |
|
8
|
|
|
use Bdf\Form\Registry\RegistryInterface; |
|
9
|
|
|
use libphonenumber\PhoneNumberFormat; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* @extends ChildBuilder<PhoneElementBuilder> |
|
13
|
|
|
*/ |
|
14
|
|
|
class PhoneChildBuilder extends ChildBuilder |
|
15
|
|
|
{ |
|
16
|
|
|
/** |
|
17
|
|
|
* @var PhoneNumberFormat::*|null |
|
18
|
|
|
*/ |
|
19
|
|
|
private $saveFormat; |
|
20
|
|
|
|
|
21
|
|
|
/** |
|
22
|
|
|
* {@inheritdoc} |
|
23
|
|
|
* |
|
24
|
|
|
* @param PhoneElementBuilder $elementBuilder |
|
25
|
|
|
*/ |
|
26
|
9 |
|
public function __construct(string $name, ElementBuilderInterface $elementBuilder, RegistryInterface $registry = null) |
|
27
|
|
|
{ |
|
28
|
9 |
|
parent::__construct($name, $elementBuilder, $registry); |
|
29
|
|
|
|
|
30
|
9 |
|
$this->addTransformerProvider([$this, 'provideModelTransformer']); |
|
31
|
9 |
|
} |
|
32
|
|
|
|
|
33
|
|
|
/** |
|
34
|
|
|
* The model value of the input will be transformer to a formatted string |
|
35
|
|
|
* |
|
36
|
|
|
* <code> |
|
37
|
|
|
* // The entity : the phone is a simple string |
|
38
|
|
|
* class MyEntity { |
|
39
|
|
|
* public string $phone; |
|
40
|
|
|
* } |
|
41
|
|
|
* |
|
42
|
|
|
* // Build the element |
|
43
|
|
|
* $builder->phone('phone')->saveAsString()->getter()->setter(); |
|
44
|
|
|
* |
|
45
|
|
|
* $form->import(MyEntity::get($id)); |
|
46
|
|
|
* $form['phone']->element()->value(); // Value is an instance of PhoneNumber |
|
47
|
|
|
* |
|
48
|
|
|
* $entity = $form->value(); |
|
49
|
|
|
* $entity->phone; // phone is a string |
|
50
|
|
|
* </code> |
|
51
|
|
|
* |
|
52
|
|
|
* @param PhoneNumberFormat::*|null $format The phone number format. Must be one of the constant of PhoneNumberFormat. Set null to disable |
|
|
|
|
|
|
53
|
|
|
* |
|
54
|
|
|
* @return $this |
|
55
|
|
|
* |
|
56
|
|
|
* @see PhoneNumberToStringTransformer |
|
57
|
|
|
*/ |
|
58
|
5 |
|
public function saveAsString(?int $format = PhoneNumberFormat::E164): self |
|
59
|
|
|
{ |
|
60
|
5 |
|
$this->saveFormat = $format; |
|
|
|
|
|
|
61
|
|
|
|
|
62
|
5 |
|
return $this; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* @return PhoneNumberToStringTransformer[] |
|
67
|
|
|
*/ |
|
68
|
8 |
|
protected function provideModelTransformer(): array |
|
69
|
|
|
{ |
|
70
|
8 |
|
if ($this->saveFormat === null) { |
|
71
|
4 |
|
return []; |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
4 |
|
return [new PhoneNumberToStringTransformer($this->saveFormat)]; |
|
|
|
|
|
|
75
|
|
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|