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
Pull Request — master (#13)
by Pedro
04:05
created

MakerFile::waitOfDatabase()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 4
nc 1
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 15 and the first side effect is on line 8.

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\Maker\AbstractMaker;
7
8
require_once 'Classes/AdapterMakerFile/AbstractAdapter.php';
9
require_once 'Classes/Maker/AbstractMaker.php';
10
11
/**
12
 * @author Pedro Alarcao <[email protected]>
13
 * @link   https://github.com/pedro151/orm-generator
14
 */
15
class MakerFile extends AbstractMaker
16
{
17
18
    /**
19
     * @type string[]
20
     */
21
    public $location = array ();
22
23
    /**
24
     * caminho de pastas Base
25
     *
26
     * @type string
27
     */
28
    private $baseLocation = '';
29
30
    /**
31
     * @type \Classes\AdapterConfig\AbstractAdapter
32
     */
33
    private $config;
34
35
    /**
36
     * @type \Classes\AdaptersDriver\AbsractAdapter
37
     */
38
    private $driver;
39
40
    private $countDir;
41
    private $max;
42
43
    private $msgReservedWord = "\033[0mPlease enter the value for reserved word \033[0;31m'%index%' \033[1;33m[%config%]:\033[0m ";
44
45
    public function __construct ( Config $config )
46
    {
47
        $this->config = $config->getAdapterConfig ();
48
        $this->parseReservedWord ( $this->getConfig () );
49
        $this->driver = $config->getAdapterDriver ( $this->getConfig () );
50
        $this->parseLocation ( $config->_basePath );
51
    }
52
53
    /**
54
     * @param AdapterConfig\AbstractAdapter $config
55
     */
56
    public function parseReservedWord ( AdapterConfig\AbstractAdapter $config )
57
    {
58
        $palavrasReservadas = $config->reservedWord;
59
        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...
60
            return;
61
        }
62
63
        $schema      = $config->getSchemas ();
64
        $db          = $config->getDatabase ();
65
        $hasSchema   = array_intersect ( $schema, array_flip ( $palavrasReservadas ) );
66
        $hasDatabase = in_array ( $db, $palavrasReservadas );
67
        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...
68
            return;
69
        }
70
71
        echo "- database has reserved words\n";
72 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...
73
            $attribs = array (
74
                "%index%"  => $index,
75
                "%config%" => $config
76
            );
77
            echo strtr ( $this->msgReservedWord, $attribs );
78
            $line = trim ( fgets ( STDIN ) );
79
            if ( !empty( $line ) ) {
80
                $this->getConfig ()->reservedWord[ $index ] = $line;
81
            }
82
        }
83
    }
84
85
    /**
86
     * @param array $arrFoldersName
87
     *
88
     * @return string
89
     */
90
    private function filterLocation ( $arrFoldersName )
91
    {
92
        foreach ( $arrFoldersName as $index => $folderName ) {
93
            $arrFoldersName[ $index ] = $this->getConfig ()
94
                                             ->replaceReservedWord ( $folderName );
95
        }
96
97
        return implode ( DIRECTORY_SEPARATOR, array_filter ( $arrFoldersName ) );
98
    }
99
100
    /**
101
     * Analisa os caminhos das pastas base
102
     */
103
    public function parseLocation ( $basePath )
104
    {
105
106
        $arrBase = array (
107
            $basePath,
108
            $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...
109
        );
110
111
        $this->baseLocation = $this->filterLocation ( $arrBase );
112
113
        # pasta com nome do driver do banco
114
        $driverBase = '';
115
        if ( (bool) @$this->config->{"folder-database"} ) {
116
            $classDriver = explode ( '\\', get_class ( $this->driver ) );
117
            $driverBase  = end ( $classDriver );
118
        }
119
        $folderName = '';
120
        if ( (bool) @$this->config->{"folder-name"} ) {
121
            $folderName = $this->getClassName ( trim ( $this->config->{"folder-name"} ) );
122
        }
123
124
        if ( $this->config->hasSchemas () ) {
125
126
            $schemas = $this->config->getSchemas ();
127
            foreach ( $schemas as $schema ) {
128
                $arrUrl = array (
129
                    $this->baseLocation,
130
                    $driverBase,
131
                    $folderName,
132
                    $this->getClassName ( $schema )
133
                );
134
135
                $this->location[ $schema ] = $this->filterLocation ( $arrUrl );
136
                unset( $arrUrl );
137
            }
138
139
        }
140
        else {
141
            $url            = array (
142
                $this->baseLocation,
143
                $driverBase,
144
                $folderName,
145
                $this->getClassName (
146
                    $this->getConfig ()
147
                         ->getDatabase ()
148
                )
149
            );
150
            $this->location = array ( $this->filterLocation ( $url ) );
151
            unset( $url );
152
        }
153
    }
154
155
    /**
156
     * @return AdapterConfig\AbstractAdapter
157
     */
158
    public function getConfig ()
159
    {
160
        return $this->config;
161
    }
162
163
    /* Get current time */
164
    public function startTime ()
165
    {
166
        echo "\033[1;32mStarting..\033[0m\n";
167
        $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...
168
    }
169
170
    private function getRunTime ()
171
    {
172
        return round ( ( microtime ( true ) - $this->startTime ), 3 );
173
    }
174
175
    /**
176
     * Executa o Make, criando arquivos e Diretorios
177
     */
178
    public function run ()
179
    {
180
        $cur             = 0;
181
        $numFilesCreated = 0;
182
        $numFilesIgnored = 0;
183
184
        $this->startTime ();
185
        $this->waitOfDatabase($cur);
186
187
        $this->max       = $this->driver->getTotalTables () * $this->countDiretory ();
188
189
        foreach ( $this->location as $schema => $location ) {
190
            foreach ( $this->factoryMakerFile () as $objMakeFile ) {
191
                $path = $location . DIRECTORY_SEPARATOR . $objMakeFile->getPastName ();
192
                self::makeDir ( $path );
193
                if ( $objMakeFile->getParentFileTpl () != '' ) {
194
                    $fileAbstract = $this->baseLocation
195
                                    . DIRECTORY_SEPARATOR
196
                                    . $objMakeFile->getParentClass ()
197
                                    . '.php';
198
199
                    $tplAbstract = $this->getParsedTplContents ( $objMakeFile->getParentFileTpl () );
200
                    self::makeSourcer ( $fileAbstract, $tplAbstract, true );
201
                    unset( $fileAbstract, $tplAbstract );
202
                }
203
204
                foreach ( $this->driver->getTables ( $schema ) as $key => $objTables ) {
205
                    $file = $path . DIRECTORY_SEPARATOR . self::getClassName ( $objTables->getName () ) . '.php';
206
207
                    $tpl = $this->getParsedTplContents (
208
                        $objMakeFile->getFileTpl (),
209
                        $objMakeFile->parseRelation ( $this, $objTables ),
210
                        $objTables,
211
                        $objMakeFile
212
213
                    );
214
                    if ( self::makeSourcer ( $file, $tpl, $objMakeFile->isOverwrite () ) ) {
215
                        ++$numFilesCreated;
216
                    }
217
                    else {
218
                        ++$numFilesIgnored;
219
                    }
220
221
                    $this->countCreatedFiles ( $cur );
222
                }
223
            }
224
        }
225
226
        $this->reportProcess ( $numFilesCreated, $numFilesIgnored );
227
        echo "\n\033[1;32mSuccessfully process finished!\n\033[0m";
228
    }
229
230
    private function waitOfDatabase ( &$cur )
231
    {
232
        printf ( "\033[1;33mWait, the database is being analyzed..\033[0m\n" );
233
        $this->driver->runDatabase ();
234
        printf ( "\r Creating: \033[1;32m%6.2f%%\033[0m", $cur );
235
    }
236
237
    private function countCreatedFiles ( &$cur )
238
    {
239
        ++$cur;
240
        $total = ( $cur / $this->max ) * 100;
241
        printf ( "\r Creating: \033[1;32m%6.2f%%\033[0m", $total );
242
    }
243
244
    private function reportProcess ( $numFilesCreated = 0, $numFilesIgnored = 0 )
245
    {
246
        if ( $this->config->isStatusEnabled () ) {
247
            $databases  = count ( $this->location );
248
            $countDir   = $this->countDiretory ();
249
            $totalTable = $this->driver->getTotalTables ();
250
            $totalFiles = $numFilesIgnored + $numFilesCreated;
251
            echo "\n------";
252
            printf ( "\n\r-Files generated/updated: \033[1;33m%s\033[0m", $numFilesCreated );
253
            printf ( "\n\r-Files not upgradeable: \033[1;33m%s\033[0m", $numFilesIgnored );
254
            printf ( "\n\r-Total files analyzed: \033[1;33m%s of %s\033[0m", $totalFiles, $this->max );
255
            printf ( "\n\r-Diretories: \033[1;33m%s\033[0m", $databases * $countDir );
256
            printf ( "\n\r-Scanned tables: \033[1;33m%s\033[0m", $totalTable );
257
            printf ( "\n\r-Execution time: \033[1;33m%ssec\033[0m", $this->getRunTime () );
258
            echo "\n------";
259
        }
260
    }
261
262
    /**
263
     * Instancia os Modulos de diretorios e tampletes
264
     *
265
     * @return AbstractAdapter[]
266
     */
267
    public function factoryMakerFile ()
268
    {
269
        return $this->config->getMakeFileInstances ();
270
    }
271
272
    /**
273
     * conta o numero de diretorios que serao criados
274
     *
275
     * @return int
276
     */
277
    public function countDiretory ()
278
    {
279
        if ( null === $this->countDir ) {
280
            $this->countDir = 1;
281
            foreach ( $this->factoryMakerFile () as $abstractAdapter ) {
282
                if ( $abstractAdapter->hasDiretory () ) {
283
                    ++$this->countDir;
284
                }
285
            }
286
        }
287
288
        return $this->countDir;
289
    }
290
291
    /**
292
     *
293
     * parse a tpl file and return the result
294
     *
295
     * @param String $tplFile
296
     *
297
     * @return String
298
     */
299
    protected function getParsedTplContents ( $tplFile, $vars = array (), \Classes\Db\DbTable $objTables = null,
300
                                              $objMakeFile = null )
301
    {
302
303
        $arrUrl = array (
304
            __DIR__,
305
            'templates',
306
            $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...
307
            $tplFile
308
        );
309
310
        $filePath = implode ( DIRECTORY_SEPARATOR, filter_var_array ( $arrUrl ) );
311
312
        extract ( $vars );
313
        ob_start ();
314
        require $filePath;
315
        $data = ob_get_contents ();
316
        ob_end_clean ();
317
318
        return $data;
319
    }
320
321
}