1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace EdmondsCommerce\DoctrineStaticMeta\Entity\Fields\FakerData\String; |
6
|
|
|
|
7
|
|
|
use EdmondsCommerce\DoctrineStaticMeta\Entity\Fields\FakerData\AbstractFakerDataProvider; |
8
|
|
|
use Faker\Generator; |
9
|
|
|
use RuntimeException; |
10
|
|
|
use Symfony\Component\Intl\Intl; |
11
|
|
|
use Symfony\Component\Intl\Locales; |
12
|
|
|
|
13
|
|
|
use function class_exists; |
14
|
|
|
|
15
|
|
|
class LocaleIdentifierFakerData extends AbstractFakerDataProvider |
16
|
|
|
{ |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @var string[] |
20
|
|
|
*/ |
21
|
|
|
private static $locales; |
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* LocaleIdentifierFakerDataProvider constructor. |
25
|
|
|
* |
26
|
|
|
* @param Generator $generator |
27
|
|
|
*/ |
28
|
|
|
public function __construct(Generator $generator) |
29
|
|
|
{ |
30
|
|
|
parent::__construct($generator); |
31
|
|
|
if (null === self::$locales) { |
|
|
|
|
32
|
|
|
self::$locales = $this->getLocales(); |
33
|
|
|
} |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
/** |
37
|
|
|
* Symfony 4.3 deprecated the Intl::getLocaleBundle in favour of the new Locales class. We need to support both the |
38
|
|
|
* older projects that are using symfony 4.0 - 2 as well as newer versions so we will use the method to try and get |
39
|
|
|
* the locales the new way if possible, and then fall back to the older way if not |
40
|
|
|
* |
41
|
|
|
* @return array |
42
|
|
|
* @SuppressWarnings(PHPMD.StaticAccess) |
43
|
|
|
*/ |
44
|
|
|
private function getLocales(): array |
45
|
|
|
{ |
46
|
|
|
if (class_exists(Locales::class)) { |
47
|
|
|
return Locales::getLocales(); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
if (class_exists(Intl::class)) { |
51
|
|
|
return Intl::getLocaleBundle()->getLocales(); |
|
|
|
|
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
throw new RuntimeException('No locale provider exists'); |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
public function __invoke(): string |
58
|
|
|
{ |
59
|
|
|
do { |
60
|
|
|
$value = $this->generator->locale; |
61
|
|
|
} while (false === $this->isValid($value)); |
62
|
|
|
|
63
|
|
|
return $value; |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
private function isValid(string $value): bool |
67
|
|
|
{ |
68
|
|
|
if (!isset(self::$locales[$value])) { |
69
|
|
|
return false; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
return true; |
73
|
|
|
} |
74
|
|
|
} |
75
|
|
|
|