Completed
Push — master ( 92ff07...b7a271 )
by Benjamin
02:43
created

ItemAdmin::checkUri()   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 26
rs 8.439
cc 6
eloc 15
nc 5
nop 1
1
<?php
2
3
namespace Alpixel\Bundle\MenuBundle\Controller\Admin\CRUD;
4
5
use Alpixel\Bundle\MenuBundle\Entity\Item;
6
use Alpixel\Bundle\MenuBundle\Utils\URLChecker;
7
use Doctrine\ORM\EntityRepository;
8
use Sonata\AdminBundle\Admin\Admin;
9
use Sonata\AdminBundle\Datagrid\ListMapper;
10
use Sonata\AdminBundle\Form\FormMapper;
11
use Sonata\AdminBundle\Route\RouteCollection;
12
use Symfony\Component\Form\FormError;
13
use Symfony\Component\HttpFoundation\Request;
14
15
class ItemAdmin extends Admin
16
{
17
    public $last_position = 0;
18
19
    protected $datagridValues = [
20
        '_page'       => 1,
21
        '_sort_order' => 'ASC',
22
        '_sort_by'    => 'position',
23
    ];
24
25
    public function setPositionService(\Pix\SortableBehaviorBundle\Services\PositionHandler $positionHandler)
26
    {
27
        $this->positionService = $positionHandler;
28
    }
29
30
    protected function configureRoutes(RouteCollection $collection)
31
    {
32
        $collection->add('move', $this->getRouterIdParameter().'/move/{position}');
33
        $collection->add('item', $this->getRouterIdParameter().'/item');
34
    }
35
36
    public function getPersistentParameters()
37
    {
38
        $parameters = [];
39
        if ($this->getRequest() instanceof Request) {
40
            $query = $this->getRequest()->query;
41
            if ($query->has('menu')) {
42
                $parameters['menu'] = $query->getInt('menu');
43
            }
44
45
            if ($query->has('item')) {
46
                $parameters['item'] = $query->getInt('item');
47
            }
48
        }
49
50
        return $parameters;
51
    }
52
53
    public function createQuery($context = 'list')
54
    {
55
        $query = parent::createQuery($context);
56
        if ($this->getRequest() instanceof Request) {
57
            $requestQuery = $this->getRequest()->query;
58
            if ($requestQuery->has('item')) {
59
                $parentId = $requestQuery->getInt('item');
60
                $query->join($query->getRootAlias().'.parent', 'p')
61
                    ->andWhere('p.id = :parentId')
62
                    ->setParameters([
63
                        'parentId' => $parentId,
64
                    ]);
65
            } elseif ($requestQuery->has('menu')) {
66
                $menuId = $requestQuery->getInt('menu');
67
                $query
68
                    ->join($query->getRootAlias().'.menu', 'm')
69
                    ->leftJoin($query->getRootAlias().'.parent', 'p')
70
                    ->where('m.id = :menuId')
71
                    ->andwhere('p.id IS NULL')
72
                    ->setParameters([
73
                        'menuId' => $menuId,
74
                    ]);
75
            }
76
        }
77
78
        return $query;
79
    }
80
81
    protected function configureFormFields(FormMapper $formMapper)
82
    {
83
        $subject = $this->getSubject();
84
        $isNew = ($this->id($subject) === null) ? true : false;
85
86
        if ($isNew === true) {
87
            $idMenu = $this->getRequest()->query->getInt('create-menu');
88
            $idItem = $this->getRequest()->query->getInt('create-item');
89
        } else {
90
            $idMenu = $subject->getMenu()->getId();
91
            $idItem = ($subject->getParent() !== null) ? $subject->getParent()->getId() : 0;
92
        }
93
94
        $formMapper
95
            ->add('menu', null, [
96
                'label'         => 'Menu',
97
                'required'      => true,
98
                'property'      => 'name',
99 View Code Duplication
                'query_builder' => function (EntityRepository $entityRepository) use ($idMenu) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
100
                    $query = $entityRepository->createQuerybuilder('m');
101
                    if ($idMenu === 0) {
102
                        return $query;
103
                    }
104
105
                    return $query
106
                        ->where('m.id = :id')
107
                        ->setParameter('id', $idMenu);
108
                },
109
            ]);
110
111
        if ($idItem === 0 && $idMenu === 0 || $isNew === false && $subject->getParent() !== null || $isNew === true && $idItem > 0) {
112
            $formMapper->add('parent', null, [
113
                'label'         => 'Item parent',
114
                'required'      => true,
115
                'property'      => 'name',
116 View Code Duplication
                'query_builder' => function (EntityRepository $entityRepository) use ($idItem) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
117
                    $query = $entityRepository->createQuerybuilder('i');
118
                    if ($idItem === 0) {
119
                        return $query;
120
                    }
121
122
                    return $query
123
                        ->where('i.id = :id')
124
                        ->setParameter('id', $idItem);
125
                },
126
            ]);
127
        }
128
129
        $formMapper
130
            ->add('name', null, [
131
                'label'    => 'Nom du menu à afficher',
132
                'required' => true,
133
            ])
134
            ->add('uri', 'text', [
135
                'label'    => 'URI',
136
                'required' => true,
137
            ]);
138
    }
139
140
    protected function configureListFields(ListMapper $listMapper)
141
    {
142
        $this->last_position = $this->positionService->getLastPosition($this->getRoot()->getClass());
143
144
        $listMapper
145
            ->add('name', null, [
146
                'label'    => 'Label',
147
                'required' => true,
148
            ])
149
            ->add('uri', null, [
150
                'label'    => 'URI',
151
                'required' => true,
152
            ])
153
            ->add('position', null, [
154
                'label'    => 'Position',
155
                'required' => true,
156
            ])
157
            ->add('_action', 'actions', [
158
                'actions' => [
159
                    'edit' => [],
160
                    'move' => [
161
                        'template' => 'PixSortableBehaviorBundle:Default:_sort.html.twig',
162
                    ],
163
                    'item' => [
164
                        'template' => 'AlpixelMenuBundle:CRUD:list__action_item.html.twig',
165
                    ],
166
                ],
167
            ]);
168
    }
169
170
    public function checkUri($object = null)
171
    {
172
        if($object === null) {
173
            return;
174
        }
175
176
        $form    = $this->getForm();
177
        $request = $this->getRequest();
178
        $uriType = $request->request->get('uri_type');
179
        if (empty($uriType) || !in_array($uriType, [Item::URI_TYPE_EXTERNAL, Item::URI_TYPE_INTERNAL])) {
180
            $form->get('uri')->addError(new FormError(
181
               'Le type d\'url est invalide !'
182
            ));
183
184
            return;
185
        }
186
187
        if ($uriType === Item::URI_TYPE_EXTERNAL) {
188
            $uri = $form->get('uri')->getData();
189
            if (preg_match('/^https?:\/\//', $uri) === 0) {
190
                $form->get('uri')->addError(new FormError(
191
                    'Votre lien dois débuter par "http://" ou "https://"'
192
                ));
193
            }
194
        }
195
    }
196
197
    public function preValidate($object = null)
198
    {
199
        $this->checkUri($object);
200
    }
201
202
    public function postUpdate($object = null)
203
    {
204
        if ($object !== null && $object->getUri() !== null) {
205
            $container = $this->getConfigurationPool()->getContainer();
206
            $checker = $container->get('alpixel_menu.utils.url_checker');
207
            $url = $object->getUri();
208
            if ($checker->check($url) === URLChecker::URL_PROBLEM) {
209
                $session = $container->get('session');
210
                $session->getFlashBag()->add('warning', 'Cependant une erreur semble être apparue quand nous avons tenté d\'analyser la page "'.$url.'". Vous devriez vérifier que le lien spécifié n\'affiche aucune erreur.');
211
            }
212
        }
213
    }
214
}
215