Completed
Push — master ( 6c70b0...61e583 )
by Vitaly
09:31 queued 07:32
created

Generator::generateClassName()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 25
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 3
Metric Value
c 4
b 0
f 3
dl 0
loc 25
rs 8.8571
cc 3
eloc 13
nc 3
nop 2
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($path, array $extensions = array(View::DEFAULT_EXT), $sourcepath)
0 ignored issues
show
Coding Style introduced by
Parameters which have default values should be placed at the end.

If you place a parameter with a default value before a parameter with a default value, the default value of the first parameter will never be used as it will always need to be passed anyway:

// $a must always be passed; it's default value is never used.
function someFunction($a = 5, $b) { }
Loading history...
67
    {
68
        // Recursively go deeper into inner folders for scanning
69
        $folders  = glob($path.'/*', GLOB_ONLYDIR);
70
        foreach ($folders as $folder) {
71
            $this->scan($folder, $extensions, $sourcepath);
72
        }
73
74
        // Iterate file extensions
75
        foreach ($extensions as $extension) {
76
            foreach (glob(rtrim($path, '/') . '/*.'.$extension) as $file) {
77
                $this->metadata[$file] = $this->analyze($file);
78
                $this->metadata[$file]->path = str_replace($sourcepath, '', $file);
79
                list($this->metadata[$file]->className,
80
                    $this->metadata[$file]->namespace) = $this->generateClassName($file, $sourcepath);
81
            }
82
        }
83
    }
84
85
    /**
86
     * Analyze view file and create its metadata.
87
     *
88
     * @param string $file Path to view file
89
     *
90
     * @return Metadata View file metadata
91
     */
92
    public function analyze($file)
93
    {
94
        $metadata = new Metadata();
95
        // Use PHP tokenizer to find variables
96
        foreach ($tokens = token_get_all(file_get_contents($file)) as $idx => $token) {
97
            if (!is_string($token) && $token[0] === T_VARIABLE) {
98
                // Store variable
99
                $variableText = $token[1];
100
                // Store variable name
101
                $variableName = ltrim($token[1], '$');
102
                // If next token is object operator
103
                if ($tokens[$idx + 1][0] === T_OBJECT_OPERATOR) {
104
                    $variableName = $tokens[$idx + 2][1];
105
                    // And two more tokens
106
                    $variableText .= $tokens[$idx + 1][1] . $variableName;
107
                }
108
                // Store view variable key - actual object name => full varaible usage
109
                $metadata->variables[$variableName] = $variableText;
110
            }
111
        }
112
113
        return $metadata;
114
    }
115
116
    /**
117
     * Generic class name and its name space generator.
118
     *
119
     * @param string $file      Full path to view file
120
     * @param string $entryPath Entry path
121
     *
122
     * @return array Class name[0] and namespace[1]
123
     */
124
    protected function generateClassName($file, $entryPath)
125
    {
126
        // Get only file name as a class name with suffix
127
        $className = pathinfo($file, PATHINFO_FILENAME) . self::VIEW_CLASSNAME_SUFFIX;
128
129
        // Get namespace as part of file path relatively to entry path
130
        $nameSpace = rtrim(ltrim(
131
            str_replace(
132
                '/',
133
                '\\',
134
                str_replace($entryPath, '', pathinfo($file, PATHINFO_DIRNAME))
135
            ),
136
            '\\'
137
        ), '\\');
138
139
        // Check generated namespaces
140
        foreach (static::$reservedWords as $reserverWord) {
141
            if (strpos($nameSpace, '\\' . $reserverWord) !== false) {
142
                throw new GeneratedViewPathHasReservedWord($reserverWord);
143
            }
144
        }
145
146
        // Return collection for further usage
147
        return array($className, rtrim($this->namespacePrefix . $nameSpace, '\\'));
148
    }
149
150
    public function generate($path = __DIR__)
151
    {
152
        foreach ($this->metadata as $metadata) {
153
            $this->generateViewClass($metadata, $path);
154
        }
155
    }
156
157
    protected function generateViewClass(Metadata $metadata, $path)
158
    {
159
        $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...
160
            ->defNamespace($metadata->namespace)
161
            ->multiComment(array('Class for view "'.$metadata->path.'" rendering'))
162
            ->defClass($metadata->className, '\\'.View::class)
163
            ->commentVar('string', 'Path to view file')
164
            ->defClassVar('$path', 'protected', $metadata->path)
165
            ->commentVar('array', 'Collection of view variables')
166
            ->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...
167
168
        // Iterate all view variables
169
        foreach (array_keys($metadata->variables) as $name) {
170
            $this->generator
171
                ->commentVar('mixed', 'View variable')
172
                ->defClassVar('$'.$name, 'public')
173
                ->text($this->generateViewVariableSetter($name));
174
        }
175
176
        file_put_contents(
177
            $path.'/'.$metadata->className.'.php',
178
            '<?php'.$this->generator->endClass()->flush()
179
        );
180
    }
181
182
    /**
183
     * Generate constructor for application class.
184
     *
185
     * @param string $variable View variable name
186
     *
187
     * @return string View variable setter method
188
     */
189
    protected function generateViewVariableSetter($variable)
190
    {
191
        $class = "\n\t" . '/**';
192
        $class .= "\n\t" . ' * Setter for ' . $variable . ' view variable';
193
        $class .= "\n\t" . ' *';
194
        $class .= "\n\t" . ' * @param mixed $value View variable value';
195
        $class .= "\n\t" . ' * @return $this Chaining';
196
        $class .= "\n\t" . ' */';
197
        $class .= "\n\t" . 'public function ' . $variable . '($value)';
198
        $class .= "\n\t" . '{';
199
        $class .= "\n\t\t" . 'return parent::set($value, \'' . $variable . '\');';
200
        $class .= "\n\t" . '}' . "\n";
201
202
        return $class;
203
    }
204
}
205