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