GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 85b2a1...28feed )
by Pedro
07:16 queued 04:34
created

MakerFile::generateFilesFixed()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 1
1
<?php
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 18 and the first side effect is on line 9.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
namespace Classes;
4
5
use Classes\AdapterMakerFile\AbstractAdapter;
6
use Classes\AdapterMakerFile\FilesFixeds;
7
use Classes\Maker\AbstractMaker;
8
9
require_once 'Classes/AdapterMakerFile/AbstractAdapter.php';
10
require_once 'Classes/AdapterMakerFile/FilesFixeds.php';
11
require_once 'Classes/Maker/AbstractMaker.php';
12
require_once 'Classes/CleanTrash.php';
13
14
/**
15
 * @author Pedro Alarcao <[email protected]>
16
 * @link   https://github.com/pedro151/orm-generator
17
 */
18
class MakerFile extends AbstractMaker
19
{
20
21
    /**
22
     * @type string[]
23
     */
24
    public $location = array ();
25
26
    /**
27
     * caminho de pastas Base
28
     *
29
     * @type string
30
     */
31
    private $baseLocation = '';
32
33
    /**
34
     * @type \Classes\AdapterConfig\AbstractAdapter
35
     */
36
    private $config;
37
38
    /**
39
     * @type \Classes\AdaptersDriver\AbsractAdapter
40
     */
41
    private $driver;
42
43
    private $countDir;
44
    private $max;
45
46
    private $msgReservedWord = "\033[0mPlease enter the value for reserved word \033[0;31m'%index%' \033[1;33m[%config%]:\033[0m ";
47
48
    public function __construct ( Config $config )
49
    {
50
        $this->config = $config->getAdapterConfig ();
51
        $this->parseReservedWord ( $this->getConfig () );
52
        $this->driver = $config->getAdapterDriver ( $this->getConfig () );
53
        $this->parseLocation ( $config->_basePath );
54
    }
55
56
    /**
57
     * @param AdapterConfig\AbstractAdapter $config
58
     */
59
    public function parseReservedWord ( AdapterConfig\AbstractAdapter $config )
60
    {
61
        $palavrasReservadas = $config->reservedWord;
62
        if ( !$palavrasReservadas ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $palavrasReservadas of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
63
            return;
64
        }
65
66
        $schema      = $config->getSchemas ();
67
        $db          = $config->getDatabase ();
68
        $hasSchema   = array_intersect ( $schema, array_flip ( $palavrasReservadas ) );
69
        $hasDatabase = in_array ( $db, $palavrasReservadas );
70
        if ( !( $hasSchema or $hasDatabase ) ) {
0 ignored issues
show
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
71
            return;
72
        }
73
74
        echo "- database has reserved words\n";
75 View Code Duplication
        foreach ( $palavrasReservadas as $index => $config ) {
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...
76
            $attribs = array (
77
                "%index%"  => $index,
78
                "%config%" => $config
79
            );
80
            echo strtr ( $this->msgReservedWord, $attribs );
81
            $line = trim ( fgets ( STDIN ) );
82
            if ( !empty( $line ) ) {
83
                $this->getConfig ()->reservedWord[ $index ] = $line;
84
            }
85
        }
86
    }
87
88
    /**
89
     * @param array $arrFoldersName
90
     *
91
     * @return string
92
     */
93
    private function filterLocation ( $arrFoldersName )
94
    {
95
        foreach ( $arrFoldersName as $index => $folderName ) {
96
            $arrFoldersName[ $index ] = $this->getConfig ()
97
                                             ->replaceReservedWord ( $folderName );
98
        }
99
100
        return implode ( DIRECTORY_SEPARATOR, array_filter ( $arrFoldersName ) );
101
    }
102
103
    /**
104
     * Analisa os caminhos das pastas base
105
     */
106
    public function parseLocation ( $basePath )
107
    {
108
109
        $arrBase = array (
110
            $basePath,
111
            $this->config->path
0 ignored issues
show
Documentation introduced by
The property path does not exist on object<Classes\AdapterConfig\AbstractAdapter>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
112
        );
113
114
        $this->baseLocation = $this->filterLocation ( $arrBase );
115
116
        # pasta com nome do driver do banco
117
        $driverBase = '';
118
        if ( (bool) @$this->config->{"folder-database"} ) {
119
            $classDriver = explode ( '\\', get_class ( $this->driver ) );
120
            $driverBase  = end ( $classDriver );
121
        }
122
        $folderName = '';
123
        if ( (bool) @$this->config->{"folder-name"} ) {
124
            $folderName = $this->getClassName ( trim ( $this->config->{"folder-name"} ) );
125
        }
126
127
        if ( $this->config->hasSchemas () ) {
128
129
            $schemas = $this->config->getSchemas ();
130
            foreach ( $schemas as $schema ) {
131
                $arrUrl = array (
132
                    $this->baseLocation,
133
                    $driverBase,
134
                    $folderName,
135
                    $this->getClassName ( $schema )
136
                );
137
138
                $this->location[ $schema ] = $this->filterLocation ( $arrUrl );
139
                unset( $arrUrl );
140
            }
141
142
        }
143
        else {
144
            $url            = array (
145
                $this->baseLocation,
146
                $driverBase,
147
                $folderName,
148
                $this->getClassName (
149
                    $this->getConfig ()
150
                         ->getDatabase ()
151
                )
152
            );
153
            $this->location = array ( $this->filterLocation ( $url ) );
154
            unset( $url );
155
        }
156
    }
157
158
    /**
159
     * @return AdapterConfig\AbstractAdapter
160
     */
161
    public function getConfig ()
162
    {
163
        return $this->config;
164
    }
165
166
    /* Get current time */
167
    public function startTime ()
168
    {
169
        echo "\033[1;32mStarting..\033[0m\n";
170
        $this->startTime = microtime ( true );
0 ignored issues
show
Bug introduced by
The property startTime 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...
171
    }
172
173
    private function getRunTime ()
174
    {
175
        return round ( ( microtime ( true ) - $this->startTime ), 3 );
176
    }
177
178
    /**
179
     * @param $objMakeFile
180
     */
181
    private function generateFilesFixed ( FilesFixeds $objFilesFixeds )
182
    {
183
        if ( $objFilesFixeds->hasData() )
184
        {
185
            $file = $this->baseLocation
186
                             . DIRECTORY_SEPARATOR
187
                             . $objFilesFixeds->getFileName()
188
                             . '.php';
189
190
            $tpl = $this->getParsedTplContents ( $objFilesFixeds->getTpl() );
191
            self::makeSourcer ( $file , $tpl , true );
192
        }
193
    }
194
195
    /**
196
     * Executa o Make, criando arquivos e Diretorios
197
     */
198
    public function run ()
199
    {
200
        $cur             = 0;
201
        $numFilesCreated = 0;
202
        $numFilesIgnored = 0;
203
204
        $this->startTime ();
205
        $this->waitOfDatabase($cur);
206
207
        $this->max       = $this->driver->getTotalTables () * $this->countDiretory ();
208
209
        foreach ( $this->location as $schema => $location ) {
210
            foreach ( $this->factoryMakerFile () as $objMakeFile ) {
211
                $path = $location . DIRECTORY_SEPARATOR . $objMakeFile->getPastName ();
212
                if($this->config->isCleanTrash()){
213
                    CleanTrash::getInstance ()->run ( $path , $this->driver, $schema );
214
                }
215
                self::makeDir ( $path );
216
217
                #Cria as Classes de Exceção e Abstratas
218
                foreach ( $objMakeFile->getListFilesFixed () as $nameObject )
219
                {
220
                    $this->generateFilesFixed($objMakeFile->getFilesFixeds($nameObject));
221
                }
222
223
                #Cria as Classes do Banco
224
                foreach ( $this->driver->getTables ( $schema ) as $key => $objTables ) {
225
                    $file = $path . DIRECTORY_SEPARATOR . self::getClassName ( $objTables->getName () ) . '.php';
226
227
                    $tpl = $this->getParsedTplContents (
228
                        $objMakeFile->getFileTpl (),
229
                        $objMakeFile->parseRelation ( $this, $objTables ),
230
                        $objTables,
231
                        $objMakeFile
232
233
                    );
234
                    if ( self::makeSourcer ( $file, $tpl, $objMakeFile->isOverwrite () ) ) {
235
                        ++$numFilesCreated;
236
                    }
237
                    else {
238
                        ++$numFilesIgnored;
239
                    }
240
241
                    $this->countCreatedFiles ( $cur );
242
                }
243
            }
244
        }
245
246
        $this->reportProcess ( $numFilesCreated, $numFilesIgnored );
247
        echo "\n\033[1;32mSuccessfully process finished!\n\033[0m";
248
    }
249
250
    private function waitOfDatabase ( &$cur )
251
    {
252
        printf ( "\033[1;33mWait, the database is being analyzed..\033[0m\n" );
253
        $this->driver->runDatabase ();
254
        printf ( "\r Creating: \033[1;32m%6.2f%%\033[0m", $cur );
255
    }
256
257
    private function countCreatedFiles ( &$cur )
258
    {
259
        ++$cur;
260
        $total = ( $cur / $this->max ) * 100;
261
        printf ( "\r Creating: \033[1;32m%6.2f%%\033[0m", $total );
262
    }
263
264
    private function reportProcess ( $numFilesCreated = 0, $numFilesIgnored = 0 )
265
    {
266
        if ( $this->config->isStatusEnabled () ) {
267
            $databases  = count ( $this->location );
268
            $countDir   = $this->countDiretory ();
269
            $totalTable = $this->driver->getTotalTables ();
270
            $totalFiles = $numFilesIgnored + $numFilesCreated;
271
            $totalFilesDeleted = CleanTrash::getInstance ()->getNumFilesDeleted();
272
            echo "\n------";
273
            printf ( "\n\r-Files generated/updated: \033[1;33m%s\033[0m" , $numFilesCreated );
274
            printf ( "\n\r-Files not upgradeable: \033[1;33m%s\033[0m" , $numFilesIgnored );
275
            printf ( "\n\r-Files deleted: \033[1;33m%s\033[0m" , $totalFilesDeleted );
276
            printf ( "\n\r-Total files analyzed: \033[1;33m%s of %s\033[0m" , $totalFiles , $this->max );
277
            printf ( "\n\r-Diretories: \033[1;33m%s\033[0m" , $databases * $countDir );
278
            printf ( "\n\r-Scanned tables: \033[1;33m%s\033[0m" , $totalTable );
279
            printf ( "\n\r-Execution time: \033[1;33m%ssec\033[0m" , $this->getRunTime () );
280
            echo "\n------";
281
        }
282
    }
283
284
    /**
285
     * Instancia os Modulos de diretorios e tampletes
286
     *
287
     * @return AbstractAdapter[]
288
     */
289
    public function factoryMakerFile ()
290
    {
291
        return $this->config->getMakeFileInstances ();
292
    }
293
294
    /**
295
     * conta o numero de diretorios que serao criados
296
     *
297
     * @return int
298
     */
299
    public function countDiretory ()
300
    {
301
        if ( null === $this->countDir ) {
302
            $this->countDir = 1;
303
            foreach ( $this->factoryMakerFile () as $abstractAdapter ) {
304
                if ( $abstractAdapter->hasDiretory () ) {
305
                    ++$this->countDir;
306
                }
307
            }
308
        }
309
310
        return $this->countDir;
311
    }
312
313
    /**
314
     *
315
     * parse a tpl file and return the result
316
     *
317
     * @param String $tplFile
318
     *
319
     * @return String
320
     */
321
    protected function getParsedTplContents ( $tplFile, $vars = array (), \Classes\Db\DbTable $objTables = null,
322
                                              $objMakeFile = null )
323
    {
324
325
        $arrUrl = array (
326
            __DIR__,
327
            'templates',
328
            $this->config->framework,
0 ignored issues
show
Documentation introduced by
The property framework does not exist on object<Classes\AdapterConfig\AbstractAdapter>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
329
            $tplFile
330
        );
331
332
        $filePath = implode ( DIRECTORY_SEPARATOR, filter_var_array ( $arrUrl ) );
333
334
        extract ( $vars );
335
        ob_start ();
336
        require $filePath;
337
        $data = ob_get_contents ();
338
        ob_end_clean ();
339
340
        return $data;
341
    }
342
343
}