-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathPhpUnitUtil.php
302 lines (267 loc) · 9.84 KB
/
PhpUnitUtil.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
<?php
declare(strict_types=1);
namespace App\Tests\Utils;
use App\General\Domain\Doctrine\DBAL\Types\Types as AppTypes;
use App\General\Domain\Enum\Language;
use App\General\Domain\Enum\Locale;
use App\Log\Domain\Enum\LogLogin;
use App\Role\Domain\Entity\Role;
use DateTime;
use DateTimeImmutable;
use Doctrine\DBAL\Types\Type;
use Exception;
use LogicException;
use Ramsey\Uuid\UuidInterface;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use ReflectionClass;
use ReflectionException;
use ReflectionMethod;
use RegexIterator;
use stdClass;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\HttpKernel\KernelInterface;
use Throwable;
use function array_key_exists;
use function explode;
use function sprintf;
use function str_contains;
use function substr_count;
/**
* @package App\Tests
*/
class PhpUnitUtil
{
final public const string TYPE_INT = 'int';
final public const string TYPE_INTEGER = 'integer';
final public const string TYPE_STRING = 'string';
final public const string TYPE_ARRAY = 'array';
final public const string TYPE_JSON = 'json';
final public const string TYPE_BOOL = 'bool';
final public const string TYPE_BOOLEAN = 'boolean';
final public const string TYPE_CUSTOM_CLASS = 'CustomClass';
final public const string TYPE_ENUM = 'ENUM';
/**
* @var array<string, mixed>
*/
private static array $validValueCache = [];
/**
* @var array<string, stdClass|DateTime|string>
*/
private static array $invalidValueCache = [];
/**
* @codeCoverageIgnore
*
* @throws Exception
*/
public static function loadFixtures(KernelInterface $kernel): void
{
$application = new Application($kernel);
$application->setAutoExit(false);
$input = new ArrayInput([
'command' => 'doctrine:fixtures:load',
'--no-interaction' => true,
'--quiet' => true,
]);
$input->setInteractive(false);
$application->run($input, new ConsoleOutput(OutputInterface::VERBOSITY_QUIET));
}
/**
* @codeCoverageIgnore
*
* @return array<int, string>
*/
public static function recursiveFileSearch(string $folder, string $pattern): array
{
$dir = new RecursiveDirectoryIterator($folder);
$ite = new RecursiveIteratorIterator($dir);
/**
* @var array<int, string> $files
*
* @phpstan-ignore-next-line
*/
$files = new RegexIterator($ite, $pattern, RegexIterator::GET_MATCH);
$fileList = [];
foreach ($files as $file) {
$fileList[] = $file[0];
}
return $fileList;
}
/**
* Method to call specified 'protected' or 'private' method on given class.
*
* @param object $object The instantiated instance of your class
* @param non-empty-string $name The name of your private/protected method
* @param array<int, mixed> $args Method arguments
*
* @throws ReflectionException
*/
public static function callMethod(object $object, string $name, array $args): mixed
{
return self::getMethod($object, $name)->invokeArgs($object, $args);
}
/**
* Get a private or protected method for testing/documentation purposes.
* How to use for MyClass->foo():
* $cls = new MyClass();
* $foo = PHPUnitUtil::getPrivateMethod($cls, 'foo');
* $foo->invoke($cls, $...);
*
* @param object $object The instantiated instance of your class
* @param non-empty-string $name The name of your private/protected method
*
* @throws ReflectionException
*
* @return ReflectionMethod The method you asked for
*/
public static function getMethod(object $object, string $name): ReflectionMethod
{
// Get reflection and make specified method accessible
$class = new ReflectionClass($object);
$method = $class->getMethod($name);
$method->setAccessible(true);
return $method;
}
/**
* Helper method to get any property value from given class.
*
* @param non-empty-string $property
*
* @throws ReflectionException
*/
public static function getProperty(string $property, object $object): mixed
{
$clazz = new ReflectionClass($object::class);
$property = $clazz->getProperty($property);
$property->setAccessible(true);
return $property->getValue($object);
}
public static function getType(Type | string | null $type): string
{
$exception = new LogicException(
sprintf(
"Currently type '%s' is not supported within type normalizer",
$type instanceof Type ? $type::class : (string)$type,
),
);
return match ($type) {
'time', 'date', 'datetime' => DateTime::class,
'time_immutable', 'date_immutable', 'datetime_immutable' => DateTimeImmutable::class,
AppTypes::ENUM_LANGUAGE => Language::class,
AppTypes::ENUM_LOCALE => Locale::class,
AppTypes::ENUM_LOG_LOGIN => LogLogin::class,
self::TYPE_INT, self::TYPE_INTEGER => self::TYPE_INT,
self::TYPE_STRING, 'bigint', 'text' => self::TYPE_STRING,
self::TYPE_JSON => self::TYPE_JSON,
self::TYPE_ARRAY => self::TYPE_ARRAY,
self::TYPE_BOOL, self::TYPE_BOOLEAN => self::TYPE_BOOL,
default => throw $exception,
};
}
/**
* Helper method to override any property value within given class.
*
* @param non-empty-string $property
* @param UuidInterface|array<array-key, string>|null $value
*
* @throws ReflectionException
*/
public static function setProperty(string $property, UuidInterface | array | null $value, object $object): void
{
$clazz = new ReflectionClass($object::class);
$property = $clazz->getProperty($property);
$property->setAccessible(true);
$property->setValue($object, $value);
}
/**
* Helper method to get valid value for specified type.
*
* @param array<string, string>|null $meta
*
* @throws Throwable
*/
public static function getValidValueForType(string $type, ?array $meta = null): mixed
{
$cacheKey = $type . serialize($meta);
if (!array_key_exists($cacheKey, self::$validValueCache)) {
self::$validValueCache[$cacheKey] = self::getValidValue($meta, $type);
}
return self::$validValueCache[$cacheKey];
}
/**
* Helper method to get invalid value for specified type.
*
* @throws Throwable
*/
public static function getInvalidValueForType(string $type): DateTime | stdClass | string
{
if ($type !== stdClass::class && substr_count($type, '\\') > 1) {
$type = self::TYPE_CUSTOM_CLASS;
}
if (!array_key_exists($type, self::$invalidValueCache)) {
if (str_contains($type, '|')) {
$output = self::getInvalidValueForType(explode('|', $type)[0]);
} elseif (str_contains($type, '[]')) {
$output = self::getInvalidValueForType(self::TYPE_ARRAY);
} else {
$output = match ($type) {
stdClass::class, DateTimeImmutable::class => new DateTime(),
self::TYPE_CUSTOM_CLASS, self::TYPE_INT, self::TYPE_INTEGER, self::TYPE_STRING, self::TYPE_ARRAY,
self::TYPE_BOOL, self::TYPE_BOOLEAN, DateTime::class, 'enumLanguage', 'enumLocale', 'enumLogLogin'
=> new stdClass(),
default => throw new LogicException(sprintf("Cannot create invalid value for type '%s'.", $type)),
};
}
self::$invalidValueCache[$type] = $output;
}
return self::$invalidValueCache[$type];
}
/**
* @param array<string, string>|null $meta
*
* @throws Throwable
*/
private static function getValidValue(
?array $meta,
string $type
): mixed {
$meta ??= [];
$class = stdClass::class;
$params = [null];
if (substr_count($type, '\\') > 1 && !str_contains($type, '|')) {
/** @var class-string $class */
$class = $meta !== [] && array_key_exists('targetEntity', $meta) ? $meta['targetEntity'] : $type;
$type = self::TYPE_CUSTOM_CLASS;
if ((new ReflectionClass($class))->isEnum()) {
$type = self::TYPE_ENUM;
} else {
/** @var class-string $class */
$class = $class[0] === '\\' ? ltrim($class, '\\') : $class;
}
if ($class === Role::class) {
$params = ['Some Role'];
}
}
$output = match ($type) {
self::TYPE_ENUM => current($class::cases()), // TODO: fix this
self::TYPE_CUSTOM_CLASS => new $class(...$params),
self::TYPE_INT, self::TYPE_INTEGER => 666,
self::TYPE_STRING => 'Some text here',
self::TYPE_ARRAY => ['some', self::TYPE_ARRAY, 'here'],
self::TYPE_BOOL, self::TYPE_BOOLEAN => true,
DateTime::class => new DateTime(),
DateTimeImmutable::class => new DateTimeImmutable(),
default => null,
};
if (str_contains($type, '|')) {
$output = self::getValidValueForType(explode('|', $type)[0], $meta);
} elseif (str_contains($type, '[]')) {
/** @var array<mixed, object> $output */
$output = self::getValidValueForType(self::TYPE_ARRAY, $meta);
}
return $output ?? throw new LogicException(sprintf("Cannot create valid value for type '%s'.", $type));
}
}