Passed
Pull Request — master (#107)
by Simon
01:43
created

DataObjectAnnotator::setupExtensionClasses()   B

Complexity

Conditions 5
Paths 3

Size

Total Lines 23
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
eloc 9
nc 3
nop 0
dl 0
loc 23
rs 8.5906
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
            $this->extend('beforeDataObjectAnnotator', $this);
74
75
            $this->setupExtensionClasses();
76
77
            $this->permissionChecker = Injector::inst()->get(AnnotatePermissionChecker::class);
78
79
            foreach ($this->permissionChecker->getSupportedParentClasses() as $supportedParentClass) {
80
                $this->setEnabledClasses($supportedParentClass);
81
            }
82
83
            $this->extend('afterDataObjectAnnotator', $this);
84
        }
85
    }
86
87
    /**
88
     * Get all annotatable classes from enabled modules
89
     */
90
    protected function setEnabledClasses($supportedParentClass)
91
    {
92
        foreach ((array)ClassInfo::subclassesFor($supportedParentClass) as $class) {
93
            $classInfo = new AnnotateClassInfo($class);
94
            if ($this->permissionChecker->moduleIsAllowed($classInfo->getModuleName())) {
95
                $this->annotatableClasses[$class] = $classInfo->getClassFilePath();
96
            }
97
        }
98
    }
99
100
    /**
101
     * @return array
102
     */
103
    public static function getExtensionClasses()
104
    {
105
        return self::$extension_classes;
106
    }
107
108
    /**
109
     * @param array $extension_classes
110
     */
111
    public static function setExtensionClasses($extension_classes)
112
    {
113
        self::$extension_classes = $extension_classes;
114
    }
115
116
    /**
117
     * Add another extension class
118
     * @param $extension_class
119
     */
120
    public static function pushExtensionClass($extension_class)
121
    {
122
        if (!in_array($extension_class, self::$extension_classes)) {
123
            self::$extension_classes[] = $extension_class;
124
        }
125
    }
126
127
    /**
128
     * @return boolean
129
     */
130
    public static function isEnabled()
131
    {
132
        return (bool)static::config()->get('enabled');
133
    }
134
135
    /**
136
     * Generate docblock for all subclasses of DataObjects and DataExtenions
137
     * within a module.
138
     *
139
     * @param string $moduleName
140
     * @return bool
141
     * @throws ReflectionException
142
     * @throws NotFoundExceptionInterface
143
     */
144
    public function annotateModule($moduleName)
145
    {
146
        if (!(bool)$moduleName || !$this->permissionChecker->moduleIsAllowed($moduleName)) {
147
            return false;
148
        }
149
150
        $classes = (array)$this->getClassesForModule($moduleName);
151
152
        foreach ($classes as $className => $filePath) {
153
            $this->annotateObject($className);
154
        }
155
156
        return true;
157
    }
158
159
    /**
160
     * @param $moduleName
161
     * @return array
162
     * @throws ReflectionException
163
     */
164
    public function getClassesForModule($moduleName)
165
    {
166
        $classes = [];
167
168
        foreach ($this->annotatableClasses as $class => $filePath) {
169
            $classInfo = new AnnotateClassInfo($class);
170
            if ($moduleName === $classInfo->getModuleName()) {
171
                $classes[$class] = $filePath;
172
            }
173
        }
174
175
        return $classes;
176
    }
177
178
    /**
179
     * Generate docblock for a single subclass of DataObject or DataExtenions
180
     *
181
     * @param string $className
182
     * @return bool
183
     * @throws ReflectionException
184
     * @throws NotFoundExceptionInterface
185
     */
186
    public function annotateObject($className)
187
    {
188
        if (!$this->permissionChecker->classNameIsAllowed($className)) {
189
            return false;
190
        }
191
192
        $this->writeFileContent($className);
193
194
        return true;
195
    }
196
197
    /**
198
     * @param string $className
199
     * @throws LogicException
200
     * @throws InvalidArgumentException
201
     * @throws ReflectionException
202
     */
203
    protected function writeFileContent($className)
204
    {
205
        $classInfo = new AnnotateClassInfo($className);
206
        $filePath = $classInfo->getClassFilePath();
207
208
        if (!is_writable($filePath)) {
209
            DB::alteration_message($className . ' is not writable by ' . get_current_user(), 'error');
210
        } else {
211
            $original = file_get_contents($filePath);
212
            $generated = $this->getGeneratedFileContent($original, $className);
213
214
            // we have a change, so write the new file
215
            if ($generated && $generated !== $original && $className) {
216
                file_put_contents($filePath, $generated);
217
                DB::alteration_message($className . ' Annotated', 'created');
218
            } elseif ($generated === $original && $className) {
219
                DB::alteration_message($className, 'repaired');
220
            }
221
        }
222
    }
223
224
    /**
225
     * Return the complete File content with the newly generated DocBlocks
226
     *
227
     * @param string $fileContent
228
     * @param string $className
229
     * @return mixed
230
     * @throws LogicException
231
     * @throws InvalidArgumentException
232
     * @throws ReflectionException
233
     */
234
    protected function getGeneratedFileContent($fileContent, $className)
235
    {
236
        $generator = new DocBlockGenerator($className);
237
238
        $existing = $generator->getExistingDocBlock();
239
        $generated = $generator->getGeneratedDocBlock();
240
241
        // Trim unneeded whitespaces at the end of lines for PSR-2
242
        $generated = preg_replace('/\s+$/m', '', $generated);
243
244
        if ($existing) {
245
            $fileContent = str_replace($existing, $generated, $fileContent);
246
        } else {
247
            if (class_exists($className)) {
248
                $exploded = explode("\\", $className);
249
                $classNameNew = end($exploded);
250
                $needle = "class {$classNameNew}";
251
                $replace = "{$generated}\nclass {$classNameNew}";
252
                $pos = strpos($fileContent, $needle);
253
                $fileContent = substr_replace($fileContent, $replace, $pos, strlen($needle));
254
            } else {
255
                DB::alteration_message(
256
                    "Could not find string 'class $className'. Please check casing and whitespace.",
257
                    'error'
258
                );
259
            }
260
        }
261
262
        return $fileContent;
263
    }
264
265
    /**
266
     * Named `setup` to not clash with the actual setter
267
     *
268
     * @param $extension_classes
269
     * @throws ReflectionException
270
     */
271
    protected function setupExtensionClasses()
272
    {
273
        $extension_classes = [];
274
275
        $extendableClasses = Config::inst()->getAll();
276
        // We need to check all config to see if the class is extensible
277
        // @todo find a cleaner method, this is already better than previous implementations though
278
        foreach ($extendableClasses as $key => $configClass) {
279
            if (isset($configClass['extensions']) &&
280
                count($configClass['extensions']) > 0 &&
281
                !in_array(self::$extension_classes, $configClass)
282
            ) {
283
                $extension_classes[] = ClassInfo::class_name($key);
284
            }
285
        }
286
287
        // Because the tests re-instantiate the class every time
288
        // We need to make it a unique array
289
        // Also, it's not a bad practice, making sure the array is unique
290
        $extension_classes = array_unique($extension_classes);
291
        // Keep it local until done saves roughly 1 to 2 MB of memory usage.
292
        // Keeping local I guess!
293
        static::$extension_classes = $extension_classes;
294
    }
295
}
296