Completed
Push — master ( cfc87e...ecfb42 )
by Laurent
03:10
created

AbstractController::getOrder()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 6
rs 9.4285
cc 2
eloc 3
nc 2
nop 1
1
<?php
2
/**
3
 * AbstractController controller des méthodes communes.
4
 *
5
 * PHP Version 5
6
 *
7
 * @author    Quétier Laurent <[email protected]>
8
 * @copyright 2014 Dev-Int GLSR
9
 * @license   http://opensource.org/licenses/gpl-license.php GNU Public License
10
 *
11
 * @version since 1.0.0
12
 *
13
 * @link      https://github.com/Dev-Int/glsr
14
 */
15
namespace AppBundle\Controller;
16
17
use Symfony\Component\HttpFoundation\Request;
18
use Symfony\Component\HttpFoundation\Session\Session;
19
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
20
use Doctrine\ORM\QueryBuilder;
21
22
/**
23
 * Abstract controller.
24
 *
25
 * @category Controller
26
 */
27
abstract class AbstractController extends Controller
28
{
29
    /**
30
     * Lists all items entity.
31
     *
32
     * @param string $entityName Name of Entity
33
     * @param \Symfony\Component\HttpFoundation\Request $request Sort request
34
     * @return array
35
     */
36
    public function abstractIndexAction($entityName, Request $request = null)
37
    {
38
        $etm = $this->getDoctrine()->getManager();
39
        $paginator = '';
40
        $entities = $this->getEntity($entityName, $etm);
41
        
42
        if ($request !== null) {
43
            $item = $this->container->getParameter('knp_paginator.page_range');
44
            $this->addQueryBuilderSort($entities, strtolower($entityName));
45
            $paginator = $this->get('knp_paginator')->paginate($entities, $request->query->get('page', 1), $item);
46
        }
47
48
        return array('entities'  => $entities, 'ctEntity' => count($entities), 'paginator' => $paginator,);
49
    }
50
51
    /**
52
     * Get the entity
53
     *
54
     * @param string $entityName Name of Entity
55
     * @param \Doctrine\Common\Persistence\ObjectManager $etm ObjectManager instances
56
     * @return type
57
     */
58
    protected function getEntity($entityName, $etm)
59
    {
60
        switch ($entityName) {
61
            case 'Article':
62
                $entities = $etm->getRepository('AppBundle:'.$entityName)->getArticles();
63
                break;
64
            case 'Supplier':
65
                $entities = $etm->getRepository('AppBundle:'.$entityName)->getSuppliers();
66
                break;
67
            case 'User':
68
                $entities = $etm->getRepository('AppBundle:'.$entityName)->getUsers();
69
                break;
70
            case 'FamilyLog':
71
                $entities = $etm->getRepository('AppBundle:'.$entityName)->childrenHierarchy();
72
                break;
73
            case 'UnitStorage':
74
                $entities = $etm->getRepository('AppBundle:'.$entityName)->createQueryBuilder('u');
75
                break;
76
            default:
77
                $entities = $etm->getRepository('AppBundle:'.$entityName)->findAll();
78
        }
79
        return $entities;
80
    }
81
82
    /**
83
     * Finds and displays an item entity.
84
     *
85
     * @param Object $entity     Entity
86
     * @param string $entityName Name of Entity
87
     * @return array
88
     */
89
    public function abstractShowAction($entity, $entityName)
90
    {
91
        $deleteForm = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
92
93
        return array(
94
            $entityName => $entity,
95
            'delete_form' => $deleteForm->createView(),
96
        );
97
    }
98
99
    /**
100
     * Displays a form to create a new item entity.
101
     *
102
     * @param string $entity     Entity
103
     * @param string $entityPath Path of Entity
104
     * @param string $typePath   Path of FormType
105
     * @return array
106
     */
107
    public function abstractNewAction($entity, $entityPath, $typePath)
108
    {
109
        $etm = $this->getDoctrine()->getManager();
110
        $ctEntity = count($etm->getRepository('AppBundle:'.$entity)->findAll());
111
        
112
        if ($entity === 'Company' || $entity === 'Settings' && $ctEntity >= 1) {
113
            $return = $this->redirectToRoute('_home');
114
            $this->addFlash('danger', 'gestock.settings.'.strtolower($entity).'.add2');
115
        }
116
117
        $entityNew = $etm->getClassMetadata($entityPath)->newInstance();
118
        $form = $this->createForm($typePath, $entityNew, array(
119
            'action' => $this->generateUrl(strtolower($entity).'_create'),
120
        ));
121
122
        $return = array(strtolower($entity) => $entityNew, 'form'   => $form->createView(),);
123
124
        return $return;
125
    }
126
127
    /**
128
     * Creates a new item entity.
129
     *
130
     * @param Request $request   Request in progress
131
     * @param string $entity     Entity <i>First letter Upper</i>
132
     * @param string $entityPath Path of Entity
133
     * @param string $typePath   Path of FormType
134
     * @return array
135
     */
136
    public function abstractCreateAction(Request $request, $entity, $entityPath, $typePath)
137
    {
138
        $param = array();
139
        $etm = $this->getDoctrine()->getManager();
140
        $entityNew = $etm->getClassMetadata($entityPath)->newInstance();
141
        $form = $this->createForm($typePath, $entityNew, array(
142
            'action' => $this->generateUrl(strtolower($entity).'_create'),
143
        ));
144
        $return = [$entity => $entityNew, 'form' => $form->createView(),];
145
146
        if ($form->handleRequest($request)->isValid()) {
147
            $etm = $this->getDoctrine()->getManager();
148
            $etm->persist($entityNew);
149
            $etm->flush();
150
            $this->addFlash('info', 'gestock.create.ok');
151
152
            $param = $this->testReturnParam($entityNew, strtolower($entity));
153
            $route = $form->get('addmore')->isClicked() ? strtolower($entity).'_new' : strtolower($entity).'_show';
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Form\FormInterface as the method isClicked() does only exist in the following implementations of said interface: Symfony\Component\Form\SubmitButton.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
154
155
            $return = $this->redirectToRoute($route, $param);
156
        }
157
158
        return $return;
159
    }
160
161
    /**
162
     * Displays a form to edit an existing item entity.
163
     *
164
     * @param Object $entity     Entity
165
     * @param string $entityName Name of Entity
166
     * @param string $typePath   Path of FormType
167
     * @return array
168
     */
169
    public function abstractEditAction($entity, $entityName, $typePath)
170
    {
171
        $param = $this->testReturnParam($entity, $entityName);
172
        $editForm = $this->createForm($typePath, $entity, array(
173
            'action' => $this->generateUrl($entityName.'_update', $param),
174
            'method' => 'PUT',
175
        ));
176
        $deleteForm = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
177
178
        return array(
179
            $entityName => $entity,
180
            'edit_form'   => $editForm->createView(),
181
            'delete_form' => $deleteForm->createView(),
182
        );
183
    }
184
185
    /**
186
     * Edits an existing item entity.
187
     *
188
     * @param Object $entity     Entity
189
     * @param Request $request   Request in progress
190
     * @param string $entityName Name of Entity
191
     * @param string $typePath   Path of FormType
192
     * @return array
193
     */
194
    public function abstractUpdateAction($entity, Request $request, $entityName, $typePath)
195
    {
196
        $param = $this->testReturnParam($entity, $entityName);
197
        $editForm = $this->createForm($typePath, $entity, array(
198
            'action' => $this->generateUrl($entityName.'_update', $param),
199
            'method' => 'PUT',
200
        ));
201
        if ($editForm->handleRequest($request)->isValid()) {
202
            $this->getDoctrine()->getManager()->flush();
203
            $this->addFlash('info', 'gestock.edit.ok');
204
205
            return $this->redirectToRoute($entityName.'_edit', $param);
206
        }
207
        $deleteForm = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
208
209
        return array(
210
            $entityName => $entity,
211
            'edit_form'   => $editForm->createView(),
212
            'delete_form' => $deleteForm->createView(),
213
        );
214
    }
215
216
    /**
217
     * Deletes an item entity.
218
     *
219
     * @param Object $entity     Entity
220
     * @param Request $request   Request in progress
221
     * @param string $entityName Name of Entity
222
     * @return array
223
     */
224
    public function abstractDeleteAction($entity, Request $request, $entityName)
225
    {
226
        $form = $this->createDeleteForm($entity->getId(), $entityName.'_delete');
227
        if ($form->handleRequest($request)->isValid()) {
228
            $etm = $this->getDoctrine()->getManager();
229
            $etm->remove($entity);
230
            $etm->flush();
231
        }
232
    }
233
234
    private function testReturnParam($entity, $entityName)
235
    {
236
        if ($entityName === 'company' || $entityName === 'settings' || $entityName === 'tva') {
237
            $param = array('id' => $entity->getId());
238
        } else {
239
            $param = array('slug' => $entity->getSlug());
240
        }
241
242
        return $param;
243
    }
244
    /**
245
     * SetOrder for the SortAction in views.
246
     *
247
     * @param string $name   session name
248
     * @param string $entity entity name
249
     * @param string $field  field name
250
     * @param string $type   sort type ("ASC"/"DESC")
251
     */
252
    protected function setOrder($name, $entity, $field, $type = 'ASC')
253
    {
254
        $session = new Session();
255
256
        $session->set('sort.'.$name, array('entity' => $entity, 'field' => $field, 'type' => $type));
257
    }
258
259
    /**
260
     * GetOrder for the SortAction in views.
261
     *
262
     * @param string $name session name
263
     *
264
     * @return array
265
     */
266
    protected function getOrder($name)
267
    {
268
        $session = new Session();
269
270
        return $session->has('sort.' . $name) ? $session->get('sort.' . $name) : null;
271
    }
272
273
    /**
274
     * AddQueryBuilderSort for the SortAction in views.
275
     *
276
     * @param QueryBuilder $qbd
277
     * @param string       $name
278
     */
279
    protected function addQueryBuilderSort(QueryBuilder $qbd, $name)
280
    {
281
        $alias = '';
282
        if (is_array($order = $this->getOrder($name))) {
283
            if ($name !== $order['entity']) {
284
                $rootAlias = current($qbd->getDQLPart('from'))->getAlias();
285
                $join = current($qbd->getDQLPart('join'));
286
                foreach ($join as $item) {
287
                    if ($item->getJoin() === $rootAlias.'.'.$order['entity']) {
288
                        $alias = $item->getAlias();
289
                    }
290
                }
291
            } else {
292
                $alias = current($qbd->getDQLPart('from'))->getAlias();
293
            }
294
            $qbd->orderBy($alias . '.' . $order['field'], $order['type']);
295
        }
296
    }
297
298
    /**
299
     * Create Delete form.
300
     *
301
     * @param int    $id
302
     * @param string $route
303
     *
304
     * @return \Symfony\Component\Form\Form
305
     */
306
    protected function createDeleteForm($id, $route)
307
    {
308
        return $this->createFormBuilder(null, array('attr' => array('id' => 'delete')))
309
            ->setAction($this->generateUrl($route, array('id' => $id)))
310
            ->setMethod('DELETE')
311
            ->getForm()
312
        ;
313
    }
314
315
    /**
316
     * Array of file (`pdf`) layout.
317
     *
318
     * @param string $date File date
319
     * @param string $title File title
320
     * @return array<string,integer|string|boolean>
321
     */
322
    protected function getArray($date, $title)
323
    {
324
        $array = array(
325
            'margin-top' => 15,
326
            'header-spacing' => 5,
327
            'header-font-size' => 8,
328
            'header-left' => 'G.L.S.R.',
329
            'header-center' => $title,
330
            'header-right' => $date,
331
            'header-line' => true,
332
            'margin-bottom' => 15,
333
            'footer-spacing' => 5,
334
            'footer-font-size' => 8,
335
            'footer-left' => 'GLSR &copy 2014 and beyond.',
336
            'footer-right' => 'Page [page]/[toPage]',
337
            'footer-line' => true,
338
        );
339
        return $array;
340
    }
341
}
342