Issues (8)

src/Autoload/ClassGenerator.php (5 issues)

1
<?php
2
3
namespace PHPKitchen\DI\Autoload;
4
5
use Yii;
6
7
/**
8
 * Represents code generator that can generate virtual class definition of IoC container.
9
 *
10
 * @author Dmitry Kolodko <[email protected]>
11
 */
12
class ClassGenerator {
13
    public function getClassFileNameIfExistOrGenerate($class) {
14
        if ($this->isClassGenerated($class) || ($this->canClassBeGenerated($class) && $this->generateClassFileIfNotExist($class))) {
15
            $fileName = $this->buildClassFileName($class);
16
        } else {
17
            $fileName = false;
18
        }
19
20
        return $fileName;
21
    }
22
23
    protected function canClassBeGenerated($class) {
24
        return $this->extractBaseClassFromDefinitionOf($class) !== false;
25
    }
26
27
    public function generateClassFileIfNotExist($class) {
28
        if ($this->isClassNotGenerated($class)) {
29
            $baseClassName = $this->extractBaseClassFromDefinitionOf($class);
30
            $isClassGenerated = $baseClassName && $this->tryToGenerateClass($class, $baseClassName);
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->tryToGenerateClass($class, $baseClassName) of type integer|false is loosely compared to true; this is ambiguous if the integer can be 0. You might want to explicitly use !== false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
31
        } else {
32
            $isClassGenerated = false;
33
        }
34
35
        return $isClassGenerated;
36
    }
37
38
    public function isClassNotGenerated($class) {
39
        return !$this->isClassGenerated($class);
40
    }
41
42
    public function isClassGenerated($class) {
43
        $classFileName = $this->buildClassFileName($class);
44
45
        return file_exists($classFileName);
46
    }
47
48
    public function buildClassFileName($class) {
49
        $baseClassName = $this->extractBaseClassFromDefinitionOf($class);
50
        $application = $this->getApplication();
51
        $runtimePath = $application ? $application->runtimePath : sys_get_temp_dir();
0 ignored issues
show
The condition $application can never be true.
Loading history...
52
        $fullClassName = str_replace('\\', '_', "{$class}__{$baseClassName}");
53
54
        return "{$runtimePath}/{$fullClassName}.php";
55
    }
56
57
    protected function extractBaseClassFromDefinitionOf($class) {
58
        $container = $this->getContainer();
59
        if (!$container) {
0 ignored issues
show
The condition ! $container can never be false.
Loading history...
60
            return false;
61
        }
62
        $definition = $container->getDefinitionOf($class);
63
        if (is_array($definition) && isset($definition['class'])) {
64
            $baseClassName = $definition['class'];
65
        } elseif (is_string($definition)) {
66
            $baseClassName = $definition;
67
        } else {
68
            $baseClassName = false;
69
        }
70
71
        return $baseClassName;
72
    }
73
74
    protected function tryToGenerateClass($class, $baseClass) {
75
        $classCanBeExtended = $this->checkWhetherClassCanBeExtended($baseClass);
76
77
        return $classCanBeExtended ? $this->generateClassFromTemplate($class, $baseClass) : false;
78
    }
79
80
    protected function checkWhetherClassCanBeExtended($class) {
81
        try {
82
            $baseClassReflection = new \ReflectionClass($class);
83
            $classCanBeExtended = !($baseClassReflection->isFinal() || $baseClassReflection->isInterface());
84
        } catch (\Exception $e) {
85
            $classCanBeExtended = false;
86
        }
87
88
        return $classCanBeExtended;
89
    }
90
91
    protected function generateClassFromTemplate($class, $baseClass) {
92
        $templateParams = $this->prepareTemplateParams($class, $baseClass);
93
        $classContent = $this->renderTemplate($templateParams);
94
95
        return file_put_contents($this->buildClassFileName($class), $classContent);
96
    }
97
98
    protected function prepareTemplateParams($class, $baseClass) {
99
        $delimiterBeforeClassNamePosition = strrpos($class, '\\');
100
        if ($delimiterBeforeClassNamePosition !== false) {
0 ignored issues
show
The condition $delimiterBeforeClassNamePosition !== false can never be false.
Loading history...
101
            $namespaceName = substr($class, 0, $delimiterBeforeClassNamePosition);
102
            $className = substr($class, $delimiterBeforeClassNamePosition + 1);
103
        } else {
104
            $namespaceName = false;
105
            $className = $class;
106
        }
107
108
        return compact('className', 'namespaceName', 'baseClass');
109
    }
110
111
    protected function renderTemplate($params) {
112
        ob_start();
113
        ob_implicit_flush(false);
0 ignored issues
show
false of type false is incompatible with the type integer expected by parameter $flag of ob_implicit_flush(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

113
        ob_implicit_flush(/** @scrutinizer ignore-type */ false);
Loading history...
114
        extract($params, EXTR_OVERWRITE);
115
        require __DIR__ . '/class-template.php';
116
117
        return ob_get_clean();
118
    }
119
120
    /**
121
     * @return \PHPKitchen\DI\Container
122
     */
123
    protected function getContainer() {
124
        return Yii::$container;
125
    }
126
127
    protected function getApplication() {
128
        return Yii::$app;
129
    }
130
}