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