Completed
Branch Projets (f4ac88)
by Hugo
02:59
created

ControllerBase::getInstance()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 7

Duplication

Lines 0
Ratio 0 %
Metric Value
dl 0
loc 10
rs 9.4286
cc 2
eloc 7
nc 2
nop 1
1
<?php
2
3
use Phalcon\Mvc\Controller;
4
use Phalcon\Mvc\Url;
5
6
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...
7
{
8
9
    protected $model;
10
    protected $title;
11
    protected $controller;
12
    protected $messageTimerInterval = 3000;
13
14
    public function afterExecuteRoute($dispatcher)
15
    {
16
        $baseUrl = $this->baseUrl;
17
        $this->view->setVar("baseUrl", $baseUrl);
18
        $this->view->setVar("controller", $this->controller);
19
        $this->view->setVar("title", $this->title);
20
    }
21
22
    public function indexAction($message = NULL)
23
    {
24
        $msg = "";
25
        if (isset($message)) {
26
            if (is_string($message)) {
27
                $message = new DisplayedMessage($message);
28
            }
29
            $message->setTimerInterval($this->messageTimerInterval);
30
            $msg = $this->_showDisplayedMessage($message);
31
        }
32
        $this->view->setVar("msg", $msg);
33
        $objects = call_user_func($this->model . "::find");
34
        $this->view->setVar("objects", $objects);
35
        $this->view->pick("main/index");
36
    }
37
38
    public function frmAction($id = NULL)
39
    {
40
        echo "Pas encore implémenté...";
41
    }
42
43
    public function getInstance($id = NULL)
44
    {
45
        if (isset($id)) {
46
            $object = call_user_func($this->model . "::findfirst", $id);
47
        } else {
48
            $className = $this->model;
49
            $object = new $className();
50
        }
51
        return $object;
52
    }
53
54
    public function readAction($id = NULL)
55
    {
56
        if ($id != null) {
57
            $object = call_user_func($this->model . '::find', "id = $id");
58
            $this->view->setVar("object", $object);
59
            $this->view->pick("main/read");
60
        }
61
    }
62
63
    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...
64
    {
65
        $object->assign($_POST);
66
    }
67
68
    /////////////////////////////////////////
69
    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...
70
    {
71
        if ($this->request->isPost()) {
72
            $object = $this->getInstance(@$_POST["id"]);
73
            $this->setValuesToObject($object);
74
            if (@$_POST["id"]) {
75
                try {
76
                    $object->save();
77
                    $msg = new DisplayedMessage("Instance de " . $this->model . " modifiée");
78
                } catch (\Exception $e) {
79
                    $msg = new DisplayedMessage("Impossible d'ajouter l'instance de " . $this->model, "danger : $e");
80
                }
81
            } else {
82
                try {
83
                    $object->save();
84
                    $msg = new DisplayedMessage("Instance de " . $this->model . " ajoutée");
85
                } catch (\Exception $e) {
86
                    $msg = new DisplayedMessage("Impossible d'ajouter l'instance de " . $this->model, "danger : $e");
87
                }
88
            }
89
            $this->dispatcher->forward(array("controller" => $this->dispatcher->getControllerName(), "action" => "index", "params" => array($msg)));
90
        }
91
    }
92
93
    /////////////////////////////////////
94
95
    public function deleteAction($id = null)
96
    {
97
        $object = call_user_func($this->model . '::find', "id = $id");
98
        $object->delete();
99
        $this->response->redirect("Index/index");
100
    }
101
102
    public function asAdminAction()
103
    {
104
        $user = User::findFirst("id=3");
105
        $this->session->set("user", $user);
106
        $this->response->redirect("Index/index");
107
    }
108
109
    public function asUserAction()
110
    {
111
        $user = User::findFirst("id=1");
112
        $this->session->set("user", $user);
113
        $this->response->redirect("Index/index");
114
    }
115
116
    public function logoutAction()
117
    {
118
        $this->session->destroy();
119
        $this->response->redirect("Index/index");
120
    }
121
122
123
    /**
124
     * Affiche un message Alert bootstrap
125
     * @param DisplayedMessage $message
126
     */
127
    public function _showDisplayedMessage($message)
128
    {
129
        return $message->compile($this->jquery);
130
    }
131
132
    /**
133
     * Affiche un message Alert bootstrap
134
     * @param string $message texte du message
135
     * @param string $type type du message (info, success, warning ou danger)
136
     * @param number $timerInterval durée en millisecondes d'affichage du message (0 pour que le message reste affiché)
137
     * @param string $dismissable si vrai, l'alert dispose d'une croix de fermeture
138
     */
139
    public function _showMessage($message, $type = "success", $timerInterval = 0, $dismissable = true, $visible = true)
140
    {
141
        $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 139 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...
142
        $this->_showDisplayedMessage($message);
143
    }
144
145
146
    public function messageSuccess($message, $timerInterval = 0, $dismissable = true)
147
    {
148
        $this->_showMessage($message, "success", $timerInterval, $dismissable);
149
    }
150
151
    /**
152
     * Affiche un message Alert bootstrap de type warning
153
     * @param string $message texte du message
154
     * @param number $timerInterval durée en millisecondes d'affichage du message (0 pour que le message reste affiché)
155
     * @param string $dismissable si vrai, l'alert dispose d'une croix de fermeture
156
     */
157
    public function messageWarning($message, $timerInterval = 0, $dismissable = true)
158
    {
159
        $this->_showMessage($message, "warning", $timerInterval, $dismissable);
160
    }
161
162
    /**
163
     * Affiche un message Alert bootstrap de type danger
164
     * @param string $message texte du message
165
     * @param number $timerInterval durée en millisecondes d'affichage du message (0 pour que le message reste affiché)
166
     * @param string $dismissable si vrai, l'alert dispose d'une croix de fermeture
167
     */
168
    public function messageDanger($message, $timerInterval = 0, $dismissable = true)
169
    {
170
        $this->_showMessage($message, "danger", $timerInterval, $dismissable);
171
    }
172
173
    /**
174
     * Affiche un message Alert bootstrap de type info
175
     * @param string $message texte du message
176
     * @param number $timerInterval durée en millisecondes d'affichage du message (0 pour que le message reste affiché)
177
     * @param string $dismissable si vrai, l'alert dispose d'une croix de fermeture
178
     */
179
    public function messageInfo($message, $timerInterval = 0, $dismissable = true)
180
    {
181
        $this->_showMessage($message, "info", $timerInterval, $dismissable);
182
    }
183
184
185
}
186