1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Ecodev\Felix; |
6
|
|
|
|
7
|
|
|
use Ecodev\Felix\Model\Model; |
8
|
|
|
use GraphQL\Doctrine\Definition\EntityID; |
9
|
|
|
use ReflectionClass; |
10
|
|
|
|
11
|
|
|
abstract class Utility |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* Returns the short class name of any object, eg: Application\Model\Calendar => Calendar. |
15
|
|
|
* |
16
|
|
|
* @param class-string|object $object |
|
|
|
|
17
|
|
|
*/ |
18
|
6 |
|
public static function getShortClassName(object|string $object): string |
19
|
|
|
{ |
20
|
6 |
|
$reflect = new ReflectionClass($object); |
21
|
|
|
|
22
|
6 |
|
return $reflect->getShortName(); |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* Replace EntityID model and don't touch other values. |
27
|
|
|
* |
28
|
|
|
* @param array $data mix of objects and scalar values |
29
|
|
|
*/ |
30
|
1 |
|
public static function entityIdToModel(?array $data): ?array |
31
|
|
|
{ |
32
|
1 |
|
if ($data === null) { |
|
|
|
|
33
|
1 |
|
return null; |
34
|
|
|
} |
35
|
|
|
|
36
|
1 |
|
foreach ($data as &$value) { |
37
|
1 |
|
if ($value instanceof EntityID) { |
38
|
1 |
|
$value = $value->getEntity(); |
39
|
|
|
} |
40
|
|
|
} |
41
|
|
|
|
42
|
1 |
|
return $data; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Replace object by their ID in the array and don't touch other values. |
47
|
|
|
* |
48
|
|
|
* Support both AbstractModel and EntityID. |
49
|
|
|
* |
50
|
|
|
* @param array $data mix of objects and scalar values |
51
|
|
|
*/ |
52
|
1 |
|
public static function modelToId(?array $data): ?array |
53
|
|
|
{ |
54
|
1 |
|
if ($data === null) { |
|
|
|
|
55
|
|
|
return null; |
56
|
|
|
} |
57
|
|
|
|
58
|
1 |
|
foreach ($data as &$value) { |
59
|
1 |
|
if ($value instanceof Model || $value instanceof EntityID) { |
60
|
1 |
|
$value = $value->getId(); |
61
|
|
|
} |
62
|
|
|
} |
63
|
|
|
|
64
|
1 |
|
return $data; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* Removes duplicate values from an array by using strict comparison. |
69
|
|
|
* |
70
|
|
|
* So it can be used with objects, whereas the native `array_unique` cannot. |
71
|
|
|
*/ |
72
|
1 |
|
public static function unique(array $array): array |
73
|
|
|
{ |
74
|
1 |
|
$result = []; |
75
|
1 |
|
foreach ($array as $value) { |
76
|
1 |
|
if (!in_array($value, $result, true)) { |
77
|
1 |
|
$result[] = $value; |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|
81
|
1 |
|
return $result; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|