Completed
Push — master ( 61e583...27bd14 )
by Vitaly
09:33 queued 07:34
created

Generator::scan()   B

Complexity

Conditions 5
Paths 12

Size

Total Lines 20
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 1
Metric Value
c 4
b 0
f 1
dl 0
loc 20
rs 8.8571
cc 5
eloc 11
nc 12
nop 3
1
<?php
2
/**
3
 * Created by Vitaly Iegorov <[email protected]>.
4
 * on 18.02.16 at 14:17
5
 */
6
namespace samsonframework\view;
7
use samsonframework\view\exception\GeneratedViewPathHasReservedWord;
8
9
/**
10
 * Views generator, this class scans resource for view files and creates
11
 * appropriate View class ancestors with namespace as relative view location
12
 * and file name as View class name ending with "View".
13
 *
14
 * Generator also analyzes view files content and creates protected class field
15
 * members for every variable used inside with chainable setter for this field,
16
 * to help IDE and developer in creating awesome code.
17
 *
18
 * TODO: Check for reserved keywords(like list) in namespaces
19
 * TODO: Somehow know view variable type(typehint??) and add comments and type-hints to generated classes.
20
 * TODO: Clever analysis for foreach, if, and so on language structures, we do not need to create variables for loop iterator.
21
 * TODO: If a variable is used in foreach - this is an array or Iteratable ancestor - we can add typehint automatically
22
 * TODO: Analyze view file php doc comments to get variable types
23
 * TODO: If a token variable is not $this and has "->" - this is object, maybe type-hint needs to be added.
24
 * TODO: Add caching logic to avoid duplicate file reading
25
 *
26
 * @package samsonframework\view
27
 */
28
class Generator
29
{
30
    /** string All generated view classes will end with this suffix */
31
    const VIEW_CLASSNAME_SUFFIX = 'View';
32
33
    /** @var array Collection of PHP reserved words */
34
    protected static $reservedWords = array(
35
        'list'
36
    );
37
38
    /** @var Metadata[] Collection of view metadata */
39
    protected $metadata = array();
40
41
    /** @var \samsonphp\generator\Generator */
42
    protected $generator;
43
44
    /** @var string Generated classes namespace prefix */
45
    protected $namespacePrefix;
46
47
    /**
48
     * Generator constructor.
49
     *
50
     * @param \samsonphp\generator\Generator $generator
51
     * @param string                               $namespacePrefix
52
     */
53
    public function __construct(\samsonphp\generator\Generator $generator, $namespacePrefix)
54
    {
55
        $this->generator = $generator;
56
        $this->namespacePrefix = ltrim($namespacePrefix, '\\');
57
    }
58
59
    /**
60
     * Recursively scan path for files with specified extensions.
61
     *
62
     * @param string $path       Entry path for scanning
63
     * @param array  $extensions Collection of file extensions without dot
64
     * @param string $sourcepath Entry point path
65
     */
66
    public function scan($sourcepath, array $extensions = array(View::DEFAULT_EXT), $path = null)
67
    {
68
        $path = isset($path) ? $path : $sourcepath;
69
70
        // Recursively go deeper into inner folders for scanning
71
        $folders  = glob($path.'/*', GLOB_ONLYDIR);
72
        foreach ($folders as $folder) {
73
            $this->scan($folder, $extensions, $sourcepath);
74
        }
75
76
        // Iterate file extensions
77
        foreach ($extensions as $extension) {
78
            foreach (glob(rtrim($path, '/') . '/*.'.$extension) as $file) {
79
                $this->metadata[$file] = $this->analyze($file);
80
                $this->metadata[$file]->path = str_replace($sourcepath, '', $file);
81
                list($this->metadata[$file]->className,
82
                    $this->metadata[$file]->namespace) = $this->generateClassName($file, $sourcepath);
83
            }
84
        }
85
    }
86
87
    /**
88
     * Analyze view file and create its metadata.
89
     *
90
     * @param string $file Path to view file
91
     *
92
     * @return Metadata View file metadata
93
     */
94
    public function analyze($file)
95
    {
96
        $metadata = new Metadata();
97
        // Use PHP tokenizer to find variables
98
        foreach ($tokens = token_get_all(file_get_contents($file)) as $idx => $token) {
99
            if (!is_string($token) && $token[0] === T_VARIABLE) {
100
                // Store variable
101
                $variableText = $token[1];
102
                // Store variable name
103
                $variableName = ltrim($token[1], '$');
104
                // If next token is object operator
105
                if ($tokens[$idx + 1][0] === T_OBJECT_OPERATOR) {
106
                    $variableName = $tokens[$idx + 2][1];
107
                    // And two more tokens
108
                    $variableText .= $tokens[$idx + 1][1] . $variableName;
109
                }
110
                // Store view variable key - actual object name => full varaible usage
111
                $metadata->variables[$variableName] = $variableText;
112
            }
113
        }
114
115
        return $metadata;
116
    }
117
118
    /**
119
     * Generic class name and its name space generator.
120
     *
121
     * @param string $file      Full path to view file
122
     * @param string $entryPath Entry path
123
     *
124
     * @return array Class name[0] and namespace[1]
125
     */
126
    protected function generateClassName($file, $entryPath)
127
    {
128
        // Get only file name as a class name with suffix
129
        $className = pathinfo($file, PATHINFO_FILENAME) . self::VIEW_CLASSNAME_SUFFIX;
130
131
        // Get namespace as part of file path relatively to entry path
132
        $nameSpace = rtrim(ltrim(
133
            str_replace(
134
                '/',
135
                '\\',
136
                str_replace($entryPath, '', pathinfo($file, PATHINFO_DIRNAME))
137
            ),
138
            '\\'
139
        ), '\\');
140
141
        // Check generated namespaces
142
        foreach (static::$reservedWords as $reserverWord) {
143
            if (strpos($nameSpace, '\\' . $reserverWord) !== false) {
144
                throw new GeneratedViewPathHasReservedWord($reserverWord);
145
            }
146
        }
147
148
        // Return collection for further usage
149
        return array($className, rtrim($this->namespacePrefix . $nameSpace, '\\'));
150
    }
151
152
    public function generate($path = __DIR__)
153
    {
154
        foreach ($this->metadata as $metadata) {
155
            $this->generateViewClass($metadata, $path);
156
        }
157
    }
158
159
    protected function generateViewClass(Metadata $metadata, $path)
160
    {
161
        $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...
162
            ->defNamespace($metadata->namespace)
163
            ->multiComment(array('Class for view "'.$metadata->path.'" rendering'))
164
            ->defClass($metadata->className, '\\'.View::class)
165
            ->commentVar('string', 'Path to view file')
166
            ->defClassVar('$path', 'protected', $metadata->path)
167
            ->commentVar('array', 'Collection of view variables')
168
            ->defClassVar('$variables', 'public static', array_keys($metadata->variables));
0 ignored issues
show
Documentation introduced by
array_keys($metadata->variables) is of type array<integer,integer|string>, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
169
170
        // Iterate all view variables
171
        foreach (array_keys($metadata->variables) as $name) {
172
            $this->generator
173
                ->commentVar('mixed', 'View variable')
174
                ->defClassVar('$'.$name, 'public')
175
                ->text($this->generateViewVariableSetter($name));
176
        }
177
178
        file_put_contents(
179
            $path.'/'.$metadata->className.'.php',
180
            '<?php'.$this->generator->endClass()->flush()
181
        );
182
    }
183
184
    /**
185
     * Generate constructor for application class.
186
     *
187
     * @param string $variable View variable name
188
     *
189
     * @return string View variable setter method
190
     */
191
    protected function generateViewVariableSetter($variable)
192
    {
193
        $class = "\n\t" . '/**';
194
        $class .= "\n\t" . ' * Setter for ' . $variable . ' view variable';
195
        $class .= "\n\t" . ' *';
196
        $class .= "\n\t" . ' * @param mixed $value View variable value';
197
        $class .= "\n\t" . ' * @return $this Chaining';
198
        $class .= "\n\t" . ' */';
199
        $class .= "\n\t" . 'public function ' . $variable . '($value)';
200
        $class .= "\n\t" . '{';
201
        $class .= "\n\t\t" . 'return parent::set($value, \'' . $variable . '\');';
202
        $class .= "\n\t" . '}' . "\n";
203
204
        return $class;
205
    }
206
}
207