ControllerBase::_showMessage()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 5
rs 9.4285
cc 1
eloc 3
nc 1
nop 5
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
    }
25
26
    public function frmAction(){
27
28
    }
29
30
    public function indexAction($message = NULL)
31
    {
32
    if ($this->verifyAccessAction($this->controller, "index")) {
33
        $msg = "";
34
        if (isset($message)) {
35
            if (is_string($message)) {
36
                $message = new DisplayedMessage($message);
37
            }
38
            $message->setTimerInterval($this->messageTimerInterval);
39
            $msg = $this->_showDisplayedMessage($message);
40
        }
41
        $this->view->setVar("msg", $msg);
42
        $objects = call_user_func($this->model . "::find");
43
        $this->view->setVar("objects", $objects);
44
        $this->view->pick("main/index");
45
        } else {
46
            $this->view->pick("main/error");
47
    	}
48
    }
49
50
    public function getInstance($id = NULL)
51
    {
52
        if (isset($id)) {
53
            $object = call_user_func($this->model . "::findfirst", $id);
54
        } else {
55
            $className = $this->model;
56
            $object = new $className();
57
        }
58
        return $object;
59
    }
60
61
    public function readAction($id = NULL)
62
    {
63
        if ($this->verifyAccessAction($this->controller, "read")) {
64
            if ($id != null) {
65
                $object = call_user_func($this->model . '::find', "id = $id");
66
                $this->view->setVar("object", $object);
67
                $this->view->pick("main/read");
68
            }
69
        }else{
0 ignored issues
show
Unused Code introduced by
This else statement is empty and can be removed.

This check looks for the else branches of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These else branches can be removed.

if (rand(1, 6) > 3) {
print "Check failed";
} else {
    //print "Check succeeded";
}

could be turned into

if (rand(1, 6) > 3) {
    print "Check failed";
}

This is much more concise to read.

Loading history...
70
71
        }
72
    }
73
74
75
    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...
76
    {
77
        $object->assign($_POST);
78
    }
79
80
81
    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...
82
    {
83
        if ($this->verifyAccessAction($this->controller, "write")) {
84
85
            $id = $this->request->getPost('id', 'int');
86
            if ($this->request->isPost()) {
87
                $object = $this->getInstance(@$_POST["id"]);
88
                $this->setValuesToObject($object);
89
                if ($id) {
90
                    try {
91
                        $object->save();
92
                        $msg = new DisplayedMessage("Instance de " . $this->model . " modifiée");
93
                    } catch (\Exception $e) {
94
                        $msg = new DisplayedMessage("Impossible d'ajouter l'instance de " . $this->model, "danger : $e");
95
                    }
96
                } else {
97
                    try {
98
                        $object->save();
99
                        $msg = new DisplayedMessage("Instance de " . $this->model . " ajoutée");
100
                    } catch (\Exception $e) {
101
                        $msg = new DisplayedMessage("Impossible d'ajouter l'instance de " . $this->model, "danger : $e");
102
                    }
103
                }
104
                $this->dispatcher->forward(array("controller" => $this->dispatcher->getControllerName(), "action" => "index", "params" => array($msg)));
105
            }
106
        }
107
    }
108
109
    //PErmet l'édition d'un seul champ à la fois
110
    public function soloUpdateAction()
0 ignored issues
show
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...
111
    {
112
        if ($this->verifyAccessAction($this->controller, "write")) {
113
            if($this->session->has("user") && ($this->session->get("user")->getId() == $this->request->getPost('pk', 'int')) || $this->session->get("user")->getIdTypeUser() == 0){
114
                $name = $this->request->getPost('name', 'string');
115
                //Créer la fonction variable 'set' en fonction du name en POST
116
                $func = 'set' . ucfirst($name);
117
                $projet = call_user_func($this->model . '::findFirst', $_POST['pk']);
118
                $projet->$func($_POST['value']);
119
                $projet->save();
120
            }
121
        }
122
123
    }
124
125
126 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...
127
    {
128
        if ($this->verifyAccessAction($this->controller, "write")) {
129
            $object = call_user_func($this->model . '::findFirst', "$id");
130
            $object->delete();
131
        }
132
133
        $this->response->redirect("$this->controller/index");
134
    }
135
136
    public function asAdminAction()
137
    {
138
        $user = User::findFirst("id=3");
139
        $this->session->set("user", $user);
140
        $this->response->redirect("$this->controller/index");
141
    }
142
143
    public function asUserAction()
144
    {
145
        $user = User::findFirst("id=1");
146
        $this->session->set("user", $user);
147
        $this->response->redirect("$this->controller/index");
148
    }
149
150
    public function logoutAction()
151
    {
152
        $this->session->destroy();
153
        $this->response->redirect("Index/index");
154
    }    
155
    
156
    public function loadAclAction($typeUser) {
157
    	$acl = new AclList();
158
    	$acl->setDefaultAction(Phalcon\Acl::DENY);
159
    	
160
    	$roles = TypeUser::find();
161
    	foreach ($roles as $role) {
162
    		$acl->addRole($role->getLibelle());
163
    	}
164
165
    	$operationsBdd = Operation::find();
166
    	$operations = array();
167
    	foreach ($operationsBdd as $operation) {
168
    		$operations[] = $operation->getOperation();
169
    	}
170
    	
171
    	$ressources = Ressource::find();
172
    	foreach ($ressources as $ressource) {
173
    		$acl->addResource($ressource->getLibelle(), $operations);
174
    	}
175
 
176
    	$aclsBdd = Acl::find();
177
    	foreach ($aclsBdd as $aclBdd) {
178
    		$typeUserBdd = TypeUser::findFirst("id = ".$aclBdd->getIdTypeUser());
179
    		$ressourceBdd = Ressource::findFirst("id = ".$aclBdd->getIdRessource());
180
    		$operationBdd = Operation::findFirst("id = ".$aclBdd->getIdOperation());
181
    		$acl->allow($typeUserBdd->getLibelle(), $ressourceBdd->getLibelle(), $operationBdd->getOperation());
182
    	}
183
    	
184
    	return $acl;
185
    }
186
    
187
    public function verifyAccessAction($activeResource, $activeOperation) {
188
        if($this->session->has("user")){
189
            $user = $this->session->get("user");
190
            $typeUser = TypeUser::findFirst("id = ".$user->getIdTypeUser());
191
            $typeUserSession = $user->getIdTypeUser();
192
            $acl = $this->loadAclAction($typeUserSession);
193
            if ($acl->isAllowed($typeUser->getLibelle(), $activeResource, $activeOperation)) {
194
                return 1;
195
            } else {
196
                return 0;
197
            }
198
        }else{
199
            return 0;
200
        }
201
    }
202
203
204
    public function moreAction(){
205
        $this->view->pick("main/more");
206
    }
207
208
    /**
209
     * Affiche un message Alert bootstrap
210
     * @param DisplayedMessage $message
211
     */
212
    public function _showDisplayedMessage($message)
213
    {
214
        return $message->compile($this->jquery);
215
    }
216
217
    /**
218
     * Affiche un message Alert bootstrap
219
     * @param string $message texte du message
220
     * @param string $type type du message (info, success, warning ou danger)
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 _showMessage($message, $type = "success", $timerInterval = 0, $dismissable = true, $visible = true)
225
    {
226
        $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 224 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...
227
        $this->_showDisplayedMessage($message);
228
    }
229
230
231
    public function messageSuccess($message, $timerInterval = 0, $dismissable = true)
232
    {
233
        $this->_showMessage($message, "success", $timerInterval, $dismissable);
234
    }
235
236
    /**
237
     * Affiche un message Alert bootstrap de type warning
238
     * @param string $message texte du message
239
     * @param number $timerInterval durée en millisecondes d'affichage du message (0 pour que le message reste affiché)
240
     * @param string $dismissable si vrai, l'alert dispose d'une croix de fermeture
241
     */
242
    public function messageWarning($message, $timerInterval = 0, $dismissable = true)
243
    {
244
        $this->_showMessage($message, "warning", $timerInterval, $dismissable);
245
    }
246
247
    /**
248
     * Affiche un message Alert bootstrap de type danger
249
     * @param string $message texte du message
250
     * @param number $timerInterval durée en millisecondes d'affichage du message (0 pour que le message reste affiché)
251
     * @param string $dismissable si vrai, l'alert dispose d'une croix de fermeture
252
     */
253
    public function messageDanger($message, $timerInterval = 0, $dismissable = true)
254
    {
255
        $this->_showMessage($message, "danger", $timerInterval, $dismissable);
256
    }
257
258
    /**
259
     * Affiche un message Alert bootstrap de type info
260
     * @param string $message texte du message
261
     * @param number $timerInterval durée en millisecondes d'affichage du message (0 pour que le message reste affiché)
262
     * @param string $dismissable si vrai, l'alert dispose d'une croix de fermeture
263
     */
264
    public function messageInfo($message, $timerInterval = 0, $dismissable = true)
265
    {
266
        $this->_showMessage($message, "info", $timerInterval, $dismissable);
267
    }
268
269
270
    public function isAdmin($userId){
271
        $user = User::findFirst($userId);
272
        if($user->getTypeUser() == 0){
0 ignored issues
show
Coding Style introduced by
The if-else statement can be simplified to return $user->getTypeUser() == 0;.
Loading history...
273
            return true;
274
        }else{
275
            return false;
276
        }
277
    }
278
279
    public function isActual($user){
280
        if($this->session->has("user") || $user == $this->session->get("user")->getId()){
0 ignored issues
show
Coding Style introduced by
The if-else statement can be simplified to return $this->session->h...->get('user')->getId();.
Loading history...
281
            return true;
282
        }else{
283
            return false;
284
        }
285
    }
286
287
    public function isAdminAndActual($user){
288
        if($this->isAdmin($user) || $this->isActual($user)){
0 ignored issues
show
Coding Style introduced by
The if-else statement can be simplified to return $this->isAdmin($u...$this->isActual($user);.
Loading history...
289
            return true;
290
        }else{
291
            return false;
292
        }
293
    }
294
}
295