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
|
6 |
|
public static function metaForUrl(ClassMetadataBuilder $builder): void |
29
|
|
|
{ |
30
|
6 |
|
MappingHelper::setSimpleStringFields( |
31
|
6 |
|
[UrlFieldInterface::PROP_URL], |
32
|
6 |
|
$builder, |
33
|
6 |
|
UrlFieldInterface::DEFAULT_URL, |
34
|
6 |
|
false |
35
|
|
|
); |
36
|
6 |
|
} |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* This method validates that the url is valid |
40
|
|
|
* |
41
|
|
|
* It allows the protocol to be ommitted, eg //www.edmondscommerce.co.uk |
42
|
|
|
* |
43
|
|
|
* You can extend the list of allowed protocols as you see fit |
44
|
|
|
*/ |
45
|
6 |
|
protected static function validatorMetaForPropertyUrl(ValidatorClassMetaData $metadata): void |
46
|
|
|
{ |
47
|
6 |
|
$metadata->addPropertyConstraints( |
48
|
6 |
|
UrlFieldInterface::PROP_URL, |
49
|
|
|
[ |
50
|
6 |
|
new Url([ |
51
|
6 |
|
'relativeProtocol' => true, |
52
|
|
|
'protocols' => ['http', 'https'], |
53
|
|
|
]), |
54
|
6 |
|
new Length( |
55
|
|
|
[ |
56
|
6 |
|
'min' => 1, |
57
|
|
|
'max' => Database::MAX_VARCHAR_LENGTH, |
58
|
|
|
] |
59
|
|
|
), |
60
|
|
|
] |
61
|
|
|
); |
62
|
6 |
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* @return string|null |
66
|
|
|
*/ |
67
|
6 |
|
public function getUrl(): ?string |
68
|
|
|
{ |
69
|
6 |
|
if (null === $this->url) { |
70
|
6 |
|
return UrlFieldInterface::DEFAULT_URL; |
71
|
|
|
} |
72
|
|
|
|
73
|
6 |
|
return $this->url; |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
/** |
77
|
|
|
* @param string|null $url |
78
|
|
|
* |
79
|
|
|
* @return self |
80
|
|
|
*/ |
81
|
6 |
|
private function setUrl(?string $url): self |
82
|
|
|
{ |
83
|
6 |
|
$this->updatePropertyValue( |
|
|
|
|
84
|
6 |
|
UrlFieldInterface::PROP_URL, |
85
|
6 |
|
$url |
86
|
|
|
); |
87
|
|
|
|
88
|
6 |
|
return $this; |
89
|
|
|
} |
90
|
|
|
} |
91
|
|
|
|