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 Symfony\Component\Validator\Constraints\Url; |
11
|
|
|
use Symfony\Component\Validator\Mapping\ClassMetadata as ValidatorClassMetaData; |
12
|
|
|
|
13
|
|
|
// phpcs:enable |
14
|
|
|
trait UrlFieldTrait |
15
|
|
|
{ |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @var string|null |
19
|
|
|
*/ |
20
|
|
|
private $url; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* @SuppressWarnings(PHPMD.StaticAccess) |
24
|
|
|
* @param ClassMetadataBuilder $builder |
25
|
|
|
*/ |
26
|
6 |
|
public static function metaForUrl(ClassMetadataBuilder $builder): void |
27
|
|
|
{ |
28
|
6 |
|
MappingHelper::setSimpleStringFields( |
29
|
6 |
|
[UrlFieldInterface::PROP_URL], |
30
|
6 |
|
$builder, |
31
|
6 |
|
UrlFieldInterface::DEFAULT_URL, |
32
|
6 |
|
false |
33
|
|
|
); |
34
|
6 |
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* This method validates that the url is valid |
38
|
|
|
* |
39
|
|
|
* It allows the protocol to be ommitted, eg //www.edmondscommerce.co.uk |
40
|
|
|
* |
41
|
|
|
* You can extend the list of allowed protocols as you see fit |
42
|
|
|
*/ |
43
|
6 |
|
protected static function validatorMetaForPropertyUrl(ValidatorClassMetaData $metadata): void |
44
|
|
|
{ |
45
|
6 |
|
$metadata->addPropertyConstraint( |
46
|
6 |
|
UrlFieldInterface::PROP_URL, |
47
|
6 |
|
new Url([ |
48
|
6 |
|
'relativeProtocol' => true, |
49
|
|
|
'protocols' => ['http', 'https'], |
50
|
|
|
]) |
51
|
|
|
); |
52
|
6 |
|
} |
53
|
|
|
|
54
|
|
|
/** |
55
|
|
|
* @return string|null |
56
|
|
|
*/ |
57
|
6 |
|
public function getUrl(): ?string |
58
|
|
|
{ |
59
|
6 |
|
if (null === $this->url) { |
60
|
6 |
|
return UrlFieldInterface::DEFAULT_URL; |
61
|
|
|
} |
62
|
|
|
|
63
|
6 |
|
return $this->url; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
/** |
67
|
|
|
* @param string|null $url |
68
|
|
|
* |
69
|
|
|
* @return self |
70
|
|
|
*/ |
71
|
6 |
|
private function setUrl(?string $url): self |
72
|
|
|
{ |
73
|
6 |
|
$this->updatePropertyValue( |
|
|
|
|
74
|
6 |
|
UrlFieldInterface::PROP_URL, |
75
|
6 |
|
$url |
76
|
|
|
); |
77
|
|
|
|
78
|
6 |
|
return $this; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|