Completed
Pull Request — master (#34)
by Márk
11:26 queued 01:17
created

ClassDiscovery   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 144
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Test Coverage

Coverage 100%

Importance

Changes 10
Bugs 2 Features 3
Metric Value
wmc 22
c 10
b 2
f 3
lcom 1
cbo 3
dl 0
loc 144
ccs 24
cts 24
cp 1
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A getPuliFactory() 0 18 4
A setPuliFactory() 0 9 3
A resetPuliFactory() 0 5 1
A getPuliDiscovery() 0 11 2
A findOneByType() 0 19 4
A find() 0 4 1
C evaluateCondition() 0 22 7
1
<?php
2
3
namespace Http\Discovery;
4
5
use Puli\Discovery\Api\Discovery;
6
7
/**
8
 * Registry that based find results on class existence.
9
 *
10
 * @author David de Boer <[email protected]>
11
 * @author Márk Sági-Kazár <[email protected]>
12
 */
13
abstract class ClassDiscovery
14
{
15
    /**
16
     * @var GeneratedPuliFactory
17
     */
18 6
    private static $puliFactory;
19
20 6
    /**
21
     * @var Discovery
22
     */
23 6
    private static $puliDiscovery;
24 6
25 6
    /**
26
     * @return GeneratedPuliFactory
27 6
     */
28 6
    public static function getPuliFactory()
29
    {
30
        if (null === self::$puliFactory) {
31
            if (!defined('PULI_FACTORY_CLASS')) {
32
                throw new \RuntimeException('Puli Factory is not available');
33
            }
34
35
            $puliFactoryClass = PULI_FACTORY_CLASS;
36
37 13
            if (!class_exists($puliFactoryClass)) {
38
                throw new \RuntimeException('Puli Factory class does not exist');
39
            }
40 13
41 1
            self::$puliFactory = new $puliFactoryClass();
42
        }
43
44 13
        return self::$puliFactory;
45 12
    }
46 12
47
    /**
48 12
     * Sets the Puli factory.
49
     *
50 5
     * @param object $puliFactory
51
     */
52 1
    public static function setPuliFactory($puliFactory)
53
    {
54
        if (!is_callable([$puliFactory, 'createRepository']) || !is_callable([$puliFactory, 'createDiscovery'])) {
55
            throw new \InvalidArgumentException('The Puli Factory must expose a repository and a discovery');
56
        }
57
58
        self::$puliFactory = $puliFactory;
59
        self::$puliDiscovery = null;
60
    }
61
62 12
    /**
63
     * Resets the factory.
64 12
     */
65
    public static function resetPuliFactory()
66 9
    {
67 4
        self::$puliFactory = null;
68 1
        self::$puliDiscovery = null;
69 4
    }
70 4
71
    /**
72
     * Returns the Puli discovery layer.
73 1
     *
74
     * @return Discovery
75
     */
76
    public static function getPuliDiscovery()
77
    {
78
        if (!isset(self::$puliDiscovery)) {
79
            $factory = self::getPuliFactory();
80
            $repository = $factory->createRepository();
81
82
            self::$puliDiscovery = $factory->createDiscovery($repository);
83
        }
84
85
        return self::$puliDiscovery;
86
    }
87
88
    /**
89
     * Finds a class.
90
     *
91
     * @param $type
92
     *
93
     * @return string
94
     *
95
     * @throws NotFoundException
96
     */
97
    public static function findOneByType($type)
98
    {
99
        $bindings = self::getPuliDiscovery()->findBindings($type);
100
101
        foreach ($bindings as $binding) {
102
            if ($binding->hasParameterValue('depends')) {
103
                $dependency = $binding->getParameterValue('depends');
104
105
                if (!self::evaluateCondition($dependency)) {
106
                    continue;
107
                }
108
            }
109
110
            // TODO: check class binding
111
            return $binding->getClassName();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Puli\Discovery\Api\Binding\Binding as the method getClassName() does only exist in the following implementations of said interface: Puli\Discovery\Binding\ClassBinding.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
112
        }
113
114
        throw new NotFoundException(sprintf('Binding of type "%s" not found', $type));
115
    }
116
117
    /**
118
     * Finds a resource.
119
     *
120
     * @return object
121
     */
122
    public static function find()
123
    {
124
        throw new \LogicException('Not implemented');
125
    }
126
127
    /**
128
     * Evaulates conditions to boolean.
129
     *
130
     * @param mixed $condition
131
     *
132
     * @return bool
133
     */
134
    protected static function evaluateCondition($condition)
135
    {
136
        if (is_string($condition)) {
137
            // Should be extended for functions, extensions???
138
            return class_exists($condition);
139
        } elseif (is_callable($condition)) {
140
            return $condition();
141
        } elseif (is_bool($condition)) {
142
            return $condition;
143
        } elseif (is_array($condition)) {
144
            $evaluatedCondition = true;
145
146
            // Immediately stop execution if the condition is false
147
            for ($i = 0; $i < count($condition) && false !== $evaluatedCondition; ++$i) {
148
                $evaluatedCondition &= static::evaluateCondition($condition[$i]);
149
            }
150
151
            return $evaluatedCondition;
152
        }
153
154
        return false;
155
    }
156
}
157