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 (#8)
by Pedro
03:38
created

MakerFile   A

Complexity

Total Complexity 29

Size/Duplication

Total Lines 285
Duplicated Lines 3.86 %

Coupling/Cohesion

Components 1
Dependencies 6

Importance

Changes 20
Bugs 5 Features 0
Metric Value
wmc 29
c 20
b 5
f 0
lcom 1
cbo 6
dl 11
loc 285
rs 10

12 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
B parseReservedWord() 11 28 6
A filterLocation() 0 9 2
B parseLocation() 0 52 5
A getConfig() 0 4 1
A startTime() 0 5 1
A getRunTime() 0 4 1
B run() 0 49 5
A reportProcess() 0 14 2
A factoryMakerFile() 0 4 1
A countDiretory() 0 12 3
A getParsedTplContents() 0 21 1

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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