FakerValueResolver::__construct()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 0

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 0
c 0
b 0
f 0
dl 0
loc 4
ccs 1
cts 1
cp 1
rs 10
cc 1
nc 1
nop 2
crap 1
1
<?php
2
3
namespace CHStudio\Raven\Http\Factory\Resolver;
4
5
use Faker\Generator;
6
use InvalidArgumentException;
7
use JsonException;
8
9
class FakerValueResolver implements ValueResolverInterface
10
{
11 12
    public function __construct(
12
        private readonly Generator $faker,
13
        private readonly ValueResolverInterface $resolver
14
    ) {
15 12
    }
16
17 11
    public function resolve(mixed $value): mixed
18
    {
19 11
        if (\is_string($value) && preg_match('/<([^(]+)\((.*)\)>/', $value, $matches) === 1) {
20 5
            return $this->resolveFakerValue($matches);
21
        }
22
23 6
        return $this->resolver->resolve($value);
24
    }
25
26
    /**
27
     * @param array<int, string> $matches
28
     */
29 5
    private function resolveFakerValue(array $matches): mixed
30
    {
31
        try {
32 5
            $methodName = $matches[1];
33 5
            $arguments =  json_decode('['.$matches[2].']', true, 512, JSON_THROW_ON_ERROR);
34
35 4
            return $this->faker->__call(
36 4
                $methodName,
37 4
                \is_array($arguments) ? $arguments : [$arguments]
38 4
            );
39 2
        } catch (InvalidArgumentException) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
40 1
        } catch (JsonException $error) {
41 1
            $message = sprintf(
42 1
                "Can't extract the arguments to call method %s: [%s]",
43 1
                $matches[1],
44 1
                $matches[2]
45 1
            );
46 1
            throw new InvalidArgumentException($message, 0, $error);
47
        }
48
49 1
        return null;
50
    }
51
}
52