Module   A
last analyzed

Complexity

Total Complexity 20

Size/Duplication

Total Lines 219
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 20
eloc 109
dl 0
loc 219
rs 10
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
F init() 0 166 13
A setTranslator() 0 25 4
A getUserConfig() 0 3 1
A getUserAdapter() 0 8 2
1
<?php
2
3
namespace Workarea;
4
5
use Auth\Model\User;
6
use Auth\Model\UserTbl;
7
use Drone\Db\TableGateway\EntityAdapter;
8
use Drone\Dom\Element\Form;
9
Use Drone\Mvc\AbstractionModule;
10
use Drone\Mvc\AbstractionController;
11
use Drone\Mvc\Layout;
12
use Drone\Validator\FormValidator;
13
use Drone\Util\ArrayDimension;
14
15
class Module extends AbstractionModule
16
{
17
    /**
18
     * @var UsersEntity
0 ignored issues
show
Bug introduced by
The type Workarea\UsersEntity was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
19
     */
20
    private $userAdapter;
21
22
    /**
23
     * @return UsersEntity
24
     */
25
    private function getUserAdapter()
26
    {
27
        if (!is_null($this->userAdapter))
28
            return $this->userAdapter;
29
30
        $this->userAdapter = new EntityAdapter(new UserTbl(new User()));
0 ignored issues
show
Documentation Bug introduced by
It seems like new Drone\Db\TableGatewa...new Auth\Model\User())) of type Drone\Db\TableGateway\EntityAdapter is incompatible with the declared type Workarea\UsersEntity of property $userAdapter.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
31
32
        return $this->userAdapter;
0 ignored issues
show
Bug Best Practice introduced by
The expression return $this->userAdapter returns the type Drone\Db\TableGateway\EntityAdapter which is incompatible with the documented return type Workarea\UsersEntity.
Loading history...
33
    }
34
35
    public function init(AbstractionController $c)
36
    {
37
        $config = $this->getUserConfig();
38
39
        $_config = ArrayDimension::toUnidimensional($config, "_");
40
41
        $this->setTranslator($c);
42
43
        $app_config = include 'config/application.config.php';
44
        $global_config = include 'config/global.config.php';
45
46
        /** LAST REQUESTED URI :
47
         * The last REQUEST_URI registered by $_SERVER. This session var is useful to redirect to the last URI requested
48
         * when users log in. It should be an unique session id for the app to prevent bad redirections with other projects.
49
         */
50
        # save only no XmlHttpRequest!
51
        if (!$c->isXmlHttpRequest())
52
            $_SESSION["last_uri_" . $global_config["project"]["id"]] = $_SERVER["REQUEST_URI"];
53
54
        # config constraints
55
        $components = [
56
            "attributes" => [
57
                "project_name" => [
58
                    "required"  => true,
59
                    "type"      => "text",
60
                    "minlength" => 2,
61
                    "maxlength" => 60
62
                ],
63
                "authentication_method" => [
64
                    "required"  => true,
65
                    "type"      => "text"
66
                ],
67
                "authentication_key" => [
68
                    "required"  => true,
69
                    "type"      => "text",
70
                    "minlength" => 1
71
                ],
72
                "database_prefix" => [
73
                    "required"  => false,
74
                    "type"      => "text"
75
                ],
76
                "redirect" => [
77
                    "required"  => true,
78
                    "type"      => "text"
79
                ]
80
            ],
81
        ];
82
83
        $options = [
84
            "project" => [
85
                "label"      => "project -> name"
86
            ],
87
            "authentication_method" => [
88
                "label"      => "authentication -> method",
89
                "validators" => [
90
                    "InArray"  => ["haystack" => ['_COOKIE', '_SESSION']]
91
                ]
92
            ],
93
            "authentication_key" => [
94
                "label"      => "authentication -> key",
95
            ],
96
            "database_prefix" => [
97
                "label"      => "database -> prefix"
98
            ],
99
            "redirect" => [
100
                "label"      => "redirect"
101
            ],
102
        ];
103
104
        $form = new Form($components);
105
        $form->fill($_config);
106
107
        $validator = new FormValidator($form, $options);
108
        $validator->validate();
109
110
        $data["validator"] = $validator;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$data was never initialized. Although not strictly required by PHP, it is generally a good practice to add $data = array(); before regardless.
Loading history...
111
112
        try
113
        {
114
            if (!$validator->isValid())
115
            {
116
                $data["messages"] = $validator->getMessages();
117
                throw new \Exception("Module config errros in user.config!", 300);
118
            }
119
120
            $redirect = $config["redirect"];
121
            $method   = $config["authentication"]["method"];
122
            $key      = $config["authentication"]["key"];
123
124
            $username_credential = null;
125
126
            switch ($method)
127
            {
128
                case '_COOKIE':
129
130
                    if (!array_key_exists($key, $_COOKIE) || empty($_COOKIE[$key]))
131
                    {
132
                        # stops current controller execution
133
                        $c->stopExecution(false);
0 ignored issues
show
Unused Code introduced by
The call to Drone\Mvc\AbstractionController::stopExecution() has too many arguments starting with false. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

133
                        $c->/** @scrutinizer ignore-call */ 
134
                            stopExecution(false);

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
134
135
                        header("location: " . $c->getBasePath() . "/public/" . $redirect);
136
                    }
137
                    else
138
                        $username_credential = $_COOKIE[$key];
139
140
                    break;
141
142
                case '_SESSION':
143
144
                    if (!array_key_exists($key, $_SESSION) || empty($_SESSION[$key]))
145
                    {
146
                        # stops current controller execution
147
                        $c->stopExecution(false);
148
149
                        header("location: " . $c->getBasePath() . "/public/" . $redirect);
150
                    }
151
                    else
152
                        $username_credential = $_SESSION[$key];
153
154
                    break;
155
            }
156
157
            # check inactivity (change user state to inactive while he's logged)
158
            $user = $this->getUserAdapter()->getTableGateway()->getUserByUsernameCredential($username_credential);
159
160
            $config = include 'module/Auth/config/user.config.php';
161
            $state_field  = $config["authentication"]["gateway"]["table_info"]["columns"]["state_field"];
162
            $active_state = $config["authentication"]["gateway"]["table_info"]["column_values"]["state_field"]["user_active"];
163
164
            if ($user->{$state_field} != $active_state)
165
                throw new \Exception("The user has been inactived!. Please log-in again.");
166
        }
167
        catch (\Exception $e)
168
        {
169
            $file = str_replace('\\', '', __CLASS__);
170
            $storage = new \Drone\Exception\Storage("cache/$file.json");
171
172
            # stores the error code
173
            if (($errorCode = $storage->store($e)) === false)
0 ignored issues
show
introduced by
The condition $errorCode = $storage->store($e) === false is always true.
Loading history...
174
            {
175
                $errors = $storage->getErrors();
0 ignored issues
show
Unused Code introduced by
The assignment to $errors is dead and can be removed.
Loading history...
176
177
                # if error storing is not possible, handle it (internal app error)
178
                //$this->handleErrors($errors, __METHOD__);
179
            }
180
181
            $data["code"]    = $errorCode;
182
            $data["message"] = $e->getMessage();
183
184
            $data["dev_mode"] = $app_config["environment"]["dev_mode"];
185
186
            # stops current controller execution
187
            $c->stopExecution(false);
188
189
            # loads error view
190
            $layoutManager = new Layout();
191
            $layoutManager->setBasePath($c->getBasePath());
192
193
            $layoutManager->setView($this, "validation");
194
            $layoutManager->setParams($data);
195
196
            # for AJAX requests!
197
            if ($c->isXmlHttpRequest())
198
                $layoutManager->content();
199
            else
200
                $layoutManager->fromTemplate($this, 'blank');
201
        }
202
    }
203
204
    private function setTranslator(AbstractionController $c)
205
    {
206
        $config = include('config/application.config.php');
207
208
        if (array_key_exists('locale', $_GET))
209
        {
210
            if (in_array($_GET['locale'], ['en', 'es', 'fr']))
211
                $_SESSION["LOCALE"] = $_GET['locale'];
212
        }
213
214
        $locale = (array_key_exists('LOCALE', $_SESSION)) ? $_SESSION["LOCALE"] : $config["environment"]["locale"];
215
216
        $i18nTranslator = \Zend\I18n\Translator\Translator::factory(
217
            [
218
                'locale'  => "$locale",
219
                'translation_files' => [
220
                    [
221
                        "type" => 'phparray',
222
                        "filename" => __DIR__ . "/lang/$locale.php"
223
                    ]
224
                ]
225
            ]
226
        );
227
228
        $c->translator = new \Zend\Mvc\I18n\Translator($i18nTranslator);
0 ignored issues
show
Bug introduced by
The property translator does not seem to exist on Drone\Mvc\AbstractionController.
Loading history...
229
    }
230
231
    public function getUserConfig()
232
    {
233
        return include __DIR__ . "/config/user.config.php";
234
    }
235
}