Completed
Push — master ( 5eab6a...6d37e2 )
by Vitaly
02:06
created

Generator::changeName()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 12
ccs 9
cts 9
cp 1
rs 9.4285
cc 1
eloc 7
nc 1
nop 1
crap 1
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
 *
27
 * @package samsonframework\view
28
 */
29
class Generator
30
{
31
    /** string All generated view classes will end with this suffix */
32
    const VIEW_CLASSNAME_SUFFIX = 'View';
33
34
    /** @var array Collection of PHP reserved words */
35
    protected static $reservedWords = array(
36
        'list'
37
    );
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
    /**
49
     * Generator constructor.
50
     *
51
     * @param \samsonphp\generator\Generator $generator
52
     * @param string                               $namespacePrefix
53
     */
54 2
    public function __construct(\samsonphp\generator\Generator $generator, $namespacePrefix)
55
    {
56 2
        $this->generator = $generator;
57 2
        $this->namespacePrefix = rtrim(ltrim($namespacePrefix, '\\'), '\\').'\\';
58 2
    }
59
60
    /**
61
     * Change variable name to camel caps format.
62
     *
63
     * @param string $variable
64
     *
65
     * @return string Changed variable name
66
     */
67 1
    public function changeName($variable)
68
    {
69 1
        return lcfirst(
70 1
            implode(
71 1
                '',
72 1
                array_map(
73
                    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...
74 1
                    explode('_', $variable)
75 1
                )
76 1
            )
77 1
        );
78
    }
79
80
    /**
81
     * Recursively scan path for files with specified extensions.
82
     *
83
     * @param string $source     Entry point path
84
     * @param string $path       Entry path for scanning
85
     * @param array  $extensions Collection of file extensions without dot
86
     */
87 2
    public function scan($source, array $extensions = array(View::DEFAULT_EXT), $path = null)
88
    {
89 2
        $path = isset($path) ? $path : $source;
90
91
        // Recursively go deeper into inner folders for scanning
92 2
        $folders  = glob($path.'/*', GLOB_ONLYDIR);
93 2
        foreach ($folders as $folder) {
94 2
            $this->scan($source, $extensions, $folder);
95 2
        }
96
97
        // Iterate file extensions
98 2
        foreach ($extensions as $extension) {
99 2
            foreach (glob(rtrim($path, '/') . '/*.'.$extension) as $file) {
100 2
                $this->metadata[$file] = $this->analyze($file);
101 2
                $this->metadata[$file]->path = str_replace($source, '', $file);
102 1
                list($this->metadata[$file]->className,
103 2
                    $this->metadata[$file]->namespace) = $this->generateClassName($file, $source);
104 2
            }
105 2
        }
106 2
    }
107
108
    /**
109
     * Analyze view file and create its metadata.
110
     *
111
     * @param string $file Path to view file
112
     *
113
     * @return Metadata View file metadata
114
     */
115 2
    public function analyze($file)
116
    {
117 2
        $metadata = new Metadata();
118
        // Use PHP tokenizer to find variables
119 2
        foreach ($tokens = token_get_all(file_get_contents($file)) as $idx => $token) {
120 2
            if (!is_string($token) && $token[0] === T_VARIABLE) {
121
                // Store variable
122 1
                $variableText = $token[1];
123
                // Store variable name
124 1
                $variableName = ltrim($token[1], '$');
125
                // If next token is object operator
126 1
                if ($tokens[$idx + 1][0] === T_OBJECT_OPERATOR) {
127 1
                    $variableName = $tokens[$idx + 2][1];
128
                    // And two more tokens
129 1
                    $variableText .= $tokens[$idx + 1][1] . $variableName;
130 1
                }
131
                // Store view variable key - actual object name => full varaible usage
132 1
                $metadata->variables[$this->changeName($variableName)] = $variableText;
133 1
            }
134 2
        }
135
136 2
        return $metadata;
137
    }
138
139
    /**
140
     * Generic class name and its name space generator.
141
     *
142
     * @param string $file      Full path to view file
143
     * @param string $entryPath Entry path
144
     *
145
     * @return array Class name[0] and namespace[1]
146
     * @throws GeneratedViewPathHasReservedWord
147
     */
148 2
    protected function generateClassName($file, $entryPath)
149
    {
150
        // Get only file name as a class name with suffix
151 2
        $className = ucfirst(pathinfo($file, PATHINFO_FILENAME) . self::VIEW_CLASSNAME_SUFFIX);
152
153
        // Get namespace as part of file path relatively to entry path
154 2
        $nameSpace = rtrim(ltrim(
155 2
            str_replace(
156 2
                '/',
157 2
                '\\',
158 2
                str_replace($entryPath, '', pathinfo($file, PATHINFO_DIRNAME))
159 2
            ),
160
            '\\'
161 2
        ), '\\');
162
163
        // Check generated namespaces
164 2
        foreach (static::$reservedWords as $reservedWord) {
165 2
            if (strpos($nameSpace, '\\' . $reservedWord) !== false) {
166 1
                throw new GeneratedViewPathHasReservedWord($file.'('.$reservedWord.')');
167
            }
168 1
        }
169
170
        // Return collection for further usage
171 1
        return array($className, rtrim($this->namespacePrefix . $nameSpace, '\\'));
172
    }
173
174
    /**
175
     * Generate view classes.
176
     *
177
     * @param string $path Entry path for generated classes and folders
178
     */
179 1
    public function generate($path = __DIR__)
180
    {
181 1
        foreach ($this->metadata as $metadata) {
182 1
            $this->generateViewClass($metadata, $path);
183 1
        }
184 1
    }
185
186
    /**
187
     * Create View class ancestor.
188
     *
189
     * @param Metadata $metadata View file metadata
190
     * @param string   $path Entry path for generated classes and folders
191
     */
192 1
    protected function generateViewClass(Metadata $metadata, $path)
193
    {
194 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...
195 1
            ->defNamespace($metadata->namespace)
196 1
            ->multiComment(array('Class for view "'.$metadata->path.'" rendering'))
197 1
            ->defClass($metadata->className, '\\' . View::class)
198 1
            ->commentVar('string', 'Path to view file')
199 1
            ->defClassVar('$path', 'protected', $metadata->path)
200 1
            ->commentVar('array', 'Collection of view variables')
201 1
            ->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...
202
203
        // Iterate all view variables
204 1
        foreach (array_keys($metadata->variables) as $name) {
205 1
            $this->generator
206 1
                ->commentVar('mixed', 'View variable')
207 1
                ->defClassVar('$'.$name, 'public')
208 1
                ->text($this->generateViewVariableSetter($name));
209 1
        }
210
211
        // Iterate namespace and create folder structure
212 1
        $path .= '/'.str_replace('\\', '/', $metadata->namespace);
213 1
        if (!is_dir($path)) {
214 1
            mkdir($path, 0775, true);
215 1
        }
216
217 1
        file_put_contents(
218 1
            $path.'/'.$metadata->className.'.php',
219 1
            '<?php'.$this->generator->endClass()->flush()
220 1
        );
221 1
    }
222
223
    /**
224
     * Generate constructor for application class.
225
     *
226
     * @param string $variable View variable name
227
     *
228
     * @return string View variable setter method
229
     */
230 1
    protected function generateViewVariableSetter($variable)
231
    {
232 1
        $class = "\n\t" . '/**';
233 1
        $class .= "\n\t" . ' * Setter for ' . $variable . ' view variable';
234 1
        $class .= "\n\t" . ' *';
235 1
        $class .= "\n\t" . ' * @param mixed $value View variable value';
236 1
        $class .= "\n\t" . ' * @return $this Chaining';
237 1
        $class .= "\n\t" . ' */';
238 1
        $class .= "\n\t" . 'public function ' . $variable . '($value)';
239 1
        $class .= "\n\t" . '{';
240 1
        $class .= "\n\t\t" . 'return parent::set($value, \'' . $variable . '\');';
241 1
        $class .= "\n\t" . '}' . "\n";
242
243 1
        return $class;
244
    }
245
}
246