Completed
Push — dev ( ceb2ac...663271 )
by Arnaud
82:57 queued 27:42
created

AdminExtension::functionExists()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

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