Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
100.00% |
14 / 14 |
|
100.00% |
2 / 2 |
CRAP | |
100.00% |
1 / 1 |
| UseConstructorFaker | |
100.00% |
14 / 14 |
|
100.00% |
2 / 2 |
12 | |
100.00% |
1 / 1 |
| supports | |
100.00% |
1 / 1 |
|
100.00% |
1 / 1 |
2 | |||
| fakeFor | |
100.00% |
13 / 13 |
|
100.00% |
1 / 1 |
10 | |||
| 1 | <?php |
| 2 | namespace Apie\Faker\Fakers; |
| 3 | |
| 4 | use Apie\Faker\Interfaces\ApieClassFaker; |
| 5 | use Faker\Generator; |
| 6 | use ReflectionClass; |
| 7 | use ReflectionMethod; |
| 8 | use ReflectionProperty; |
| 9 | |
| 10 | /** @implements ApieClassFaker<object> */ |
| 11 | class UseConstructorFaker implements ApieClassFaker |
| 12 | { |
| 13 | public function supports(ReflectionClass $class): bool |
| 14 | { |
| 15 | return is_null($class->getConstructor()) || $class->getConstructor()->isPublic(); |
| 16 | } |
| 17 | |
| 18 | public function fakeFor(Generator $generator, ReflectionClass $class): object |
| 19 | { |
| 20 | $constructor = $class->getConstructor(); |
| 21 | $arguments = $constructor ? $generator->fakeArgumentsOfMethod($constructor) : []; |
| 22 | $object = $class->newInstance(...$arguments); |
| 23 | foreach ($class->getMethods(ReflectionMethod::IS_PUBLIC) as $method) { |
| 24 | if ($generator->randomElement([0, 1]) && preg_match('/^(set|with)([A-Z].*)$/', $method->name)) { |
| 25 | $arguments = $generator->fakeArgumentsOfMethod($method); |
| 26 | $result = $method->invoke($object, ...$arguments); |
| 27 | // in case object is immutable or polymorphic... |
| 28 | if (is_object($result) && $class->isInstance($result)) { |
| 29 | $object = $result; |
| 30 | } |
| 31 | } |
| 32 | } |
| 33 | foreach ($class->getProperties(ReflectionProperty::IS_PUBLIC) as $property) { |
| 34 | if (!$property->isReadOnly() || !$property->isInitialized($object)) { |
| 35 | $object->{$property->name} = $generator->fakeFromType($property->getType()); |
| 36 | } |
| 37 | } |
| 38 | return $object; |
| 39 | } |
| 40 | } |