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

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