1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace EdmondsCommerce\DoctrineStaticMeta\Entity\Fields\Traits\String; |
6
|
|
|
|
7
|
|
|
// phpcs:disable |
8
|
|
|
|
9
|
|
|
use Doctrine\ORM\Mapping\Builder\ClassMetadataBuilder; |
10
|
|
|
use EdmondsCommerce\DoctrineStaticMeta\Entity\Fields\Interfaces\String\UrlFieldInterface; |
11
|
|
|
use EdmondsCommerce\DoctrineStaticMeta\MappingHelper; |
12
|
|
|
use EdmondsCommerce\DoctrineStaticMeta\Schema\Database; |
13
|
|
|
use Symfony\Component\Validator\Constraints\Length; |
14
|
|
|
use Symfony\Component\Validator\Constraints\Url; |
15
|
|
|
use Symfony\Component\Validator\Mapping\ClassMetadata as ValidatorClassMetaData; |
16
|
|
|
|
17
|
|
|
// phpcs:enable |
18
|
|
|
trait UrlFieldTrait |
19
|
|
|
{ |
20
|
|
|
|
21
|
|
|
/** |
22
|
|
|
* @var string|null |
23
|
|
|
*/ |
24
|
|
|
private $url; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* @SuppressWarnings(PHPMD.StaticAccess) |
28
|
|
|
* @param ClassMetadataBuilder $builder |
29
|
|
|
*/ |
30
|
|
|
public static function metaForUrl(ClassMetadataBuilder $builder): void |
31
|
|
|
{ |
32
|
|
|
MappingHelper::setSimpleStringFields( |
33
|
|
|
[UrlFieldInterface::PROP_URL], |
34
|
|
|
$builder, |
35
|
|
|
UrlFieldInterface::DEFAULT_URL |
36
|
|
|
); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* This method validates that the url is valid |
41
|
|
|
* |
42
|
|
|
* It allows the protocol to be ommitted, eg //www.edmondscommerce.co.uk |
43
|
|
|
* |
44
|
|
|
* You can extend the list of allowed protocols as you see fit |
45
|
|
|
* |
46
|
|
|
* @param ValidatorClassMetaData $metadata |
47
|
|
|
*/ |
48
|
|
|
protected static function validatorMetaForPropertyUrl(ValidatorClassMetaData $metadata): void |
49
|
|
|
{ |
50
|
|
|
$metadata->addPropertyConstraints( |
51
|
|
|
UrlFieldInterface::PROP_URL, |
52
|
|
|
[ |
53
|
|
|
new Url([ |
54
|
|
|
'relativeProtocol' => true, |
55
|
|
|
'protocols' => ['http', 'https'], |
56
|
|
|
]), |
57
|
|
|
new Length( |
58
|
|
|
[ |
59
|
|
|
'min' => 1, |
60
|
|
|
'max' => Database::MAX_VARCHAR_LENGTH, |
61
|
|
|
] |
62
|
|
|
), |
63
|
|
|
] |
64
|
|
|
); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* @return string|null |
69
|
|
|
*/ |
70
|
|
|
public function getUrl(): ?string |
71
|
|
|
{ |
72
|
|
|
if (null === $this->url) { |
73
|
|
|
return UrlFieldInterface::DEFAULT_URL; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
return $this->url; |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
/** |
80
|
|
|
* @param string|null $url |
81
|
|
|
* |
82
|
|
|
* @return self |
83
|
|
|
*/ |
84
|
|
|
private function setUrl(?string $url): self |
85
|
|
|
{ |
86
|
|
|
$this->updatePropertyValue( |
|
|
|
|
87
|
|
|
UrlFieldInterface::PROP_URL, |
88
|
|
|
$url |
89
|
|
|
); |
90
|
|
|
|
91
|
|
|
return $this; |
92
|
|
|
} |
93
|
|
|
} |
94
|
|
|
|