Completed
Push — master ( e82275...7671fb )
by Vitaly
02:06
created

Generator::analyze()   C

Complexity

Conditions 8
Paths 7

Size

Total Lines 40
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 22
CRAP Score 8

Importance

Changes 7
Bugs 1 Features 4
Metric Value
c 7
b 1
f 4
dl 0
loc 40
ccs 22
cts 22
cp 1
rs 5.3846
cc 8
eloc 19
nc 7
nop 1
crap 8
1
<?php
2
/**
3
 * Created by Vitaly Iegorov <[email protected]>.
4
 * on 18.02.16 at 14:17
5
 */
6
namespace samsonframework\view;
7
8
use samsonframework\view\exception\GeneratedViewPathHasReservedWord;
9
10
/**
11
 * Views generator, this class scans resource for view files and creates
12
 * appropriate View class ancestors with namespace as relative view location
13
 * and file name as View class name ending with "View".
14
 *
15
 * Generator also analyzes view files content and creates protected class field
16
 * members for every variable used inside with chainable setter for this field,
17
 * to help IDE and developer in creating awesome code.
18
 *
19
 * TODO: Check for reserved keywords(like list) in namespaces
20
 * TODO: Somehow know view variable type(typehint??) and add comments and type-hints to generated classes.
21
 * TODO: Clever analysis for foreach, if, and so on language structures, we do not need to create variables for loop iterator.
22
 * TODO: If a variable is used in foreach - this is an array or Iteratable ancestor - we can add typehint automatically
23
 * TODO: Analyze view file php doc comments to get variable types
24
 * TODO: If a token variable is not $this and has "->" - this is object, maybe type-hint needs to be added.
25
 * TODO: Add caching logic to avoid duplicate file reading
26
 * TODO: Do not generate class fields with empty values
27
 * TODO: Generate constants with field names
28
 *
29
 * @package samsonframework\view
30
 */
31
class Generator
32
{
33
    /** string All generated view classes will end with this suffix */
34
    const VIEW_CLASSNAME_SUFFIX = 'View';
35
36
    /** @var array Collection of PHP reserved words */
37
    protected static $reservedWords = array('list');
38
39
    /** @var Metadata[] Collection of view metadata */
40
    protected $metadata = array();
41
42
    /** @var \samsonphp\generator\Generator */
43
    protected $generator;
44
45
    /** @var string Generated classes namespace prefix */
46
    protected $namespacePrefix;
47
48
    /** @var string Collection of namespace parts to be ignored in generated namespaces */
49
    protected $ignoreNamespace = array();
50
51
    /** @var array Collection of view files */
52
    protected $files = array();
53
54
    /** @var string Scanning entry path */
55
    protected $entryPath;
56
57
    /**
58
     * Generator constructor.
59
     *
60
     * @param \samsonphp\generator\Generator $generator
61
     * @param string                         $namespacePrefix
62
     * @param array                          $ignoreNamespace
63
     */
64 3
    public function __construct(\samsonphp\generator\Generator $generator, $namespacePrefix, array $ignoreNamespace = array())
65
    {
66 3
        $this->generator = $generator;
67 3
        $this->ignoreNamespace = $ignoreNamespace;
0 ignored issues
show
Documentation Bug introduced by
It seems like $ignoreNamespace of type array is incompatible with the declared type string of property $ignoreNamespace.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
68 3
        $this->namespacePrefix = rtrim(ltrim($namespacePrefix, '\\'), '\\').'\\';
69 3
    }
70
71
    /**
72
     * Change variable name to camel caps format.
73
     *
74
     * @param string $variable
75
     *
76
     * @return string Changed variable name
77
     */
78 1
    public function changeName($variable)
79
    {
80 1
        return lcfirst(
81 1
            implode(
82 1
                '',
83 1
                array_map(
84
                    function ($element) { return ucfirst($element);},
0 ignored issues
show
Coding Style introduced by
Opening brace must be the last content on the line
Loading history...
85 1
                    explode('_', $variable)
86 1
                )
87 1
            )
88 1
        );
89
    }
90
91
    /**
92
     * Recursively scan path for files with specified extensions.
93
     *
94
     * @param string $source     Entry point path
95
     * @param string $path       Entry path for scanning
96
     * @param array  $extensions Collection of file extensions without dot
97
     */
98 3
    public function scan($source, array $extensions = array(View::DEFAULT_EXT), $path = null)
99
    {
100 3
        $this->entryPath = $source;
101
102 3
        $path = isset($path) ? $path : $source;
103
104
        // Recursively go deeper into inner folders for scanning
105 3
        $folders  = glob($path.'/*', GLOB_ONLYDIR);
106 3
        foreach ($folders as $folder) {
107 3
            $this->scan($source, $extensions, $folder);
108 3
        }
109
110
        // Iterate file extensions
111 3
        foreach ($extensions as $extension) {
112 3
            foreach (glob(rtrim($path, '/') . '/*.'.$extension) as $file) {
113 3
                $this->files[str_replace($source, '', $file)] = $file;
114 3
            }
115 3
        }
116 3
    }
117
118
    /**
119
     * Analyze view file and create its metadata.
120
     *
121
     * @param string $file Path to view file
122
     *
123
     * @return Metadata View file metadata
124
     */
125 2
    public function analyze($file)
126
    {
127 2
        $metadata = new Metadata();
128
        // Use PHP tokenizer to find variables
129 2
        foreach ($tokens = token_get_all(file_get_contents($file)) as $idx => $token) {
130 2
            if (!is_string($token) && $token[0] === T_VARIABLE) {
131
                // Store variable
132 1
                $variableText = $token[1];
133
                // Store variable name
134 1
                $variableName = ltrim($token[1], '$');
135
                // If next token is object operator
136 1
                if ($tokens[$idx + 1][0] === T_OBJECT_OPERATOR) {
137
                    // Ignore $this
138 1
                    if ($variableName === 'this') {
139 1
                        continue;
140
                    }
141
142
                    // And two more tokens
143 1
                    $variableText .= $tokens[$idx + 1][1] . $tokens[$idx + 2][1];
144
145
                    // Store object variable
146 1
                    $metadata->variables[$this->changeName($variableName)] = $variableText;
147
                    // Store view variable key - actual object name => full variable usage
148 1
                    $metadata->originalVariables[$this->changeName($variableName)] = $variableName;
149 1
                } else {
150
                    // Store original variable name
151 1
                    $metadata->originalVariables[$this->changeName($variableName)] = $variableName;
152
                    // Store view variable key - actual object name => full variable usage
153 1
                    $metadata->variables[$this->changeName($variableName)] = $variableText;
154
                }
155 2
            } elseif ($token[0] === T_DOC_COMMENT) { // Match doc block comments
156
                // Parse variable type and name
157 2
                if (preg_match('/@var\s+(?<type>[^ ]+)\s+(?<variable>[^*]+)/', $token[1], $matches)) {
158 1
                    $metadata->types[substr(trim($matches['variable']), 1)] = $matches['type'];
159 1
                }
160 2
            }
161 2
        }
162
163 2
        return $metadata;
164
    }
165
166
    /**
167
     * Generic class name and its name space generator.
168
     *
169
     * @param string $file      Full path to view file
170
     * @param string $entryPath Entry path
171
     *
172
     * @return array Class name[0] and namespace[1]
173
     * @throws GeneratedViewPathHasReservedWord
174
     */
175 2
    protected function generateClassName($file, $entryPath)
176
    {
177
        // Get only file name as a class name with suffix
178 2
        $className = ucfirst(pathinfo($file, PATHINFO_FILENAME) . self::VIEW_CLASSNAME_SUFFIX);
179
180
        // Get namespace as part of file path relatively to entry path
181 2
        $nameSpace = rtrim(ltrim(
182 2
            str_replace(
183 2
                '/',
184 2
                '\\',
185 2
                str_replace($entryPath, '', pathinfo($file, PATHINFO_DIRNAME))
186 2
            ),
187
            '\\'
188 2
        ), '\\');
189
190
        // Remove ignored parts from namespaces
191 2
        $nameSpace = str_replace($this->ignoreNamespace, '', $nameSpace);
192
193
        // Check generated namespaces
194 2
        foreach (static::$reservedWords as $reservedWord) {
195 2
            if (strpos($nameSpace, '\\' . $reservedWord) !== false) {
196 1
                throw new GeneratedViewPathHasReservedWord($file.'('.$reservedWord.')');
197
            }
198 1
        }
199
200
        // Return collection for further usage
201 1
        return array($className, rtrim($this->namespacePrefix . $nameSpace, '\\'));
202
    }
203
204
    /**
205
     * Generate view classes.
206
     *
207
     * @param string $path Entry path for generated classes and folders
208
     */
209 2
    public function generate($path = __DIR__)
210
    {
211 2
        foreach ($this->files as $relativePath => $absolutePath) {
212 2
            $this->metadata[$absolutePath] = $this->analyze($absolutePath);
213 2
            $this->metadata[$absolutePath]->path = $absolutePath;
214 1
            list($this->metadata[$absolutePath]->className,
215 2
                $this->metadata[$absolutePath]->namespace) = $this->generateClassName($absolutePath, $this->entryPath);
216 1
        }
217
218 1
        foreach ($this->metadata as $metadata) {
219 1
            $this->generateViewClass($metadata, $path);
220 1
        }
221 1
    }
222
223
    /** @return string Hash representing generator state */
224 1
    public function hash()
225
    {
226 1
        $hash = '';
227 1
        foreach ($this->files as $relativePath => $absolutePath) {
228 1
            $hash .= $relativePath.filemtime($absolutePath);
229 1
        }
230
231 1
        return md5($hash);
232
    }
233
234
    /**
235
     * Create View class ancestor.
236
     *
237
     * @param Metadata $metadata View file metadata
238
     * @param string   $path Entry path for generated classes and folders
239
     */
240 1
    protected function generateViewClass(Metadata $metadata, $path)
241
    {
242 1
        $this->generator
0 ignored issues
show
Bug introduced by
The method defnamespace() cannot be called from this context as it is declared private in class samsonphp\generator\Generator.

This check looks for access to methods that are not accessible from the current context.

If you need to make a method accessible to another context you can raise its visibility level in the defining class.

Loading history...
243 1
            ->defNamespace($metadata->namespace)
244 1
            ->multiComment(array('Class for view "'.$metadata->path.'" rendering'))
245 1
            ->defClass($metadata->className, '\\' . View::class)
246 1
            ->commentVar('string', 'Path to view file')
247 1
            ->defClassVar('$file', 'protected', $metadata->path)
248
            //->commentVar('array', 'Collection of view variables')
249
            //->defClassVar('$variables', 'public static', array_keys($metadata->variables))
250
            //->commentVar('array', 'Collection of view variable types')
251
            //->defClassVar('$types', 'public static', $metadata->types)
252
        ;
253
254
        // Iterate all view variables
255 1
        foreach (array_keys($metadata->variables) as $name) {
256 1
            $type = array_key_exists($name, $metadata->types) ? $metadata->types[$name] : 'mixed';
257 1
            $this->generator
258 1
                ->commentVar($type, 'View variable')
259 1
                ->defClassVar('$'.$name, 'public')
260 1
                ->text($this->generateViewVariableSetter(
261 1
                    $name,
262 1
                    $metadata->originalVariables[$name],
263
                    $type
264 1
                ));
265 1
        }
266
267
        // Iterate namespace and create folder structure
268 1
        $path .= '/'.str_replace('\\', '/', $metadata->namespace);
269 1
        if (!is_dir($path)) {
270 1
            mkdir($path, 0775, true);
271 1
        }
272
273 1
        file_put_contents(
274 1
            $path.'/'.$metadata->className.'.php',
275 1
            '<?php'.$this->generator->endClass()->flush()
276 1
        );
277 1
    }
278
279
    /**
280
     * Generate constructor for application class.
281
     *
282
     * @param string $variable View variable name
283
     * @param string $original Original view variable name
284
     * @param string $type Variable type
285
     *
286
     * @return string View variable setter method
287
     */
288 1
    protected function generateViewVariableSetter($variable, $original, $type = 'mixed')
289
    {
290 1
        $class = "\n\t" . '/**';
291 1
        $class .= "\n\t" . ' * Setter for ' . $variable . ' view variable';
292 1
        $class .= "\n\t" . ' *';
293 1
        $class .= "\n\t" . ' * @param '.$type.' $value View variable value';
294 1
        $class .= "\n\t" . ' * @return $this Chaining';
295 1
        $class .= "\n\t" . ' */';
296 1
        $class .= "\n\t" . 'public function ' . $variable . '($value)';
297 1
        $class .= "\n\t" . '{';
298 1
        $class .= "\n\t\t" . 'return parent::set($value, \'' . $original . '\');';
299 1
        $class .= "\n\t" . '}' . "\n";
300
301 1
        return $class;
302
    }
303
}
304