Completed
Pull Request — master (#107)
by Simon
03:56 queued 44s
created

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