forked from thephpleague/oauth2-server-bundle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImplodedArray.php
95 lines (75 loc) · 2.2 KB
/
ImplodedArray.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
<?php
declare(strict_types=1);
namespace League\Bundle\OAuth2ServerBundle\DBAL\Type;
use Doctrine\DBAL\Platforms\AbstractPlatform;
use Doctrine\DBAL\Types\TextType;
/**
* @psalm-template T
*/
abstract class ImplodedArray extends TextType
{
/**
* @var string
*/
private const VALUE_DELIMITER = ' ';
/**
* @psalm-suppress MixedArgumentTypeCoercion
*/
public function convertToDatabaseValue(mixed $value, AbstractPlatform $platform): ?string
{
if (!\is_array($value)) {
throw new \LogicException('This type can only be used in combination with arrays.');
}
if (0 === \count($value)) {
return null;
}
/** @psalm-var T $item */
foreach ($value as $item) {
$this->assertValueCanBeImploded($item);
}
return implode(self::VALUE_DELIMITER, $value);
}
/**
* @psalm-return list<T>
*/
public function convertToPHPValue(mixed $value, AbstractPlatform $platform): array
{
if (null === $value) {
return [];
}
\assert(\is_string($value), 'Expected $value of be either a string or null.');
$values = explode(self::VALUE_DELIMITER, $value);
return $this->convertDatabaseValues($values);
}
public function getSQLDeclaration(array $column, AbstractPlatform $platform): string
{
$column['length'] = 65535;
return parent::getSQLDeclaration($column, $platform);
}
public function requiresSQLCommentHint(AbstractPlatform $platform): bool
{
return true;
}
/**
* @psalm-param T $value
*/
private function assertValueCanBeImploded($value): void
{
if (null === $value) {
return;
}
if (\is_scalar($value)) {
return;
}
if (\is_object($value) && method_exists($value, '__toString')) {
return;
}
throw new \InvalidArgumentException(sprintf('The value of \'%s\' type cannot be imploded.', \gettype($value)));
}
/**
* @param list<string> $values
*
* @return list<T>
*/
abstract protected function convertDatabaseValues(array $values): array;
}