Completed
Branch master (01610a)
by Arnaud
06:29
created

AdminExtension   B

Complexity

Total Complexity 24

Size/Duplication

Total Lines 220
Duplicated Lines 1.82 %

Coupling/Cohesion

Components 2
Dependencies 16

Test Coverage

Coverage 0%

Importance

Changes 6
Bugs 2 Features 1
Metric Value
wmc 24
c 6
b 2
f 1
lcom 2
cbo 16
dl 4
loc 220
ccs 0
cts 108
cp 0
rs 8.4614

11 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 9 1
A getOrderQueryString() 0 14 3
A field() 4 18 3
A fieldTitle() 0 12 2
A routeParameters() 0 14 4
A camelize() 0 4 1
A getFunctions() 0 10 1
A getFilters() 0 6 1
A getSortColumnUrl() 0 19 3
A getSortColumnIconClass() 0 15 4
A getName() 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
namespace LAG\AdminBundle\Twig;
4
5
use LAG\AdminBundle\Admin\Behaviors\TranslationKeyTrait;
6
use LAG\AdminBundle\Application\Configuration\ApplicationConfiguration;
7
use LAG\AdminBundle\Configuration\Factory\ConfigurationFactory;
8
use LAG\AdminBundle\Field\Field;
9
use LAG\AdminBundle\Field\EntityFieldInterface;
10
use LAG\AdminBundle\Field\FieldInterface;
11
use Symfony\Component\DependencyInjection\Container;
12
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
13
use Symfony\Component\PropertyAccess\PropertyAccess;
14
use Symfony\Component\Translation\TranslatorInterface;
15
use Twig_Extension;
16
use Twig_SimpleFilter;
17
use Twig_SimpleFunction;
18
use Symfony\Component\Routing\RouterInterface;
19
use Symfony\Component\HttpFoundation\Request;
20
21
/**
22
 * Class AdminExtension.
23
 *
24
 * Admin utils functions for twig
25
 */
26
class AdminExtension extends Twig_Extension
27
{
28
    use TranslationKeyTrait;
29
30
    /**
31
     * @var ApplicationConfiguration
32
     */
33
    protected $configuration;
34
35
    /**
36
     * @var RouterInterface
37
     */
38
    protected $router;
39
40
    /**
41
     * @var TranslatorInterface
42
     */
43
    protected $translator;
44
45
    /**
46
     * AdminExtension constructor.
47
     *
48
     * @param RouterInterface $router
49
     * @param TranslatorInterface $translator
50
     * @param ConfigurationFactory $configurationFactory
51
     */
52
    public function __construct(
53
        RouterInterface $router,
54
        TranslatorInterface $translator,
55
        ConfigurationFactory $configurationFactory
56
    ) {
57
        $this->router = $router;
58
        $this->translator = $translator;
59
        $this->configuration = $configurationFactory->getApplicationConfiguration();
60
    }
61
62
    /**
63
     * @return array
64
     */
65
    public function getFunctions()
66
    {
67
        return [
68
            new Twig_SimpleFunction('getSortColumnUrl', [$this, 'getSortColumnUrl']),
69
            new Twig_SimpleFunction('getSortColumnIconClass', [$this, 'getSortColumnIconClass']),
70
            new Twig_SimpleFunction('field', [$this, 'field']),
71
            new Twig_SimpleFunction('field_title', [$this, 'fieldTitle']),
72
            new Twig_SimpleFunction('route_parameters', [$this, 'routeParameters']),
73
        ];
74
    }
75
76
    /**
77
     * @return array
78
     */
79
    public function getFilters()
80
    {
81
        return [
82
            new Twig_SimpleFilter('camelize', [$this, 'camelize']),
83
        ];
84
    }
85
86
    /**
87
     * Return sort column url, with existing request parameters, according to field name.
88
     *
89
     * @param Request $request
90
     * @param $fieldName
91
     *
92
     * @return string
93
     */
94
    public function getSortColumnUrl(Request $request, $fieldName)
95
    {
96
        // get query string to not delete existing parameters
97
        $queryString = $request->query->all();
98
        $queryString['sort'] = $fieldName;
99
100
        if (array_key_exists('order', $queryString)) {
101
            // sort by opposite sorting than current
102
            $sort = $queryString['order'] == 'ASC' ? 'DESC' : 'ASC';
103
            $queryString['order'] = $sort;
104
        } else {
105
            // if no order was provided, it means that list is sorted by default order (ASC), so we must sort by DESC
106
            $queryString['order'] = 'DESC';
107
        }
108
109
        return $this
110
            ->router
111
            ->generate($request->get('_route'), $queryString);
112
    }
113
114
    /**
115
     * Return an array of query string parameters, updated with sort field name.
116
     *
117
     * @param ParameterBagInterface $parameters
118
     * @param $fieldName
119
     * @return array
120
     */
121
    public function getOrderQueryString(ParameterBagInterface $parameters, $fieldName)
122
    {
123
        $parameters->set('sort', $fieldName);
124
125
        if ($parameters->has('order')) {
126
            // sort by opposite order
127
            $order = $parameters->get('order') == 'ASC' ? 'DESC' : 'ASC';
128
            $parameters->set('order', $order);
129
        } else {
130
            // if no order was provided, it means that list is sorted by default order (ASC), so we must sort by DESC
131
            $parameters->set('order', 'DESC');
132
        }
133
        return $parameters->all();
134
    }
135
136
    /**
137
     * @param null $order
138
     * @param $fieldName
139
     * @param $sort
140
     * @return string
141
     */
142
    public function getSortColumnIconClass($order = null, $fieldName, $sort)
143
    {
144
        // when no order is provided, no icon should be displayed
145
        $class = '';
146
147
        if ($fieldName == $sort) {
148
            if ($order == 'ASC') {
149
                $class = 'fa fa-sort-asc';
150
            } elseif ($order == 'DESC') {
151
                $class = 'fa fa-sort-desc';
152
            }
153
        }
154
155
        return $class;
156
    }
157
158
    /**
159
     * Render a field of an entity.
160
     *
161
     * @param FieldInterface $field
162
     * @param $entity
163
     *
164
     * @return mixed
165
     */
166
    public function field(FieldInterface $field, $entity)
167
    {
168
        $accessor = PropertyAccess::createPropertyAccessorBuilder()
169
            ->enableMagicCall()
170
            ->getPropertyAccessor();
171
        $value = null;
172
        // if name starts with a underscore, it is a custom field, not mapped to the entity
173 View Code Duplication
        if (substr($field->getName(), 0, 1) != '_') {
174
            // get raw value from object
175
            $value = $accessor->getValue($entity, $field->getName());
176
        }
177
        if ($field instanceof EntityFieldInterface) {
178
            $field->setEntity($entity);
179
        }
180
        $render = $field->render($value);
181
182
        return $render;
183
    }
184
185
    /**
186
     * Return a the title of the field, camelized or translated.
187
     *
188
     * @param $fieldName
189
     * @param null $adminName
190
     * @return string
191
     */
192
    public function fieldTitle($fieldName, $adminName = null)
193
    {
194
        if ($this->configuration->getParameter('translation')['enabled']) {
195
            $title = $this
196
                ->translator
197
                ->trans($this->getTranslationKey($this->configuration->getParameter('translation')['pattern'], $fieldName, $adminName));
198
        } else {
199
            $title = $this->camelize($fieldName);
200
        }
201
202
        return $title;
203
    }
204
205
    /**
206
     * @param array $parameters
207
     * @param $entity
208
     * @return array
209
     */
210
    public function routeParameters(array $parameters, $entity)
211
    {
212
        $accessor = PropertyAccess::createPropertyAccessor();
213
        $routeParameters = [];
214
215
        foreach ($parameters as $parameterName => $fieldName) {
216
            if (is_array($fieldName) && !count($fieldName)) {
217
                $fieldName = $parameterName;
218
            }
219
            $routeParameters[$parameterName] = $accessor->getValue($entity, $fieldName);
220
        }
221
222
        return $routeParameters;
223
    }
224
225
    /**
226
     * Camelize a string (using Container camelize method)
227
     *
228
     * @param $string
229
     * @return string
230
     */
231
    public function camelize($string)
232
    {
233
        return Container::camelize($string);
234
    }
235
236
    /**
237
     * Returns the name of the extension.
238
     *
239
     * @return string The extension name
240
     */
241
    public function getName()
242
    {
243
        return 'lag.admin';
244
    }
245
}
246