Completed
Pull Request — master (#34)
by Márk
02:24
created

ClassDiscovery::find()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 4
Bugs 1 Features 2
Metric Value
c 4
b 1
f 2
dl 0
loc 4
ccs 0
cts 2
cp 0
rs 10
cc 1
eloc 2
nc 1
nop 0
crap 2
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
    private static $puliFactory;
19
20
    /**
21
     * @var Discovery
22
     */
23
    private static $puliDiscovery;
24
25
    /**
26
     * @return GeneratedPuliFactory
27
     */
28 10
    public static function getPuliFactory()
29
    {
30 10
        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
            if (!class_exists($puliFactoryClass)) {
38
                throw new \RuntimeException('Puli Factory class does not exist');
39
            }
40
41
            self::$puliFactory = new $puliFactoryClass();
42
        }
43
44 10
        return self::$puliFactory;
45
    }
46
47
    /**
48
     * Sets the Puli factory.
49
     *
50
     * @param object $puliFactory
51
     */
52 21
    public static function setPuliFactory($puliFactory)
53
    {
54 21
        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 21
        self::$puliFactory = $puliFactory;
59 21
        self::$puliDiscovery = null;
60 21
    }
61
62
    /**
63
     * Resets the factory.
64
     */
65 21
    public static function resetPuliFactory()
66
    {
67 21
        self::$puliFactory = null;
68 21
        self::$puliDiscovery = null;
69 21
    }
70
71
    /**
72
     * Returns the Puli discovery layer.
73
     *
74
     * @return Discovery
75
     */
76 9
    public static function getPuliDiscovery()
77
    {
78 9
        if (!isset(self::$puliDiscovery)) {
79 9
            $factory = self::getPuliFactory();
80 9
            $repository = $factory->createRepository();
81
82 9
            self::$puliDiscovery = $factory->createDiscovery($repository);
83 9
        }
84
85 9
        return self::$puliDiscovery;
86
    }
87
88
    /**
89
     * Finds a class.
90
     *
91
     * @param $type
92
     *
93
     * @return string
94
     *
95
     * @throws NotFoundException
96
     */
97 8
    public static function findOneByType($type)
98
    {
99 8
        $bindings = self::getPuliDiscovery()->findBindings($type);
100
101 8
        foreach ($bindings as $binding) {
102 7
            if ($binding->hasParameterValue('depends')) {
103 1
                $dependency = $binding->getParameterValue('depends');
104
105 1
                if (!self::evaluateCondition($dependency)) {
106 1
                    continue;
107
                }
108
            }
109
110
            // TODO: check class binding
111 7
            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 1
        }
113
114 1
        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 1
    protected static function evaluateCondition($condition)
135
    {
136 1
        if (is_string($condition)) {
137
            // Should be extended for functions, extensions???
138
            return class_exists($condition);
139 1
        } elseif (is_callable($condition)) {
140
            return $condition();
141 1
        } elseif (is_bool($condition)) {
142 1
            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