Completed
Push — master ( b08cbc...cad261 )
by Hugo
05:30 queued 02:35
created

ControllerBase   B

Complexity

Total Complexity 36

Size/Duplication

Total Lines 242
Duplicated Lines 7.44 %

Coupling/Cohesion

Components 1
Dependencies 6
Metric Value
wmc 36
lcom 1
cbo 6
dl 18
loc 242
rs 8.8

19 Methods

Rating   Name   Duplication   Size   Complexity  
A afterExecuteRoute() 0 10 2
A indexAction() 0 19 4
A getInstance() 0 10 2
A readAction() 0 8 2
A setValuesToObject() 0 4 1
B updateAction() 0 24 5
A soloUpdateAction() 10 10 1
A deleteAction() 8 8 2
A asAdminAction() 0 6 1
A asUserAction() 0 6 1
A logoutAction() 0 5 1
B loadAclAction() 0 30 5
A verifyAccessAction() 0 15 3
A _showDisplayedMessage() 0 4 1
A _showMessage() 0 5 1
A messageSuccess() 0 4 1
A messageWarning() 0 4 1
A messageDanger() 0 4 1
A messageInfo() 0 4 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
2
3
use Phalcon\Mvc\Controller;
4
5
use Phalcon\Acl\Adapter\Memory as AclList;
6
use Phalcon\Acl\Role;
7
use Phalcon\Acl\Resource;
8
use Phalcon\Mvc\Url;
9
10
class ControllerBase extends Controller
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
11
{
12
13
    protected $model;
14
    protected $title;
15
    protected $controller;
16
    protected $messageTimerInterval = 3000;
17
18
    public function afterExecuteRoute($dispatcher)
19
    {
20
        $baseUrl = $this->baseUrl;
21
        $this->view->setVar("baseUrl", $baseUrl);
22
        $this->view->setVar("controller", $this->controller);
23
        $this->view->setVar("title", $this->title);
24
        if ($this->verifyAccessAction($this->controller, "index")) {
25
            $msg = "";
0 ignored issues
show
Unused Code introduced by
$msg is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
26
        }
27
    }
28
29
    public function indexAction($message = NULL)
30
    {
31
    if ($this->verifyAccessAction($this->controller, "index")) {
32
        $msg = "";
33
        if (isset($message)) {
34
            if (is_string($message)) {
35
                $message = new DisplayedMessage($message);
36
            }
37
            $message->setTimerInterval($this->messageTimerInterval);
38
            $msg = $this->_showDisplayedMessage($message);
39
        }
40
        $this->view->setVar("msg", $msg);
41
        $objects = call_user_func($this->model . "::find");
42
        $this->view->setVar("objects", $objects);
43
        $this->view->pick("main/index");
44
        } else {
45
            $this->view->pick("main/error");
46
    	}
47
    }
48
49
    public function getInstance($id = NULL)
50
    {
51
        if (isset($id)) {
52
            $object = call_user_func($this->model . "::findfirst", $id);
53
        } else {
54
            $className = $this->model;
55
            $object = new $className();
56
        }
57
        return $object;
58
    }
59
60
    public function readAction($id = NULL)
61
    {
62
        if ($id != null) {
63
            $object = call_user_func($this->model . '::find', "id = $id");
64
            $this->view->setVar("object", $object);
65
            $this->view->pick("main/read");
66
        }
67
    }
68
69
70
    protected function setValuesToObject(&$object)
0 ignored issues
show
Coding Style introduced by
setValuesToObject uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
71
    {
72
        $object->assign($_POST);
73
    }
74
75
76
    public function updateAction()
0 ignored issues
show
Coding Style introduced by
updateAction uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
77
    {
78
        $id = $this->request->getPost('id', 'int');
79
        if ($this->request->isPost()) {
80
            $object = $this->getInstance(@$_POST["id"]);
81
            $this->setValuesToObject($object);
82
            if ($id) {
83
                try {
84
                    $object->save();
85
                    $msg = new DisplayedMessage("Instance de " . $this->model . " modifiée");
86
                } catch (\Exception $e) {
87
                    $msg = new DisplayedMessage("Impossible d'ajouter l'instance de " . $this->model, "danger : $e");
88
                }
89
            } else {
90
                try {
91
                    $object->save();
92
                    $msg = new DisplayedMessage("Instance de " . $this->model . " ajoutée");
93
                } catch (\Exception $e) {
94
                    $msg = new DisplayedMessage("Impossible d'ajouter l'instance de " . $this->model, "danger : $e");
95
                }
96
            }
97
            $this->dispatcher->forward(array("controller" => $this->dispatcher->getControllerName(), "action" => "index", "params" => array($msg)));
98
        }
99
    }
100
101
    //PErmet l'édition d'un seul champ à la fois
102 View Code Duplication
    public function soloUpdateAction()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
Coding Style introduced by
soloUpdateAction uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
103
    {
104
        $name = $this->request->getPost('name', 'string');
105
        //Créer la fonction variable 'set' en fonction du name en POST
106
        $func = 'set' . ucfirst($name);
107
        $projet = call_user_func($this->model . '::findFirst', $_POST['pk']);
108
        $projet->$func($_POST['value']);
109
        $projet->save();
110
111
    }
112
113
114 View Code Duplication
    public function deleteAction($id = null)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in 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...
115
    {
116
        if ($this->verifyAccessAction($this->controller, "write")) {
117
            $object = call_user_func($this->model . '::findFirst', "$id");
118
            $object->delete();
119
        }
120
        $this->response->redirect("$this->controller/index");
121
    }
122
123
    public function asAdminAction()
124
    {
125
        $user = User::findFirst("id=3");
126
        $this->session->set("user", $user);
127
        $this->response->redirect("$this->controller/index");
128
    }
129
130
    public function asUserAction()
131
    {
132
        $user = User::findFirst("id=1");
133
        $this->session->set("user", $user);
134
        $this->response->redirect("$this->controller/index");
135
    }
136
137
    public function logoutAction()
138
    {
139
        $this->session->destroy();
140
        $this->response->redirect("Index/index");
141
    }    
142
    
143
    public function loadAclAction($typeUser) {
144
    	$acl = new AclList();
145
    	$acl->setDefaultAction(Phalcon\Acl::DENY);
146
    	
147
    	$roles = TypeUser::find();
148
    	foreach ($roles as $role) {
149
    		$acl->addRole($role->getLibelle());
150
    	}
151
152
    	$operationsBdd = Operation::find();
153
    	$operations = array();
154
    	foreach ($operationsBdd as $operation) {
155
    		$operations[] = $operation->getOperation();
156
    	}
157
    	
158
    	$ressources = Ressource::find();
159
    	foreach ($ressources as $ressource) {
160
    		$acl->addResource($ressource->getLibelle(), $operations);
161
    	}
162
 
163
    	$aclsBdd = Acl::find();
164
    	foreach ($aclsBdd as $aclBdd) {
165
    		$typeUserBdd = TypeUser::findFirst("id = ".$aclBdd->getIdTypeUser());
166
    		$ressourceBdd = Ressource::findFirst("id = ".$aclBdd->getIdRessource());
167
    		$operationBdd = Operation::findFirst("id = ".$aclBdd->getIdOperation());
168
    		$acl->allow($typeUserBdd->getLibelle(), $ressourceBdd->getLibelle(), $operationBdd->getOperation());
169
    	}
170
    	
171
    	return $acl;
172
    }
173
    
174
    public function verifyAccessAction($activeResource, $activeOperation) {
175
        if($this->session->has("user")){
176
            $user = $this->session->get("user");
177
            $typeUser = TypeUser::findFirst("id = ".$user->getIdTypeUser());
178
            $typeUserSession = $user->getIdTypeUser();
179
            $acl = $this->loadAclAction($typeUserSession);
180
            if ($acl->isAllowed($typeUser->getLibelle(), $activeResource, $activeOperation)) {
181
                return 1;
182
            } else {
183
                return 0;
184
            }
185
        }else{
186
            return 0;
187
        }
188
    }
189
190
    /**
191
     * Affiche un message Alert bootstrap
192
     * @param DisplayedMessage $message
193
     */
194
    public function _showDisplayedMessage($message)
195
    {
196
        return $message->compile($this->jquery);
197
    }
198
199
    /**
200
     * Affiche un message Alert bootstrap
201
     * @param string $message texte du message
202
     * @param string $type type du message (info, success, warning ou danger)
203
     * @param number $timerInterval durée en millisecondes d'affichage du message (0 pour que le message reste affiché)
204
     * @param string $dismissable si vrai, l'alert dispose d'une croix de fermeture
205
     */
206
    public function _showMessage($message, $type = "success", $timerInterval = 0, $dismissable = true, $visible = true)
207
    {
208
        $message = new DisplayedMessage($message, $type, $timerInterval, $dismissable, $visible);
0 ignored issues
show
Bug introduced by
It seems like $dismissable defined by parameter $dismissable on line 206 can also be of type string; however, DisplayedMessage::DisplayedMessage() does only seem to accept boolean, maybe add an additional type check?

This check looks at variables that have been passed in as parameters and are passed out again to other methods.

If the outgoing method call has stricter type requirements than the method itself, an issue is raised.

An additional type check may prevent trouble.

Loading history...
209
        $this->_showDisplayedMessage($message);
210
    }
211
212
213
    public function messageSuccess($message, $timerInterval = 0, $dismissable = true)
214
    {
215
        $this->_showMessage($message, "success", $timerInterval, $dismissable);
216
    }
217
218
    /**
219
     * Affiche un message Alert bootstrap de type warning
220
     * @param string $message texte du message
221
     * @param number $timerInterval durée en millisecondes d'affichage du message (0 pour que le message reste affiché)
222
     * @param string $dismissable si vrai, l'alert dispose d'une croix de fermeture
223
     */
224
    public function messageWarning($message, $timerInterval = 0, $dismissable = true)
225
    {
226
        $this->_showMessage($message, "warning", $timerInterval, $dismissable);
227
    }
228
229
    /**
230
     * Affiche un message Alert bootstrap de type danger
231
     * @param string $message texte du message
232
     * @param number $timerInterval durée en millisecondes d'affichage du message (0 pour que le message reste affiché)
233
     * @param string $dismissable si vrai, l'alert dispose d'une croix de fermeture
234
     */
235
    public function messageDanger($message, $timerInterval = 0, $dismissable = true)
236
    {
237
        $this->_showMessage($message, "danger", $timerInterval, $dismissable);
238
    }
239
240
    /**
241
     * Affiche un message Alert bootstrap de type info
242
     * @param string $message texte du message
243
     * @param number $timerInterval durée en millisecondes d'affichage du message (0 pour que le message reste affiché)
244
     * @param string $dismissable si vrai, l'alert dispose d'une croix de fermeture
245
     */
246
    public function messageInfo($message, $timerInterval = 0, $dismissable = true)
247
    {
248
        $this->_showMessage($message, "info", $timerInterval, $dismissable);
249
    }
250
251
}
252