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