Completed
Push — master ( 868d3a...389cae )
by Richard
06:14
created

App   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 130
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 1
Bugs 1 Features 0
Metric Value
wmc 12
c 1
b 1
f 0
lcom 1
cbo 9
dl 0
loc 130
rs 10

6 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 6 2
A run() 0 18 2
A load_rules_file() 0 10 2
A load_extra_configs() 0 8 3
A create_config() 0 3 1
B create_dic() 0 42 2
1
<?php
2
/******************************************************************************
3
 * An implementation of dicto (scg.unibe.ch/dicto) in and for PHP.
4
 * 
5
 * Copyright (c) 2016 Richard Klees <[email protected]>
6
 *
7
 * This software is licensed under The MIT License. You should have received 
8
 * a copy of the licence along with the code.
9
 */
10
11
namespace Lechimp\Dicto\App;
12
13
use Lechimp\Dicto\App\RuleFromFSLoader;
14
15
use Symfony\Component\Yaml\Yaml;
16
use Pimple\Container;
17
use PhpParser\ParserFactory;
18
use Doctrine\DBAL\DriverManager;
19
20
/**
21
 * The App to be run from a script.
22
 */
23
class App {
24
    /**
25
     * @var Container
26
     */
27
    protected $dic;
28
29
    public function __construct(\Closure $postprocess_dic = null) {
30
        if ($postprocess_dic === null) {
31
            $postprocess_dic = function($c) { return $c; };
32
        }
33
        $this->dic = $this->create_dic($postprocess_dic); 
34
    }
35
36
    /**
37
     * Run the app.
38
     *
39
     * @param   array   $params     from commandline
40
     * @return  null
41
     */
42
    public function run(array $params) {
43
        if (count($params) < 2) {
44
            throw new \RuntimeException(
45
                "Expected path to rule-file as first parameter.");
46
        }
47
48
        $configs = array();
49
        list($ruleset, $configs[]) = $this->load_rules_file($params[1]);
0 ignored issues
show
Unused Code introduced by
The assignment to $ruleset is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
50
51
        // drop programm name and rule file path
52
        array_shift($params);
53
        array_shift($params);
54
55
        $this->load_extra_configs($params, $configs);
56
57
        $this->dic["config"] = $this->create_config($configs);
58
        $this->dic["engine"]->run();
59
    }
60
61
    /**
62
     * Load rules and initial config from a *.php-file.
63
     *
64
     * @param   string  $path
65
     * @return  array   ($ruleset, $config)
66
     */
67
    protected function load_rules_file($path) {
68
        if (!file_exists($path)) {
69
            throw new \RuntimeException("Unknown rule-file '$path'");
70
        }
71
        $rule_loader = $this->dic["rule_loader"];
72
        list($ruleset, $config) = $rule_loader->load_rules_from($path);
73
        assert('is_array($config)');
74
        assert('$ruleset instanceof \\Lechimp\\Dicto\\Definition\\RuleSet');
75
        return array($ruleset, $config);
76
    }
77
78
    /**
79
     * Load extra configs from yaml files.
80
     *
81
     * @param   array   $config_file_paths
82
     * @param   &array  $configs_array
0 ignored issues
show
Documentation introduced by
The doc-type &array could not be parsed: Unknown type name "&array" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
83
     * @return  null
84
     */
85
    protected function load_extra_configs(array $config_file_paths, array &$configs_array) {
0 ignored issues
show
Unused Code introduced by
The parameter $configs_array is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
86
        foreach ($config_file_paths as $config_file) {
87
            if (!file_exists($config_file)) {
88
                throw new \RuntimeException("Unknown config-file '$config_file'");
89
            }
90
            $configs[] = Yaml::parse(file_get_contents($config_file));
0 ignored issues
show
Coding Style Comprehensibility introduced by
$configs was never initialized. Although not strictly required by PHP, it is generally a good practice to add $configs = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
91
        }
92
    }
93
94
    /**
95
     * Create a validated config from arrays containing config chunks.
96
     *
97
     * @param   array[] $configs
98
     * @return  Config
99
     */
100
    protected function create_config(array $configs) {
101
        return new Config($configs);
102
    }
103
104
    /**
105
     * Create and initialize the DI-container.
106
     *
107
     * @param   \Closure    $postprocess_dic    Closure to postprocess the DI.
108
     * @return  Container
109
     */
110
    protected function create_dic(\Closure $postprocess_dic) {
111
        $container = new Container();
112
113
        $container["rule_loader"] = function($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
114
            return new RuleFromFSLoader(); 
115
        };
116
117
        $container["engine"] = function($c) {
118
            return new Engine($c["config"], $c["indexer"], $c["database"]);
119
        };
120
121
        $container["indexer"] = function($c) {
122
            return new \Lechimp\Dicto\Indexer\PhpParser\Indexer($c["php_parser"]);
123
        };
124
125
        $container["php_parser"] = function($c) {
0 ignored issues
show
Unused Code introduced by
The parameter $c is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
126
            return (new ParserFactory)->create(ParserFactory::PREFER_PHP7);
127
        };
128
129
        $container["database"] = function($c) {
130
            $db = new DB($c["connection"]);
131
            $db->init_sqlite_regexp();
132
            $db->maybe_init_database_schema();
133
        };
134
135
        $container["connection"] = function($c) {
136
            return DriverManager::getConnection
137
                ( array
138
                    ( "driver" => "pdo_sqlite"
139
                    , "memory" => $c["config"]->sqlite_memory()
140
                    , "path" => $c["config"]->sqlite_path()
141
                    )
142
                );
143
        };
144
145
        $container = $postprocess_dic($container);
146
        if (!($container instanceof Container)) {
147
            throw new \RuntimeException
148
                ("DIC postprocessor did not return a Container.");
149
        }
150
        return $container;
151
    }
152
}
153