Passed
Pull Request — master (#127)
by Wouter
02:51
created

ProxyGenerator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 21
c 1
b 0
f 0
dl 0
loc 39
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A generate() 0 26 4
A __construct() 0 4 1
1
<?php
2
3
namespace Zenstruck\Foundry;
4
5
use ProxyManager\Factory\AccessInterceptorValueHolderFactory;
6
7
class ProxyGenerator
8
{
9
    /** @var Configuration */
10
    private $configuration;
11
    /** @var AccessInterceptorValueHolderFactory */
12
    private $factory;
13
14
    public function __construct(Configuration $configuration, ?AccessInterceptorValueHolderFactory $factory = null)
15
    {
16
        $this->configuration = $configuration;
17
        $this->factory = $factory ?? new AccessInterceptorValueHolderFactory();
18
    }
19
20
    public function generate(object $object, array $methods = []): object
21
    {
22
        $objectManager = $this->configuration->objectManagerFor(\get_class($object));
23
        $interceptor = function (object $proxy, object $model) use ($objectManager): void {
24
            $objectManager->refresh($model);
25
        };
26
27
        $objectMethods = get_class_methods($object);
28
        $interceptMethods = [];
29
        if (!$methods) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $methods of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
30
            $interceptMethods = $objectMethods;
31
        } else {
32
            foreach ($methods as $methodName) {
33
                if (false === strpos($methodName, '*')){
34
                    $interceptMethods[] = $methodName;
35
                    continue;
36
                }
37
38
                $methodNameRegex = '/^'.str_replace('*', '[[:alnum:]]+', $methodName).'$/';
39
                $interceptMethods = array_merge($interceptMethods, array_filter($objectMethods, function ($objectMethod) use ($methodNameRegex) {
40
                    return 1 !== preg_match($methodNameRegex, $objectMethod);
41
                }));
42
            }
43
        }
44
45
        return $this->factory->createProxy($object, array_fill_keys(array_unique($interceptMethods), $interceptor));
46
    }
47
}
48