Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
72.73% |
16 / 22 |
|
66.67% |
2 / 3 |
CRAP | |
0.00% |
0 / 1 |
| UseFakeMethodFaker | |
72.73% |
16 / 22 |
|
66.67% |
2 / 3 |
12.03 | |
0.00% |
0 / 1 |
| supports | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| fakeFor | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
1 | |||
| runFake | |
70.00% |
14 / 20 |
|
0.00% |
0 / 1 |
9.73 | |||
| 1 | <?php |
| 2 | namespace Apie\Faker\Fakers; |
| 3 | |
| 4 | use Apie\Core\Attributes\FakeMethod; |
| 5 | use Apie\Core\Exceptions\InvalidTypeException; |
| 6 | use Apie\Core\Exceptions\MethodIsNotStaticException; |
| 7 | use Apie\Faker\Interfaces\ApieClassFaker; |
| 8 | use Faker\Generator; |
| 9 | use ReflectionAttribute; |
| 10 | use ReflectionClass; |
| 11 | |
| 12 | /** @implements ApieClassFaker<object> */ |
| 13 | class UseFakeMethodFaker implements ApieClassFaker |
| 14 | { |
| 15 | public function supports(ReflectionClass $class): bool |
| 16 | { |
| 17 | return !empty($class->getAttributes(FakeMethod::class)); |
| 18 | } |
| 19 | public function fakeFor(Generator $generator, ReflectionClass $class): object |
| 20 | { |
| 21 | return self::runFake($generator, $class, $class->getAttributes(FakeMethod::class)); |
| 22 | } |
| 23 | |
| 24 | /** |
| 25 | * @internal Used by CheckBaseClassFaker and UseFakeMethodFaker |
| 26 | * |
| 27 | * @template T of object |
| 28 | * @param ReflectionClass<T> $class |
| 29 | * @param array<int, ReflectionAttribute<FakeMethod>> $attributes |
| 30 | */ |
| 31 | public static function runFake(Generator $generator, ReflectionClass $class, array $attributes): object |
| 32 | { |
| 33 | /** @var ReflectionAttribute<FakeMethod> $fakeMethod */ |
| 34 | $fakeMethod = $generator->randomElement($attributes); |
| 35 | $methodName = $fakeMethod->newInstance()->methodName; |
| 36 | $method = $class->getMethod($methodName); |
| 37 | if (!$method->isStatic()) { |
| 38 | throw new MethodIsNotStaticException($method); |
| 39 | } |
| 40 | $arguments = []; |
| 41 | foreach ($method->getParameters() as $parameter) { |
| 42 | $type = $parameter->getType(); |
| 43 | if ($parameter->isVariadic()) { |
| 44 | $rand = $generator->rand(0, 4); |
| 45 | for ($i = 0; $i < $rand; $i++) { |
| 46 | $arguments[] = $generator->fakeFromType($type); |
| 47 | } |
| 48 | } elseif ($parameter->allowsNull() && 1 === $generator->rand(0, 4)) { |
| 49 | $arguments[] = null; |
| 50 | } else { |
| 51 | $arguments[] = $generator->fakeFromType($type); |
| 52 | } |
| 53 | } |
| 54 | // can not call ReflectionMethod::invokeArgs because of late static binding |
| 55 | $className = $class->name; |
| 56 | $object = $className::$methodName(...$arguments); |
| 57 | if (!$class->isInstance($object)) { |
| 58 | throw new InvalidTypeException($object, $class->name); |
| 59 | } |
| 60 | return $object; |
| 61 | } |
| 62 | } |