Code::parse()   F
last analyzed

Complexity

Conditions 52
Paths 616

Size

Total Lines 261
Code Lines 94

Duplication

Lines 110
Ratio 42.15 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 110
loc 261
rs 2
cc 52
eloc 94
nc 616
nop 4

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: egorov
5
 * Date: 09.02.2015
6
 * Time: 16:20
7
 */
8
namespace samsonphp\compressor;
9
use samson\core\Module;
10
11
/**
12
 * Code compressor.
13
 * @package samsonphp\compressor
14
 */
15
class Code implements CompressibleInterface
16
{
17
    /** Code excluding markers */
18
    const EXCLUDE_ST = '\/\/\[PHPCOMPRESSOR\(remove\,start\)\]';
19
    const EXCLUDE_EN = '\/\/\[PHPCOMPRESSOR\(remove\,end\)\]';
20
21
    /** Use statement pattern */
22
    const PAT_USE = '/\s*use\s+(?<class>[^ ]+)(\s+as\s+(<alias>[^;]+))*;/iu';
23
    /** Blank lines pattern */
24
    const PAT_BLANK_LINES = '/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/';
25
26
    /** @var array Collection of files that has been compressed */
27
    protected $files = array();
28
29
    /** @var array Collection of  NameSpace => \samsonphp\compressor\NS */
30
    protected $data = array();
31
32
    /** @var  Object Logger object */
33
    protected $logger;
34
35
    /**
36
     * Remove blank lines from code
37
     * http://stackoverflow.com/questions/709669/how-do-i-remove-blank-lines-from-text-in-php
38
     * @param string $code Code for removing blank lines
39
     * @return string Modified code
40
     */
41
    protected function removeBlankLines($code)
42
    {
43
        // New line is required to split non-blank lines
44
        return preg_replace(self::PAT_BLANK_LINES, "\n", $code);
45
    }
46
47
    /**
48
     * @param \samson\core\Module $module Module which code is being gathered
0 ignored issues
show
Bug introduced by
There is no parameter named $module. Was it maybe removed?

This check looks for PHPDoc comments describing methods or function parameters that do not exist on the corresponding method or function.

Consider the following example. The parameter $italy is not defined by the method finale(...).

/**
 * @param array $germany
 * @param array $island
 * @param array $italy
 */
function finale($germany, $island) {
    return "2:1";
}

The most likely cause is that the parameter was removed, but the annotation was not.

Loading history...
49
     */
50
    public function __construct(array $files, $logger = null)
51
    {
52
        $this->logger = & $logger;
53
54
        // Gather all module code resource files
55
        foreach ($files as $file) {
56
            // Compress this files into code array
57
            $this->compress($file);
0 ignored issues
show
Bug introduced by
The call to compress() misses a required argument $output.

This check looks for function calls that miss required arguments.

Loading history...
58
        }
59
    }
60
61
    /**
62
     * Remove all use statements in a file and replace class/function calls
63
     * to full syntax names.
64
     */
65
    public function removeUSE($code)
66
    {
67
        // Find all uses in file
68
        $matches = array();
69
        if (preg_match_all(self::PAT_USE, $code, $matches)) {
70
            for ($i = 0,$size = sizeof($matches[1]); $i < $size; $i++) {
71
                // Get full class name
72
                $fullClassName = $matches['class'][$i];
73
74
                // Get class name without namespace
75
                $className = substr(strrchr($fullClassName, '\\'), 1);
76
77
                // Prepend global namespace sign
78
                $fullClassName = $fullClassName{0} !== '\\' ? '\\'.$fullClassName : $fullClassName;
79
80
                // Determine marker in code for this use, alias or just class name
81
                $replace = isset($matches['alias'][$i]{0}) ?
82
                    $matches['alias'][$i] : // Use alias name
83
                    $className; // Use class name without namespace
84
85
                // Remove use statement
86
                $code = str_replace($matches[0][$i], '', $code);
87
88
                // Check class existence
89
                if (class_exists($fullClassName) || interface_exists($fullClassName)) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
90
91
                    $this->logger->log(' Removing USE statement for [##]', $fullClassName);
92
93
                    // Replace class static call
94
                    $code = preg_replace(
95
                        '/([^\\\a-z])' . $replace . '::/i',
96
                        '$1' . $fullClassName . '::',
97
                        $code
98
                    );
99
100
                    // Replace class implements calls
101
                    $code = preg_replace(
102
                        '/implements\s+(.*)' . $replace . '/i',
103
                        'implements $1' . $fullClassName,
104
                        $code
105
                    );
106
107
                    // Replace class extends calls
108
                    $code = preg_replace(
109
                        '/extends\s+' . $replace . '/i',
110
                        'extends ' . $fullClassName,
111
                        $code
112
                    );
113
114
                    // Replace class hint calls
115
                    $code = preg_replace(
116
                        '/(\(|\s|\,)\s*' . $replace . '\s*(&|$)/i',
117
                        '$1' . $fullClassName . ' $2',
118
                        $code
119
                    );
120
121
                    // Replace class creation call
122
                    $code = preg_replace(
123
                        '/new\s+' . $replace . '\s*\(/i',
124
                        'new ' . $fullClassName . '(',
125
                        $code
126
                    );
127
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
128
                } else {
129
                    $this->logger->log(
130
                        'Cannot remove use statement[##] - Class or interface does not exists',
131
                        $matches[0][$i]
132
                    );
133
                }
134
            }
135
        }
136
137
        return $code;
138
    }
139
140
    /**
141
     * Remove excluded code blocks
142
     * @param string $code Code to exclude
143
     * @return string Code cleared from excluded blocks
144
     */
145
    public function removeExcluded($code)
146
    {
147
        // Remove excluded code blocks
148
        return preg_replace('/'.self::EXCLUDE_ST.'.*?'.self::EXCLUDE_EN.'/uis', '', $code);
149
    }
150
151
    public function compress($file, $output)
152
    {
153
        if (file_exists($file)) {
154
            // Make full real path to file
155
            $file = realpath($file);
156
            // If we have not processed this file yet
157
            if (!in_array($file, $this->files)) {
158
                $this->files[] = $file;
159
160
                $this->logger->log('Compressing PHP code file[##]', $file);
161
162
                // Read and compress file contents
163
                $this->data[$file] = $this->removeUSE(
164
                    $this->removeExcluded(
165
                        $this->removeBlankLines(
166
                            file_get_contents($file)
167
                        )
168
                    )
169
                );
170
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
171
            } else {
172
                $this->logger->log('PHP code file[##] already compressed', $file);
173
            }
174
        } else {
175
            $this->logger->log('PHP code file[##] does not exists', $file);
176
        }
177
    }
178
179
    /**
180
     * Reccurent PHP code parser
181
     *
182
     * @param string $path Abcolute path to php file
183
     * @param Module  $module Pointer to file owning module object
184
     * @param array  $code Collection where we need to gather parsed PHP code
185
     * @param string $namespace Module namespace
186
     *
187
     * @return array
188
     */
189
    protected function parse( $path, $module = NULL, & $code = array(), $namespace = self::NS_GLOBAL )
0 ignored issues
show
Coding Style introduced by
TRUE, FALSE and NULL must be lowercase; expected null, but found NULL.
Loading history...
Coding Style introduced by
Expected 0 spaces between opening bracket and argument "$path"; 1 found
Loading history...
Coding Style introduced by
Expected 0 spaces between argument "$namespace" and closing bracket; 1 found
Loading history...
190
    {
191
        $_path = $path;
192
        $path = normalizepath(realpath($path));
193
194
        // Если мы уже подключили данный файл или он не существует
195 View Code Duplication
        if( isset( $this->files[ $path ])  ) 	return $this->log('    ! Файл: [##], already compressed', $path);
0 ignored issues
show
Bug introduced by
The method log() does not seem to exist on object<samsonphp\compressor\Code>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
Coding Style introduced by
Expected 0 spaces before closing bracket; 2 found
Loading history...
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
196
        else if( !is_file($path) )				return $this->log('    ! Файл: [##], не существует', $_path );
0 ignored issues
show
Bug introduced by
The method log() does not seem to exist on object<samsonphp\compressor\Code>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
Coding Style introduced by
Expected 0 spaces before closing bracket; 1 found
Loading history...
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
197
        else if(strpos($path, 'vendor/autoload.php') !== false) return $this->log('    Ignoring composer autoloader [##]', $path);
0 ignored issues
show
Bug introduced by
The method log() does not seem to exist on object<samsonphp\compressor\Code>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
198
        else if(in_array(basename($path), $this->ignoredFiles)) { return $this->log('    Ignoring file[##] by configuration', $path);}
0 ignored issues
show
Bug introduced by
The property ignoredFiles does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
Bug introduced by
The method log() does not seem to exist on object<samsonphp\compressor\Code>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
199
200
        $this->log(' - Parsing file [##]', $path);
0 ignored issues
show
Bug introduced by
The method log() does not seem to exist on object<samsonphp\compressor\Code>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
201
202
        // Load file once, if it's not have been loaded before
203
        require_once($path);
204
205
        // Сохраним файл
206
        $this->files[ $path ] = $path;
207
208
        // Прочитаем php файл
209
        $fileStr = file_get_contents( $path );
210
211
        $main_code = "\n".'// Модуль: '.m($module)->id().', файл: '.$path."\n";
0 ignored issues
show
Deprecated Code introduced by
The function m() has been deprecated with message: Use $this->system->module() in module context

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
212
213
        // Создадим уникальную коллекцию алиасов для NS
214
        if( !isset($code[ $namespace ][ 'uses' ] ) ) $code[ $namespace ][ 'uses' ] = array();
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
215
216
        // Установим ссылку на коллекцию алиасов
217
        $uses = & $code[ $namespace ][ 'uses' ];
218
219
        // Local file uses collection
220
        $file_uses = array();
221
222
        // Получим константы документа
223
        $consts = get_defined_constants();
224
225
        // Маркеры для отрезания специальных блоков которые не нужны в PRODUCTION
226
        $rmarker_st = '\/\/\[PHPCOMPRESSOR\(remove\,start\)\]';
227
        $rmarker_en = '\/\/\[PHPCOMPRESSOR\(remove\,end\)\]';
228
229
        // Найдем все "ненужные" блоки кода и уберем их
230
        $fileStr = preg_replace('/'.$rmarker_st.'.*?'.$rmarker_en.'/uis', '', $fileStr );
231
232
        // Разберем код программы
233
        $tokens = token_get_all($fileStr);
234
        for ($i = 0; $i < sizeof($tokens); $i++)
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function sizeof() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
235
        {
236
            // Получим следующий жетон из кода программы
237
            $token = $tokens[$i];
238
239
            // Если просто строка
240
            if ( is_string( $token ) ) $main_code .= $token;
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
241
            // Если это специальный жетон
242
            else
0 ignored issues
show
Coding Style introduced by
Expected 1 space after ELSE keyword; newline found
Loading history...
243
            {
244
                // token array
245
                list( $id, $text ) = $token;
246
247
                // Перебирем тип комманды
248
                switch ($id)
249
                {
250
                    case T_COMMENT: // Пропускаем все комментарии
251
                    case T_DOC_COMMENT:
252
                    case T_CLOSE_TAG: // Начало,конец файла
253
                    case T_OPEN_TAG: break;
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
254
255
                    case T_WHITESPACE:	$main_code .= $text; /*$main_code .= ' ';*/ break;
0 ignored issues
show
Coding Style introduced by
It is generally recommended to place each PHP statement on a line by itself.

Let’s take a look at an example:

// Bad
$a = 5; $b = 6; $c = 7;

// Good
$a = 5;
$b = 6;
$c = 7;
Loading history...
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
256
257
                    // Обработаем алиасы
258
                    case T_USE:
0 ignored issues
show
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
259
260
                        $_use = '';
261
262
                        // Переберем все что иде после комманды алиаса
263
                        for ($j = $i+1; $j < sizeof($tokens); $j++)
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function sizeof() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
264
                        {
265
                            // Получим идентификатор метки и текстовое представление
266
                            $id = isset( $tokens[ $j ][0] ) ? $tokens[ $j ][0] : '';
267
                            $text = isset( $tokens[ $j ][1] ) ? $tokens[ $j ][1] : '';
268
269
                            //trace('"'.$id.'" - "'.$text.'"');
270
271
                            // Если use используется в функции
272
                            if( $id == '(' ) { $j--; break; }
0 ignored issues
show
Coding Style introduced by
It is generally recommended to place each PHP statement on a line by itself.

Let’s take a look at an example:

// Bad
$a = 5; $b = 6; $c = 7;

// Good
$a = 5;
$b = 6;
$c = 7;
Loading history...
Coding Style introduced by
Expected 0 spaces before closing bracket; 1 found
Loading history...
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
273
274
                            // Если это закрывающая скобка - прекратим собирание пути к файлу
275
                            if( $id == ';' ) break;
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
Coding Style introduced by
Expected 0 spaces before closing bracket; 1 found
Loading history...
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
276
277
                            // Все пробелы игнорирую
278
                            if( $id == T_WHITESPACE ) continue;
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
Coding Style introduced by
Expected 0 spaces before closing bracket; 1 found
Loading history...
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
279
280
                            // Если у метки есть текстовое представление
281
                            if( isset( $text ) )
0 ignored issues
show
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
282
                            {
283
                                // Если єто константа
284
                                if( isset( $consts[ $text ])) $_use .= $consts[ $text ];
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
285
                                // Если это путь
286
                                else $_use .= $text;
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
287
                            }
288
                        }
289
290
                        // Если это не use в inline функции - добавим алиас в коллекцию
291
                        // для данного ns с проверкой на уникальность
292
                        if( $id !== '(' )
0 ignored issues
show
Coding Style introduced by
Expected 0 spaces before closing bracket; 1 found
Loading history...
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
293
                        {
294
                            // Нижний регистр
295
                            //$_use = strtolower($_use);
296
297
                            // Преведем все use к одному виду
298
                            if( $_use{0} !== '\\') $_use = '\\'.$_use;
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
299
300
                            // Add local file uses
301
                            $file_uses[] = $_use;
302
303
                            // TODO: Вывести замечание что бы код везде был одинаковый
304
                            if( !in_array( $_use, $uses ) )
0 ignored issues
show
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
305
                            {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
306
307
308
                                $uses[] = $_use;
309
                            }
310
                        } else {
311
                            $main_code .= ' use ';
312
                        }
313
314
                        // Сместим указатель чтения файла
315
                        $i = $j;
316
317
                        break;
318
319 View Code Duplication
                    case T_NAMESPACE:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Coding Style introduced by
The case body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a case statement must start on the line immediately following the case statement.

switch ($expr) {
case "A":
    doSomething(); //right
    break;
case "B":

    doSomethingElse(); //wrong
    break;

}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
320
321
                        // Определим временное пространство имен
322
                        $_namespace = '';
323
324
                        // Переберем все что иде после комманды подключения файла
325
                        for ($j = $i+1; $j < sizeof($tokens); $j++)
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function sizeof() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
326
                        {
327
                            // Получим идентификатор метки и текстовое представление
328
                            $id = isset( $tokens[ $j ][0] ) ? $tokens[ $j ][0] : '';
329
                            $text = isset( $tokens[ $j ][1] ) ? $tokens[ $j ][1] : '';
330
331
                            //trace('"'.$id.'" - "'.$text.'"');
332
333
                            // Если это закрывающая скобка - прекратим собирание пути к файлу
334
                            if( $id == ')' || $id == ';' ||  $id == '{' ) break;
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
Coding Style introduced by
Expected 0 spaces before closing bracket; 1 found
Loading history...
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
335
336
                            // Все пробелы игнорирую
337
                            if( $id == T_WHITESPACE ) continue;
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
Coding Style introduced by
Expected 0 spaces before closing bracket; 1 found
Loading history...
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
338
339
                            // Если у метки есть текстовое представление
340
                            if( isset( $text ) )
0 ignored issues
show
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
341
                            {
342
                                // Если єто константа
343
                                if( isset( $consts[ $text ])) $_namespace .= $consts[ $text ];
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
344
                                // Если это путь
345
                                else $_namespace .= $text;
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
346
                            }
347
                        }
348
349
                        // Если найденный NS отличается от текущего - установим переход к новому NS
350
                        if( $namespace !== $_namespace )
0 ignored issues
show
Coding Style introduced by
Expected 0 spaces before closing bracket; 1 found
Loading history...
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
351
                        {
352
                            // Сохраним новый как текущий
353
                            $namespace = strtolower($_namespace);
354
355
                            //trace('               #'.$i.' -> Изменили NS с '.$namespace.' на '.$_namespace);
356
357
                            // Если мы еще не создали данный NS
358
                            if( !isset($code[ $namespace ]) ) $code[ $namespace ] = array();
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
Coding Style introduced by
Expected 0 spaces before closing bracket; 1 found
Loading history...
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
359
                            // Создадим уникальную коллекцию алиасов для NS
360
                            if( !isset($code[ $namespace ][ 'uses' ] ) ) $code[ $namespace ][ 'uses' ] = array();
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
361
                            // Установим ссылку на коллекцию алиасов
362
                            $uses = & $code[ $namespace ][ 'uses' ];
363
                        }
364
365
                        // Сместим указатель чтения файла
366
                        $i = $j;
367
368
                        break;
369
370
                    // Выделяем код подключаемых файлов
371
                    case T_REQUIRE :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
372
                    case T_REQUIRE_ONCE :
0 ignored issues
show
Coding Style introduced by
There must be no space before the colon in a CASE statement

As per the PSR-2 coding standard, there must not be a space in front of the colon in case statements.

switch ($selector) {
    case "A": //right
        doSomething();
        break;
    case "B" : //wrong
        doSomethingElse();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
373
                        //case T_INCLUDE :
374 View Code Duplication
                    case T_INCLUDE_ONCE:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Coding Style introduced by
case statements should be defined using a colon.

As per the PSR-2 coding standard, case statements should not be wrapped in curly braces. There is no need for braces, since each case is terminated by the next break.

There is also the option to use a semicolon instead of a colon, this is discouraged because many programmers do not even know it works and the colon is universal between programming languages.

switch ($expr) {
    case "A": { //wrong
        doSomething();
        break;
    }
    case "B"; //wrong
        doSomething();
        break;
    case "C": //right
        doSomething();
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
375
                    {
376
                        // Получим путь к подключаемому файлу
377
                        $file_path = '';
378
379
                        // Переберем все что иде после комманды подключения файла
380
                        for ($j = $i+1; $j < sizeof($tokens); $j++)
0 ignored issues
show
Performance Best Practice introduced by
It seems like you are calling the size function sizeof() as part of the test condition. You might want to compute the size beforehand, and not on each iteration.

If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration:

for ($i=0; $i<count($array); $i++) { // calls count() on each iteration
}

// Better
for ($i=0, $c=count($array); $i<$c; $i++) { // calls count() just once
}
Loading history...
381
                        {
382
                            // Получим идентификатор метки и текстовое представление
383
                            $id = isset( $tokens[ $j ][0] ) ? $tokens[ $j ][0] : '';
384
                            $text = isset( $tokens[ $j ][1] ) ? $tokens[ $j ][1] : '';
385
386
                            //trace('"'.$id.'" - "'.$text.'"');
387
388
                            // Если это закрывающая скобка - прекратим собирание пути к файлу
389
                            if( $id == ';' ) break;
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
Coding Style introduced by
Expected 0 spaces before closing bracket; 1 found
Loading history...
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
390
391
                            // Все пробелы игнорирую
392
                            if( $id == T_WHITESPACE ) continue;
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
Coding Style introduced by
Expected 0 spaces before closing bracket; 1 found
Loading history...
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
393
394
                            // Если у метки есть текстовое представление
395
                            if( isset( $text ) )
0 ignored issues
show
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
396
                            {
397
                                // Если єто константа
398
                                if( isset( $consts[ $text ])) $file_path .= $consts[ $text ];
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
399
                                // Если это путь
400
                                else $file_path .= $text;
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
401
                            }
402
                        }
403
404
                        // Если указан путь к файлу
405
                        if( isset($file_path{1}) )
0 ignored issues
show
Coding Style introduced by
Expected 0 spaces before closing bracket; 1 found
Loading history...
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
406
                        {
407
                            // Уберем ковычки
408
                            $file_path = str_replace(array("'",'"'), array('',''), $file_path );
409
410
                            // Если это не абсолютный путь - попробуем относительный
411
                            if( !file_exists( $file_path ) ) $file_path = pathname($path).$file_path;
0 ignored issues
show
Coding Style Best Practice introduced by
It is generally a best practice to always use braces with control structures.

Adding braces to control structures avoids accidental mistakes as your code changes:

// Without braces (not recommended)
if (true)
    doSomething();

// Recommended
if (true) {
    doSomething();
}
Loading history...
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
412
413
                            // Если файл найден - получим его содержимое
414
                            if( file_exists( $file_path ) )
0 ignored issues
show
Coding Style introduced by
Expected 1 space after IF keyword; 0 found
Loading history...
415
                            {
416
                                //trace('Углубляемся в файл:'.$file_path.'('.$namespace.')');
417
418
                                // Углубимся в рекурсию
419
                                $this->compress_php( $file_path, $module, $code, $namespace );
0 ignored issues
show
Bug introduced by
The method compress_php() does not exist on samsonphp\compressor\Code. Did you maybe mean compress()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
420
421
                                // Измением позицию маркера чтения файла
422
                                $i = $j + 1;
423
                            }
424
                        } else {
425
                            $main_code .= $text;
426
                        }
427
428
                    }
429
                        break;
430
431
                    // Собираем основной код программы
432
                    default: $main_code .= $text; break;
0 ignored issues
show
Coding Style introduced by
It is generally recommended to place each PHP statement on a line by itself.

Let’s take a look at an example:

// Bad
$a = 5; $b = 6; $c = 7;

// Good
$a = 5;
$b = 6;
$c = 7;
Loading history...
Coding Style introduced by
The default body in a switch statement must start on the line following the statement.

According to the PSR-2, the body of a default statement must start on the line immediately following the statement.

switch ($expr) {
    default:
        doSomething(); //right
        break;
}


switch ($expr) {
    default:

        doSomething(); //wrong
        break;
}

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
Coding Style introduced by
Terminating statement must be on a line by itself

As per the PSR-2 coding standard, the break (or other terminating) statement must be on a line of its own.

switch ($expr) {
     case "A":
         doSomething();
         break; //wrong
     case "B":
         doSomething();
         break; //right
     case "C:":
         doSomething();
         return true; //right
 }

To learn more about the PSR-2 coding standard, please refer to the PHP-Fig.

Loading history...
433
                }
434
            }
435
        }
436
437
        //trace(' - Вышли из функции:'.$path.'('.$namespace.')');
438
        //trace('');
439
440
        // Replace all class shortcut usage with full name
441
        if (sizeof($file_uses)) {
442
            $main_code = $this->removeUSEStatement($main_code, $file_uses);
0 ignored issues
show
Bug introduced by
The method removeUSEStatement() does not exist on samsonphp\compressor\Code. Did you maybe mean removeUSE()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
443
        }
444
445
        // Запишем в коллекцию кода полученный код
446
        $code[ $namespace ][ $path ] = $main_code;
447
448
        return $main_code;
449
    }
450
}
451