Completed
Push — master ( dc8f0b...4caef0 )
by Leny
89:37 queued 68:39
created

LinkExtension::victoireLink()   D

Complexity

Conditions 12
Paths 216

Size

Total Lines 48
Code Lines 27

Duplication

Lines 8
Ratio 16.67 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
c 3
b 0
f 0
dl 8
loc 48
rs 4.4061
cc 12
eloc 27
nc 216
nop 5

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Victoire\Bundle\WidgetBundle\Twig;
4
5
use Doctrine\ORM\EntityManager;
6
use Symfony\Bundle\FrameworkBundle\Routing\Router;
7
use Symfony\Component\HttpFoundation\RequestStack;
8
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
9
use Victoire\Bundle\BusinessEntityBundle\Helper\BusinessEntityHelper;
10
use Victoire\Bundle\BusinessPageBundle\Helper\BusinessPageHelper;
11
use Victoire\Bundle\PageBundle\Helper\PageHelper;
12
use Victoire\Bundle\ViewReferenceBundle\ViewReference\ViewReference;
13
14
/**
15
 * Twig extension for rendering a link.
16
 */
17
class LinkExtension extends \Twig_Extension
18
{
19
    protected $router;
20
    protected $analytics;
21
    protected $businessEntityHelper; // @victoire_business_page.business_entity_helper
22
    protected $BusinessPageHelper; // @victoire_business_page.business_page_helper
23
    protected $pageHelper;
24
    protected $em; // @doctrine.orm.entity_manager
25
26
    public function __construct(
27
        Router $router,
28
        RequestStack $requestStack,
29
        $analytics,
30
        BusinessEntityHelper $businessEntityHelper,
31
        BusinessPageHelper $BusinessPageHelper,
32
        PageHelper $pageHelper,
33
        EntityManager $em
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $em. This is generally not recommended as it might get closed and become unusable. Instead, it is recommended to inject the ManagerRegistry and retrieve the EntityManager via getManager() each time you need it.

The EntityManager might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:

function someFunction(ManagerRegistry $registry) {
    $em = $registry->getManager();
    $em->getConnection()->beginTransaction();
    try {
        // Do something.
        $em->getConnection()->commit();
    } catch (\Exception $ex) {
        $em->getConnection()->rollback();
        $em->close();

        throw $ex;
    }
}

If that code throws an exception and the EntityManager is closed. Any other code which depends on the same instance of the EntityManager during this request will fail.

On the other hand, if you instead inject the ManagerRegistry, the getManager() method guarantees that you will always get a usable manager instance.

Loading history...
34
    ) {
35
        $this->router = $router;
36
        $this->request = $requestStack->getCurrentRequest();
0 ignored issues
show
Bug introduced by
The property request does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
37
        $this->analytics = $analytics;
38
        $this->businessEntityHelper = $businessEntityHelper;
39
        $this->BusinessPageHelper = $BusinessPageHelper;
40
        $this->pageHelper = $pageHelper;
41
        $this->em = $em;
42
    }
43
44
    /**
45
     * Returns a list of functions to add to the existing list.
46
     *
47
     * @return \Twig_SimpleFunction[] An array of functions
48
     */
49
    public function getFunctions()
50
    {
51
        return [
52
            new \Twig_SimpleFunction('vic_link_url', [$this, 'victoireLinkUrl']),
53
            new \Twig_SimpleFunction('vic_link', [$this, 'victoireLink'], ['is_safe' => ['html']]),
54
            new \Twig_SimpleFunction('vic_menu_link', [$this, 'victoireMenuLink'], ['is_safe' => ['html']]),
55
            new \Twig_SimpleFunction('vic_business_link', [$this, 'victoireBusinessLink'], ['is_safe' => ['html']]),
56
        ];
57
    }
58
59
    /**
60
     * Generate the complete link (with the a tag).
61
     *
62
     * @param array  $parameters   The link parameters (go to LinkTrait to have the list)
63
     * @param string $avoidRefresh Do we have to refresh or not ?
64
     * @param array  $url          Fallback url
65
     *
66
     * @return string
67
     */
68
    public function victoireLinkUrl($parameters, $avoidRefresh = true, $url = '#')
69
    {
70
        $referenceType = isset($parameters['referenceType']) ? $parameters['referenceType'] : UrlGeneratorInterface::ABSOLUTE_PATH;
71
72
        $viewReference = isset($parameters['viewReference']) ? $parameters['viewReference'] : null;
73
        switch ($parameters['linkType']) {
74
            case 'viewReference':
75
                if ($viewReference instanceof ViewReference) {
76
                    $viewReference = $viewReference->getId();
77
                }
78
79
                if (isset($viewReferencePage) && $viewReferencePage) {
0 ignored issues
show
Bug introduced by
The variable $viewReferencePage does not exist. Did you mean $viewReference?

This check looks for variables that are accessed but have not been defined. It raises an issue if it finds another variable that has a similar name.

The variable may have been renamed without also renaming all references.

Loading history...
80
                    $page = $viewReferencePage;
81
                } else {
82
                    $page = $this->pageHelper->findPageByParameters(['id' => $viewReference]);
83
                }
84
85
                $linkUrl = $this->router->generate(
86
                    'victoire_core_page_show', [
87
                        '_locale' => $page->getLocale(),
88
                        'url'     => $page->getReference()->getUrl(),
89
                    ],
90
                    $referenceType
91
                );
92
                if ($this->request->getRequestUri() != $linkUrl || !$avoidRefresh) {
93
                    $url = $linkUrl;
94
                }
95
                break;
96
            case 'route':
97
                $url = $this->router->generate($parameters['route'], $parameters['routeParameters'], $referenceType);
98
                break;
99
            case 'attachedWidget':
100
                $attachedWidget = $parameters['attachedWidget'];
101
                //fallback when a widget is deleted cascading the relation as null (widget_id = null)
102
                if ($attachedWidget && method_exists($attachedWidget->getView(), 'getUrl')) {
103
104
                    //create base url
105
                    $url = $this->router->generate('victoire_core_page_show', ['_locale' => $attachedWidget->getView()->getLocale(), 'url' => $attachedWidget->getView()->getUrl()], $referenceType);
106
107
                    //If widget in the same view
108
                    if (rtrim($this->request->getRequestUri(), '/') == rtrim($url, '/')) {
109
                        $url = '';
110
                    }
111
                    //Add anchor part
112
                    $url .= '#vic-widget-'.$attachedWidget->getId().'-container-anchor';
113
                }
114
                break;
115
            default:
116
                $url = $parameters['url'];
117
        }
118
119
        return $url;
120
    }
121
122
    /**
123
     * Generate the complete link (with the a tag).
124
     *
125
     * @param array  $parameters The link parameters (go to LinkTrait to have the list)
126
     * @param string $label      link label
127
     * @param array  $attr       custom attributes
128
     *
129
     * @return string
130
     */
131
    public function victoireLink($parameters, $label, $attr = [], $currentClass = 'active', $url = '#')
132
    {
133
        $referenceLink = UrlGeneratorInterface::ABSOLUTE_PATH;
134
        $attachedWidget = isset($parameters['attachedWidget']) ? $parameters['attachedWidget'] : null;
135
136
        if ($parameters['linkType'] == 'attachedWidget' && $attachedWidget && method_exists($attachedWidget->getView(), 'getUrl')) {
137
            $viewUrl = $this->router->generate('victoire_core_page_show', ['_locale' => $attachedWidget->getView()->getLocale(), 'url' => $attachedWidget->getView()->getUrl()], $referenceLink);
138
            if (rtrim($this->request->getRequestUri(), '/') == rtrim($viewUrl, '/')) {
139
                $attr['data-scroll'] = 'smooth';
140
            }
141
        }
142
143
        //Avoid to refresh page if not needed
144
        if ($this->request->getRequestUri() == $this->victoireLinkUrl($parameters, false)) {
145
            $this->addAttr('class', $currentClass, $attr);
146
        }
147
148
        //Build the target attribute
149
        if ($parameters['target'] == 'ajax-modal') {
150
            $attr['data-toggle'] = 'ajax-modal';
151
        } elseif ($parameters['target'] == '') {
152
            $attr['target'] = '_parent';
153
        } else {
154
            $attr['target'] = $parameters['target'];
155
        }
156
157
        //Add the analytics tracking code attribute
158
        if (isset($parameters['analyticsTrackCode'])) {
159
            $this->addAttr('onclick', $parameters['analyticsTrackCode'], $attr);
160
        }
161
162
        //Assemble and prepare attributes
163
        $attributes = [];
164 View Code Duplication
        foreach ($attr as $key => $_attr) {
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...
165
            if (is_array($_attr)) {
166
                $attr = implode($_attr, ' ');
167
            } else {
168
                $attr = $_attr;
169
            }
170
            $attributes[] = $key.'="'.$attr.'"';
171
        }
172
173
        $url = $this->victoireLinkUrl($parameters, true, $url);
174
        //Creates a new twig environment
175
        $twig = new \Twig_Environment(new \Twig_Loader_Array(['linkTemplate' => '{{ link|raw }}']));
176
177
        return $twig->render('linkTemplate', ['link' => '<a href="'.$url.'" '.implode($attributes, ' ').'>'.$label.'</a>']);
178
    }
179
180
    /**
181
     * Generate the complete menu link item (with the li tag).
182
     *
183
     * @param array  $parameters The link parameters (go to LinkTrait to have the list)
184
     * @param string $label      link label
185
     * @param array  $attr       custom attributes
186
     *
187
     * @return string
188
     */
189
    public function victoireMenuLink($parameters, $label, $attr = [])
190
    {
191
        $linkAttr = [];
192
        //is the link is active
193
        if ($this->request->getRequestUri() == $this->victoireLinkUrl($parameters, false)) {
194
            if (!isset($attr['class'])) {
195
                $linkAttr['class'] = '';
196
            }
197
            $linkAttr['class'] .= 'active'; //avoid to refresh page when not needed
198
        }
199
200
        $linkAttributes = [];
201 View Code Duplication
        foreach ($linkAttr as $key => $_attr) {
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...
202
            if (is_array($_attr)) {
203
                $linkAttr = implode($_attr, ' ');
204
            } else {
205
                $linkAttr = $_attr;
206
            }
207
            $linkAttributes[] = $key.'="'.$linkAttr.'"';
208
        }
209
210
        return '<li '.implode($linkAttributes, ' ').'>'.$this->victoireLink($parameters, $label, $attr, false, '#top').'</li>';
0 ignored issues
show
Documentation introduced by
false is of type boolean, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
211
    }
212
213
    public function victoireBusinessLink($businessEntityInstance, $templateId = null, $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH)
214
    {
215
        if (!$templateId) {
216
            $templateId = $this->BusinessPageHelper
217
                ->guessBestPatternIdForEntity(new \ReflectionClass($businessEntityInstance), $businessEntityInstance->getId(), $this->em);
218
        }
219
220
        $page = $this->pageHelper->findPageByParameters([
221
            'templateId' => $templateId,
222
            'entityId'   => $businessEntityInstance->getId(),
223
        ]);
224
225
        $parameters = [
226
            'linkType'        => 'route',
227
            'route'           => 'victoire_core_page_show',
228
            'routeParameters' => [
229
                'url' => $page->getReference()->getUrl(),
230
            ],
231
            'referenceType' => $referenceType,
232
        ];
233
234
        return $this->victoireLinkUrl($parameters);
235
    }
236
237
    /**
238
     * Add a given attribute to given attributes.
239
     *
240
     * @param string $label
241
     * @param string $value
242
     * @param array  $attr  The current attributes array
243
     *
244
     * @return LinkExtension
245
     **/
246
    protected function addAttr($label, $value, &$attr)
247
    {
248
        if (!isset($attr[$label])) {
249
            $attr[$label] = '';
250
        } else {
251
            $attr[$label] .= ' ';
252
        }
253
        $attr[$label] .= $value;
254
255
        return $this;
256
    }
257
258
    /**
259
     * Returns the name of the extension.
260
     *
261
     * @return string The extension name
262
     */
263
    public function getName()
264
    {
265
        return 'victoire_link_extension';
266
    }
267
}
268