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 ( 468b27...953a93 )
by Pedro
03:00
created

Config   B

Complexity

Total Complexity 42

Size/Duplication

Total Lines 328
Duplicated Lines 0 %

Coupling/Cohesion

Components 3
Dependencies 8

Importance

Changes 0
Metric Value
wmc 42
lcom 3
cbo 8
dl 0
loc 328
rs 8.295
c 0
b 0
f 0

12 Methods

Rating   Name   Duplication   Size   Complexity  
B __construct() 0 19 6
A getUsage() 0 13 1
A renderParam() 0 17 3
A checkHasNewVersion() 0 23 3
A getVersion() 0 6 1
B parseConfig() 0 26 4
A parseConfigEnv() 0 19 4
B loadIniFile() 0 31 5
A factoryConfig() 0 13 3
B factoryDriver() 0 18 8
A getAdapterConfig() 0 9 2
A getAdapterDriver() 0 9 2

How to fix   Complexity   

Complex Class

Complex classes like Config often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Config, and based on these observations, apply Extract Interface, too.

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 28 and the first side effect is on line 15.

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\AdapterConfig\None;
6
use Classes\AdapterConfig\Phalcon;
7
use Classes\AdapterConfig\ZendFrameworkOne;
8
use Classes\AdapterMakerFile\AbstractAdapter;
9
use Classes\AdaptersDriver\Dblib;
10
use Classes\AdaptersDriver\Mssql;
11
use Classes\AdaptersDriver\Mysql;
12
use Classes\AdaptersDriver\Pgsql;
13
use Classes\AdaptersDriver\Sqlsrv;
14
15
require_once 'AdapterConfig/None.php';
16
require_once 'AdapterConfig/Phalcon.php';
17
require_once 'AdapterConfig/ZendFrameworkOne.php';
18
require_once 'AdaptersDriver/Dblib.php';
19
require_once 'AdaptersDriver/Mssql.php';
20
require_once 'AdaptersDriver/Mysql.php';
21
require_once 'AdaptersDriver/Pgsql.php';
22
require_once 'AdaptersDriver/Sqlsrv.php';
23
24
/**
25
 * @author Pedro Alarcao <[email protected]>
26
 * @link   https://github.com/pedro151/orm-generator
27
 */
28
class Config
29
{
30
31
    /**
32
     * @var string
33
     */
34
    public static $version = "1.4.8";
35
36
    /**
37
     * String that separates the parent section name
38
     *
39
     * @var string
40
     */
41
    protected $sectionSeparator = ':';
42
43
    /**
44
     * @var string
45
     */
46
    private $configIniDefault = '/configs/config.ini';
47
48
    /**
49
     * @var string
50
     */
51
    public $_basePath;
52
    /**
53
     * @var array
54
     */
55
    private $argv = array ();
56
57
    /**
58
     * @var \Classes\AdapterConfig\AbstractAdapter
59
     */
60
    private $adapterConfig;
61
62
    /**
63
     * @var \Classes\AdaptersDriver\AbsractAdapter
64
     */
65
    private $adapterDriver;
66
67
    private $frameworkList = array (
68
        'none' ,
69
        'zf1' ,
70
        'phalcon'
71
    );
72
73
    private $parameterList = array (
74
        'init'        => 'Creates the necessary configuration file to start using the orm-generator.' ,
75
        'name-ini'  => 'reference to another .ini file configuration (relative path).' ,
76
        'config-env'  => 'orm-generator configuration environment.' ,
77
        'framework'   => 'name framework used, which has the contents of the database configurations and framework template.' ,
78
        'driver'      => 'database driver name (Ex.: pgsql).' ,
79
        'database'    => 'database name.' ,
80
        'schema'      => 'database schema name (one or more than one).' ,
81
        'tables'      => 'table name (parameter can be used more then once).' ,
82
        'clean-trash' => 'delete all files that do not belong to your Database due' ,
83
        'status'      => 'show status of implementation carried out after completing the process.' ,
84
        'version'     => 'shows the version of orm-generator.' ,
85
        'help'        => "help command explaining all the options and manner of use." ,
86
        'path'        => "specify where to create the files (default is current directory)." ,
87
    );
88
89
    public function __construct ( $argv , $basePath , $numArgs )
90
    {
91
        if ( array_key_exists ( 'help' , $argv ) or ( $numArgs > 1
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...
92
                                                      && count ( $argv ) < 1 )
93
        )
94
        {
95
            die ( $this->getUsage () );
0 ignored issues
show
Coding Style Compatibility introduced by
The method __construct() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
96
        }
97
        if ( array_key_exists ( 'version' , $argv ) )
98
        {
99
            die ( $this->getVersion () );
0 ignored issues
show
Coding Style Compatibility introduced by
The method __construct() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
100
        }
101
        if ( array_key_exists ( 'status' , $argv ) )
102
        {
103
            $argv[ 'status' ] = true;
104
        }
105
106
        $this->argv = $this->parseConfig ( $basePath , $argv );
107
    }
108
109
    /**
110
     * Lista de ajuda quando digita 'help'
111
     *
112
     * @return string
113
     */
114
    public function getUsage ()
115
    {
116
        $version = $this->getVersion ();
117
        $list = $this->renderParam ();
118
119
        return <<<EOF
120
parameters:
121
$list
122
 example: php generate.php --framework=zf1 --database=foo --table=foobar --status
123
124
$version
125
EOF;
126
    }
127
128
    public function renderParam ()
129
    {
130
        $return = "";
131
        foreach ( $this->parameterList as $param => $desc )
132
        {
133
            if ( strlen ( $param ) < 5 )
134
            {
135
                $return .= "\t--" . $param . "\t\t: " . $desc . "\n";
136
            } else
137
            {
138
                $return .= "\t--" . $param . "\t: " . $desc . "\n";
139
            }
140
141
        }
142
143
        return $return;
144
    }
145
146
    public function checkHasNewVersion ()
147
    {
148
        $opts = array (
149
            'http' => array (
150
                'method' => 'GET' ,
151
                'header' => array (
152
                    'User-Agent: PHP'
153
                )
154
            )
155
        );
156
157
        try
158
        {
159
            $context = stream_context_create ( $opts );
160
            $tags = json_decode ( file_get_contents ( "https://api.github.com/repos/pedro151/orm-generator/tags" , false , $context ) );
161
162
            $lastVersion = preg_replace ( "/[^0-9.]/" , "" , $tags[ 0 ]->name );
163
            if ( $lastVersion > static::$version )
164
            {
165
                return "\033[0;31mThere is a new version $lastVersion available:\033[0m https://github.com/pedro151/orm-generator\n";
166
            }
167
        } catch ( \Exception $ex ){ }
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
168
    }
169
170
    public function getVersion ()
171
    {
172
        $version = static::$version;
173
174
        return "ORM Generator By: Pedro Alarcao Version: $version\n".$this->checkHasNewVersion();
175
    }
176
177
    /**
178
     * Analisa e estrutura a Configuracao do generate
179
     *
180
     * @param  string $basePath
181
     * @param array   $argv
182
     *
183
     * @return array
184
     * @throws \Exception
185
     */
186
    private function parseConfig ( $basePath , $argv )
187
    {
188
        $this->_basePath = $basePath;
189
190
        $configIni = isset( $argv[ 'name-ini' ] )
191
            ? $argv[ 'name-ini' ]
192
            : $this->_basePath
193
              . $this->configIniDefault;
194
195
        $configTemp = $this->loadIniFile ( realpath ( $configIni ) );
196
        $configCurrent = self::parseConfigEnv ( $configTemp , $argv );
197
198
        if ( ! isset( $configCurrent[ 'framework' ] ) )
199
        {
200
            throw new \Exception( "configure which framework you want to use! \n" );
201
        }
202
203
        if ( ! in_array ( $configCurrent[ 'framework' ] , $this->frameworkList ) )
204
        {
205
            $frameworks = implode ( "\n\t" , $this->frameworkList );
206
            throw new \Exception( "list of frameworks: \n\t\033[1;33m" . $frameworks
207
                                  . "\n\033[0m" );
208
        }
209
210
        return $argv + array_filter ( $configCurrent );
211
    }
212
213
    /**
214
     *
215
     * @param $configTemp
216
     * @param $argv
217
     *
218
     * @return string
219
     */
220
    private static function parseConfigEnv ( $configTemp , $argv )
221
    {
222
        $thisSection = isset( $configTemp[ key ( $configTemp ) ][ 'config-env' ] )
223
            ? $configTemp[ key (
224
                $configTemp
225
            ) ][ 'config-env' ] : null;
226
227
        $thisSection = isset( $argv[ 'config-env' ] ) ? $argv[ 'config-env' ]
228
            : $thisSection;
229
230
        if ( isset( $configTemp[ $thisSection ][ 'extends' ] ) )
231
        {
232
            #faz marge da config principal com a config extendida
233
            return $configTemp[ $thisSection ]
234
                   + $configTemp[ $configTemp[ $thisSection ][ 'extends' ] ];
235
        }
236
237
        return $configTemp[ key ( $configTemp ) ];
238
    }
239
240
    /**
241
     * Carregar o arquivo ini e pré-processa o separador de seção ':'
242
     * no nome da seção (que é usado para a extensão seção) de modo a que a
243
     * matriz resultante tem os nomes de seção corretos e as informações de
244
     * extensão é armazenado em uma sub-ch ve
245
     *
246
     * @param string $filename
247
     *
248
     * @throws \Exception
249
     * @return array
250
     */
251
    protected function loadIniFile ( $filename )
252
    {
253
        if ( ! is_file ( $filename ) )
254
        {
255
            throw new \Exception( "\033[0;31mError: configuration file does not exist! \033[0m\n" );
256
        }
257
258
        $loaded = parse_ini_file ( $filename , true );
259
        $iniArray = array ();
260
        foreach ( $loaded as $key => $data )
261
        {
262
            $pieces = explode ( $this->sectionSeparator , $key );
263
            $thisSection = trim ( $pieces[ 0 ] );
264
            switch ( count ( $pieces ) )
265
            {
266
                case 1:
267
                    $iniArray[ $thisSection ] = $data;
268
                    break;
269
270
                case 2:
271
                    $extendedSection = trim ( $pieces[ 1 ] );
272
                    $iniArray[ $thisSection ] = array_merge ( array ( 'extends' => $extendedSection ) , $data );
273
                    break;
274
275
                default:
276
                    throw new \Exception( "Section '$thisSection' may not extend multiple sections in $filename" );
277
            }
278
        }
279
280
        return $iniArray;
281
    }
282
283
    /**
284
     * analisa a opção e cria a instancia do Atapter do determinado framework
285
     *
286
     * @return \Classes\AdapterConfig\AbstractAdapter
287
     *
288
     */
289
    private function factoryConfig ()
290
    {
291
        switch ( strtolower ( $this->argv[ 'framework' ] ) )
292
        {
293
            case 'zf1':
294
                return new ZendFrameworkOne( $this->argv );
295
            case 'phalcon':
296
                return new Phalcon( $this->argv );
297
            default:
298
                return new None( $this->argv );
299
        }
300
301
    }
302
303
    /**
304
     * Analisa a opção e instancia o determinado banco de dados
305
     *
306
     * @param AdapterConfig\AbstractAdapter $config
307
     *
308
     * @return AdaptersDriver\AbsractAdapter
309
     */
310
    private function factoryDriver ( AdapterConfig\AbstractAdapter $config )
311
    {
312
        switch ( $this->argv[ 'driver' ] )
313
        {
314
            case 'pgsql':
315
            case 'pdo_pgsql':
316
                return new Pgsql( $config );
317
            case 'mysql':
318
            case 'pdo_mysql':
319
                return new Mysql( $config );
320
            case 'mssql':
321
                return new Mssql( $config );
322
            case 'dblib':
323
                return new Dblib( $config );
324
            case 'sqlsrv':
325
                return new Sqlsrv( $config );
326
        }
327
    }
328
329
    /**
330
     * @return AdapterConfig\AbstractAdapter
331
     */
332
    public function getAdapterConfig ()
333
    {
334
        if ( ! $this->adapterConfig instanceof AbstractAdapter )
335
        {
336
            $this->adapterConfig = $this->factoryConfig ();
337
        }
338
339
        return $this->adapterConfig;
340
    }
341
342
    /**
343
     * @return AdaptersDriver\AbsractAdapter
344
     */
345
    public function getAdapterDriver ( AdapterConfig\AbstractAdapter $config )
346
    {
347
        if ( ! $this->adapterDriver )
348
        {
349
            $this->adapterDriver = $this->factoryDriver ( $config );
350
        }
351
352
        return $this->adapterDriver;
353
    }
354
355
}
356