Completed
Pull Request — master (#107)
by Simon
01:44
created

DataObjectAnnotator::setExtensionClasses()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace SilverLeague\IDEAnnotator;
4
5
use InvalidArgumentException;
6
use LogicException;
7
use Psr\Container\NotFoundExceptionInterface;
8
use ReflectionException;
9
use SilverStripe\Control\Director;
10
use SilverStripe\Core\ClassInfo;
11
use SilverStripe\Core\Config\Config;
12
use SilverStripe\Core\Config\Configurable;
13
use SilverStripe\Core\Extensible;
14
use SilverStripe\Core\Injector\Injectable;
15
use SilverStripe\Core\Injector\Injector;
16
use SilverStripe\ORM\DB;
17
18
/**
19
 * Class DataObjectAnnotator
20
 * Generates phpdoc annotations for database fields and orm relations
21
 * so IDE's with autocompletion and property inspection will recognize properties and relation methods.
22
 *
23
 * The annotations can be generated with dev/build with @see Annotatable
24
 * and from the @see DataObjectAnnotatorTask
25
 *
26
 * The generation is disabled by default.
27
 * It is advisable to only enable it in your local dev environment,
28
 * so the files won't change on a production server when you run dev/build
29
 *
30
 * @package IDEAnnotator/Core
31
 */
32
class DataObjectAnnotator
33
{
34
    use Injectable;
35
    use Configurable;
36
    use Extensible;
37
38
    /**
39
     * All classes that subclass Object
40
     * @var array
41
     */
42
    protected static $extension_classes = [];
43
    /**
44
     * @config
45
     * Enable generation from @see Annotatable and @see DataObjectAnnotatorTask
46
     * @var bool
47
     */
48
    private static $enabled = false;
0 ignored issues
show
introduced by
The private property $enabled is not used, and could be removed.
Loading history...
49
    /**
50
     * @config
51
     * Enable modules that are allowed to have generated docblocks for DataObjects and DataExtensions
52
     * @var array
53
     */
54
    private static $enabled_modules = ['mysite'];
0 ignored issues
show
introduced by
The private property $enabled_modules is not used, and could be removed.
Loading history...
55
    /**
56
     * @var AnnotatePermissionChecker
57
     */
58
    private $permissionChecker;
59
    /**
60
     * @var array
61
     */
62
    private $annotatableClasses = [];
63
64
    /**
65
     * DataObjectAnnotator constructor.
66
     * @throws NotFoundExceptionInterface
67
     * @throws ReflectionException
68
     */
69
    public function __construct()
70
    {
71
        // Don't instantiate anything if annotations are not enabled.
72
        if (static::config()->get('enabled') === true && Director::isDev()) {
73
            $extendableClasses = Config::inst()->getAll();
74
            // We need to check all config to see if the class is extensible
75
            // @todo find a cleaner method, this is already better than previous implementations though
76
            foreach ($extendableClasses as $key => $configClass) {
77
                if (isset($configClass['extensions']) &&
78
                    count($configClass['extensions']) > 0 &&
79
                    !in_array(self::$extension_classes, $configClass)
80
                ) {
81
                    $extension_classes[] = ClassInfo::class_name($key);
82
                }
83
            }
84
85
            // Because the tests re-instantiate the class every time
86
            // We need to make it a unique array
87
            // Also, it's not a bad practice, making sure the array is unique
88
            $extension_classes = array_unique($extension_classes);
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable $extension_classes does not seem to be defined for all execution paths leading up to this point.
Loading history...
89
            // Keep it local until done saves roughly 1 to 2 MB of memory usage.
90
            // Keeping local I guess!
91
            static::$extension_classes = $extension_classes;
92
93
            $this->permissionChecker = Injector::inst()->get(AnnotatePermissionChecker::class);
94
            foreach ($this->permissionChecker->getSupportedParentClasses() as $supportedParentClass) {
95
                $this->setEnabledClasses($supportedParentClass);
96
            }
97
        }
98
    }
99
100
    /**
101
     * Get all annotatable classes from enabled modules
102
     */
103
    protected function setEnabledClasses($supportedParentClass)
104
    {
105
        foreach ((array)ClassInfo::subclassesFor($supportedParentClass) as $class) {
106
            $classInfo = new AnnotateClassInfo($class);
107
            if ($this->permissionChecker->moduleIsAllowed($classInfo->getModuleName())) {
108
                $this->annotatableClasses[$class] = $classInfo->getClassFilePath();
109
            }
110
        }
111
    }
112
113
    /**
114
     * @return array
115
     */
116
    public static function getExtensionClasses()
117
    {
118
        return self::$extension_classes;
119
    }
120
121
    /**
122
     * @param array $extension_classes
123
     */
124
    public static function setExtensionClasses($extension_classes)
125
    {
126
        self::$extension_classes = $extension_classes;
127
    }
128
129
    /**
130
     * Add another extension class
131
     * @param $extension_class
132
     */
133
    public static function pushExtensionClass($extension_class)
134
    {
135
        if (!in_array($extension_class, self::$extension_classes)) {
136
            self::$extension_classes[] = $extension_class;
137
        }
138
    }
139
140
    /**
141
     * @return boolean
142
     */
143
    public static function isEnabled()
144
    {
145
        return (bool)static::config()->get('enabled');
146
    }
147
148
    /**
149
     * Generate docblock for all subclasses of DataObjects and DataExtenions
150
     * within a module.
151
     *
152
     * @param string $moduleName
153
     * @return bool
154
     * @throws ReflectionException
155
     * @throws NotFoundExceptionInterface
156
     */
157
    public function annotateModule($moduleName)
158
    {
159
        if (!(bool)$moduleName || !$this->permissionChecker->moduleIsAllowed($moduleName)) {
160
            return false;
161
        }
162
163
        $classes = (array)$this->getClassesForModule($moduleName);
164
165
        foreach ($classes as $className => $filePath) {
166
            $this->annotateObject($className);
167
        }
168
169
        return true;
170
    }
171
172
    /**
173
     * @param $moduleName
174
     * @return array
175
     * @throws ReflectionException
176
     */
177
    public function getClassesForModule($moduleName)
178
    {
179
        $classes = [];
180
181
        foreach ($this->annotatableClasses as $class => $filePath) {
182
            $classInfo = new AnnotateClassInfo($class);
183
            if ($moduleName === $classInfo->getModuleName()) {
184
                $classes[$class] = $filePath;
185
            }
186
        }
187
188
        return $classes;
189
    }
190
191
    /**
192
     * Generate docblock for a single subclass of DataObject or DataExtenions
193
     *
194
     * @param string $className
195
     * @return bool
196
     * @throws ReflectionException
197
     * @throws NotFoundExceptionInterface
198
     */
199
    public function annotateObject($className)
200
    {
201
        if (!$this->permissionChecker->classNameIsAllowed($className)) {
202
            return false;
203
        }
204
205
        $this->writeFileContent($className);
206
207
        return true;
208
    }
209
210
    /**
211
     * @param string $className
212
     * @throws LogicException
213
     * @throws InvalidArgumentException
214
     * @throws ReflectionException
215
     */
216
    protected function writeFileContent($className)
217
    {
218
        $classInfo = new AnnotateClassInfo($className);
219
        $filePath = $classInfo->getClassFilePath();
220
221
        if (!is_writable($filePath)) {
222
            DB::alteration_message($className . ' is not writable by ' . get_current_user(), 'error');
223
        } else {
224
            $original = file_get_contents($filePath);
225
            $generated = $this->getGeneratedFileContent($original, $className);
226
227
            // we have a change, so write the new file
228
            if ($generated && $generated !== $original && $className) {
229
                file_put_contents($filePath, $generated);
230
                DB::alteration_message($className . ' Annotated', 'created');
231
            } elseif ($generated === $original && $className) {
232
                DB::alteration_message($className, 'repaired');
233
            }
234
        }
235
    }
236
237
    /**
238
     * Return the complete File content with the newly generated DocBlocks
239
     *
240
     * @param string $fileContent
241
     * @param string $className
242
     * @return mixed
243
     * @throws LogicException
244
     * @throws InvalidArgumentException
245
     * @throws ReflectionException
246
     */
247
    protected function getGeneratedFileContent($fileContent, $className)
248
    {
249
        $generator = new DocBlockGenerator($className);
250
251
        $existing = $generator->getExistingDocBlock();
252
        $generated = $generator->getGeneratedDocBlock();
253
254
        // Trim unneeded whitespaces at the end of lines for PSR-2
255
        $generated = preg_replace('/\s+$/m', '', $generated);
256
257
        if ($existing) {
258
            $fileContent = str_replace($existing, $generated, $fileContent);
259
        } else {
260
            $needle = "class {$className}";
261
            $replace = "{$generated}\nclass {$className}";
262
            $pos = strpos($fileContent, $needle);
263
            if ($pos !== false) {
0 ignored issues
show
introduced by
The condition $pos !== false can never be false.
Loading history...
264
                $fileContent = substr_replace($fileContent, $replace, $pos, strlen($needle));
265
            } else {
266
                if (strrpos($className, "\\") !== false && class_exists($className)) {
267
                    $exploded = explode("\\", $className);
268
                    $classNameNew = end($exploded);
269
                    $needle = "class {$classNameNew}";
270
                    $replace = "{$generated}\nclass {$classNameNew}";
271
                    $pos = strpos($fileContent, $needle);
272
                    $fileContent = substr_replace($fileContent, $replace, $pos, strlen($needle));
273
                } else {
274
                    DB::alteration_message(
275
                        "Could not find string 'class $className'. Please check casing and whitespace.",
276
                        'error'
277
                    );
278
                }
279
            }
280
        }
281
282
        return $fileContent;
283
    }
284
}
285