Completed
Pull Request — master (#30)
by Márk
11:32
created

ClassDiscovery   A

Complexity

Total Complexity 13

Size/Duplication

Total Lines 75
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Test Coverage

Coverage 100%

Importance

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

3 Methods

Rating   Name   Duplication   Size   Complexity  
A register() 0 11 2
A find() 0 17 4
C evaluateCondition() 0 22 7
1
<?php
2
3
namespace Http\Discovery;
4
5
/**
6
 * Registry that based find results on class existence.
7
 *
8
 * @author David de Boer <[email protected]>
9
 */
10
abstract class ClassDiscovery
11
{
12
    /**
13
     * Add a class (and condition) to the discovery registry.
14
     *
15
     * @param string $class     Class that will be instantiated if found
16
     * @param string $condition Optional other class to check for existence
17
     */
18 6
    public static function register($class, $condition = null)
19
    {
20 6
        static::$cache = null;
21
22
        $definition = [
23 6
            'class'     => $class,
24 6
            'condition' => isset($condition) ? $condition : $class,
25 6
        ];
26
27 6
        array_unshift(static::$classes, $definition);
28 6
    }
29
30
    /**
31
     * Finds a Class.
32
     *
33
     * @return object
34
     *
35
     * @throws NotFoundException
36
     */
37 13
    public static function find()
38
    {
39
        // We have a cache
40 13
        if (isset(static::$cache)) {
41 1
            return new static::$cache;
42
        }
43
44 13
        foreach (static::$classes as $name => $definition) {
45 12
            if (static::evaluateCondition($definition['condition'])) {
46 12
                static::$cache = $definition['class'];
47
48 12
                return new $definition['class'];
49
            }
50 5
        }
51
52 1
        throw new NotFoundException('Not found');
53
    }
54
55
    /**
56
     * Evaulates conditions to boolean.
57
     *
58
     * @param mixed $condition
59
     *
60
     * @return boolean
61
     */
62 12
    protected static function evaluateCondition($condition)
63
    {
64 12
        if (is_string($condition)) {
65
            // Should be extended for functions, extensions???
66 9
            return class_exists($condition);
67 4
        } elseif (is_callable($condition)) {
68 1
            return $condition();
69 4
        } elseif (is_bool($condition)) {
70 4
            return $condition;
71
        } elseif (is_array($condition)) {
72
            $evaluatedCondition = true;
73 1
74
            // Immediately stop execution if the condition is false
75
            for ($i = 0; $i < count($condition) && false !== $evaluatedCondition; $i++) {
76
                $evaluatedCondition &= static::evaluateCondition($condition[$i]);
77
            }
78
79
            return $evaluatedCondition;
80
        }
81
82
        return false;
83
    }
84
}
85