Completed
Push — master ( 9745cb...81e988 )
by Paul
06:43
created

legacyGenerateEntityPageFromTemplate()   C

Complexity

Conditions 9
Paths 16

Size

Total Lines 52
Code Lines 36

Duplication

Lines 14
Ratio 26.92 %

Importance

Changes 2
Bugs 2 Features 0
Metric Value
c 2
b 2
f 0
dl 14
loc 52
rs 6.5703
cc 9
eloc 36
nc 16
nop 3

How to fix   Long Method   

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\BusinessPageBundle\Builder;
4
5
use Doctrine\ORM\EntityManager;
6
use Symfony\Component\PropertyAccess\PropertyAccess;
7
use Victoire\Bundle\BusinessEntityBundle\Converter\ParameterConverter;
8
use Victoire\Bundle\BusinessEntityBundle\Entity\BusinessEntity;
9
use Victoire\Bundle\BusinessEntityBundle\Entity\BusinessProperty;
10
use Victoire\Bundle\BusinessEntityBundle\Helper\BusinessEntityHelper;
11
use Victoire\Bundle\BusinessEntityBundle\Provider\EntityProxyProvider;
12
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessPage;
13
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessTemplate;
14
use Victoire\Bundle\BusinessPageBundle\Entity\VirtualBusinessPage;
15
use Victoire\Bundle\CoreBundle\Exception\IdentifierNotDefinedException;
16
use Victoire\Bundle\CoreBundle\Helper\UrlBuilder;
17
use Victoire\Bundle\I18nBundle\Entity\ViewTranslation;
18
use Victoire\Bundle\ViewReferenceBundle\Builder\ViewReferenceBuilder;
19
20
/**
21
 * @property mixed entityProxyProvider
22
 */
23
class BusinessPageBuilder
24
{
25
    protected $businessEntityHelper;
26
    protected $urlBuilder;
27
    protected $parameterConverter;
28
    protected $entityProxyProvider;
29
    protected $viewReferenceBuilder;
30
31
    //@todo Make it dynamic please
32
    protected $pageParameters = [
33
        'name',
34
        'bodyId',
35
        'bodyClass',
36
        'slug',
37
        'locale',
38
    ];
39
40
    /**
41
     * @param BusinessEntityHelper $businessEntityHelper
42
     * @param UrlBuilder           $urlBuilder
43
     * @param ParameterConverter   $parameterConverter
44
     * @param EntityProxyProvider  $entityProxyProvider
45
     */
46 View Code Duplication
    public function __construct(BusinessEntityHelper $businessEntityHelper,
0 ignored issues
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...
47
                                UrlBuilder $urlBuilder,
48
                                ParameterConverter $parameterConverter,
49
                                EntityProxyProvider $entityProxyProvider,
50
                                ViewReferenceBuilder $viewReferenceBuilder
51
    ) {
52
        $this->businessEntityHelper = $businessEntityHelper;
53
        $this->urlBuilder = $urlBuilder;
54
        $this->parameterConverter = $parameterConverter;
55
        $this->entityProxyProvider = $entityProxyProvider;
56
        $this->viewReferenceBuilder = $viewReferenceBuilder;
57
    }
58
59
    /**
60
     * Generate update the page parameters with the entity.
61
     *
62
     * @param BusinessTemplate $businessTemplate
63
     * @param entity           $entity
64
     *
65
     * @return VirtualBusinessPage
66
     */
67
    public function generateEntityPageFromTemplate(BusinessTemplate $businessTemplate, $entity, EntityManager $em)
68
    {
69
        $viewTranslations = $em->getRepository(ViewTranslation::class)->getTranslationForView($businessTemplate);
70
        $translations = [];
71
        if (count($viewTranslations == 0)) {
72
            return $this->legacyGenerateEntityPageFromTemplate($businessTemplate, $entity, $em);
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->legacyGenerateEnt...emplate, $entity, $em); of type object|array adds the type array to the return on line 72 which is incompatible with the return type documented by Victoire\Bundle\Business...eEntityPageFromTemplate of type Victoire\Bundle\Business...ity\VirtualBusinessPage.
Loading history...
73
        }
74
        $page = new VirtualBusinessPage();
75
76
        $pageLocale = $businessTemplate->getLocale();
77
        foreach (array_reverse($viewTranslations) as $viewTranslation) {
78
            $page = new VirtualBusinessPage();
79
            $em->refresh($viewTranslation->getObject()->setTranslatableLocale($viewTranslation->getLocale()));
80
            $reflect = new \ReflectionClass($businessTemplate);
81
            $templateProperties = $reflect->getProperties();
82
            $accessor = PropertyAccess::createPropertyAccessor();
83 View Code Duplication
            foreach ($templateProperties as $property) {
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...
84
                if (!in_array(
85
                        $property->getName(),
86
                        ['id', 'widgetMap', 'slots', 'seo', 'i18n', 'widgets']
87
                    ) && !$property->isStatic()
88
                ) {
89
                    $value = $accessor->getValue($viewTranslation->getObject(), $property->getName());
90
                    $setMethod = 'set'.ucfirst($property->getName());
91
                    if (method_exists($page, $setMethod)) {
92
                        $accessor->setValue($page, $property->getName(), $value);
93
                    }
94
                }
95
            }
96
            $translations[$viewTranslation->getLocale()]['page'] = $page;
97
        }
98
99
        //find Victoire\Bundle\BusinessEntityBundle\Entity\BusinessEntity object according to the given $entity
100
        $businessEntity = $this->businessEntityHelper->findByEntityInstance($entity);
101
102
        if ($businessEntity !== null) {
103
            //the business properties usable in a url
104
            $businessProperties = $this->getBusinessProperties($businessEntity);
105
106
            $entityProxy = $this->entityProxyProvider->getEntityProxy($entity, $businessEntity, $em);
107
108
            $references = [];
109
            foreach ($translations as $locale => $translation) {
110
                /** @var VirtualBusinessPage $page */
111
                $page = $translation['page'];
112
                //the url of the page
113
                $pageUrl = $this->urlBuilder->buildUrl($page);
114
115
                $pageName = $page->getName();
116
                $pageSlug = $page->getSlug();
117
                //parse the business properties
118 View Code Duplication
                foreach ($businessProperties as $businessProperty) {
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...
119
                    $pageUrl = $this->parameterConverter->setBusinessPropertyInstance(
120
                        $pageUrl,
121
                        $businessProperty,
122
                        $entity
123
                    );
124
                    $pageSlug = $this->parameterConverter->setBusinessPropertyInstance(
125
                        $pageSlug,
126
                        $businessProperty,
127
                        $entity
128
                    );
129
                    $pageName = $this->parameterConverter->setBusinessPropertyInstance(
130
                        $pageName,
131
                        $businessProperty,
132
                        $entity
133
                    );
134
                }
135
                //we update the url of the page
136
                $page->setTranslatableLocale($locale);
137
                $page->setUrl($pageUrl);
138
                $page->setSlug($pageSlug);
139
                $page->setName($pageName);
140
                $page->setEntityProxy($entityProxy);
141
                $page->setTemplate($businessTemplate);
142
143
                //Check that all twig variables in pattern url was removed for it's generated BusinessPage
144
                preg_match_all('/\{\%\s*([^\%\}]*)\s*\%\}|\{\{\s*([^\}\}]*)\s*\}\}/i', $pageUrl, $matches);
145
146
                if (count($matches[2])) {
147
                    throw new IdentifierNotDefinedException($matches[2]);
148
                }
149
                $translation['page'] = $page;
150
                $references[$locale] = $this->viewReferenceBuilder->buildViewReference($page, $em);
151
                $translations[$locale] = $translation;
152
            }
153
            $firstTranslation = $translations[$pageLocale];
154
            $page = $firstTranslation['page'];
155
            $page->setReferences($references);
156
157
            if ($seo = $businessTemplate->getSeo()) {
158
                $pageSeo = clone $seo;
159
                $page->setSeo($pageSeo);
160
            }
161
        }
162
163
        return $page;
164
    }
165
166
    /**
167
     * Get the list of business properties usable for the url.
168
     *
169
     * @param BusinessEntity $businessEntity
170
     *
171
     * @return BusinessProperty[] The list of business properties
172
     */
173 View Code Duplication
    public function getBusinessProperties(BusinessEntity $businessEntity)
0 ignored issues
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...
174
    {
175
        //the business properties usable in a url
176
        $businessProperties = $businessEntity->getBusinessPropertiesByType('businessParameter');
177
178
        //the business properties usable in a url
179
        $seoBusinessProps = $businessEntity->getBusinessPropertiesByType('seoable');
180
181
        //the business properties are the identifier and the seoables properties
182
        $businessProperties = array_merge($businessProperties, $seoBusinessProps);
183
184
        return $businessProperties;
185
    }
186
187
    /**
188
     * Generate update the page parameters with the entity.
189
     *
190
     * @param BusinessPage $page
191
     * @param Entity       $entity
192
     */
193
    public function updatePageParametersByEntity(BusinessPage $page, $entity)
194
    {
195
        //if no entity is provided
196
        if ($entity === null) {
197
            //we look for the entity of the page
198
            if ($page->getBusinessEntity() !== null) {
199
                $entity = $page->getBusinessEntity();
200
            }
201
        }
202
203
        //only if we have an entity instance
204
        if ($entity !== null) {
205
            $businessEntity = $this->businessEntityHelper->findByEntityInstance($entity);
206
207
            if ($businessEntity !== null) {
208
                $businessProperties = $this->getBusinessProperties($businessEntity);
209
210
                //parse the business properties
211
                foreach ($businessProperties as $businessProperty) {
212
                    //parse of seo attributes
213
                    foreach ($this->pageParameters as $pageAttribute) {
214
                        $string = $this->getEntityAttributeValue($page, $pageAttribute);
215
                        $updatedString = $this->parameterConverter->setBusinessPropertyInstance($string, $businessProperty, $entity);
216
                        $this->setEntityAttributeValue($page, $pageAttribute, $updatedString);
217
                    }
218
                }
219
            }
220
        }
221
    }
222
223
    /**
224
     * Get the content of an attribute of an entity given.
225
     *
226
     * @param BusinessPage $entity
227
     * @param string       $field
228
     *
229
     * @return mixed
230
     */
231 View Code Duplication
    protected function getEntityAttributeValue($entity, $field)
0 ignored issues
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...
232
    {
233
        $functionName = 'get'.ucfirst($field);
234
235
        $fieldValue = call_user_func([$entity, $functionName]);
236
237
        return $fieldValue;
238
    }
239
240
    /**
241
     * Update the value of the entity.
242
     *
243
     * @param BusinessPage $entity
244
     * @param string       $field
245
     * @param string       $value
246
     *
247
     * @return mixed
248
     */
249
    protected function setEntityAttributeValue($entity, $field, $value)
250
    {
251
        $functionName = 'set'.ucfirst($field);
252
253
        call_user_func([$entity, $functionName], $value);
254
    }
255
256
    private function legacyGenerateEntityPageFromTemplate(BusinessTemplate $businessTemplate, $entity, EntityManager $em)
257
    {
258
        $page = new VirtualBusinessPage();
259
        $reflect = new \ReflectionClass($businessTemplate);
260
        $templateProperties = $reflect->getProperties();
261
        $accessor = PropertyAccess::createPropertyAccessor();
262 View Code Duplication
        foreach ($templateProperties as $property) {
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...
263
            if (!in_array($property->getName(), ['id', 'widgetMap', 'slots', 'seo', 'i18n', 'widgets']) && !$property->isStatic()) {
264
                $value = $accessor->getValue($businessTemplate, $property->getName());
265
                $setMethod = 'set'.ucfirst($property->getName());
266
                if (method_exists($page, $setMethod)) {
267
                    $accessor->setValue($page, $property->getName(), $value);
268
                }
269
            }
270
        }
271
        //find Victoire\Bundle\BusinessEntityBundle\Entity\BusinessEntity object according to the given $entity
272
        $businessEntity = $this->businessEntityHelper->findByEntityInstance($entity);
273
        if ($businessEntity !== null) {
274
            //the business properties usable in a url
275
            $businessProperties = $this->getBusinessProperties($businessEntity);
276
            //the url of the page
277
            $pageUrl = $this->urlBuilder->buildUrl($page);
0 ignored issues
show
Documentation introduced by
$page is of type object|array, but the function expects a object<Victoire\Bundle\C...ntity\WebViewInterface>.

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...
278
            $pageName = $page->getName();
279
            $pageSlug = $page->getSlug();
280
            //parse the business properties
281 View Code Duplication
            foreach ($businessProperties as $businessProperty) {
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...
282
                $pageUrl = $this->parameterConverter->setBusinessPropertyInstance($pageUrl, $businessProperty, $entity);
283
                $pageSlug = $this->parameterConverter->setBusinessPropertyInstance($pageSlug, $businessProperty, $entity);
284
                $pageName = $this->parameterConverter->setBusinessPropertyInstance($pageName, $businessProperty, $entity);
285
            }
286
            //Check that all twig variables in pattern url was removed for it's generated BusinessPage
287
            preg_match_all('/\{\%\s*([^\%\}]*)\s*\%\}|\{\{\s*([^\}\}]*)\s*\}\}/i', $pageUrl, $matches);
288
            if (count($matches[2])) {
289
                throw new IdentifierNotDefinedException($matches[2]);
290
            }
291
            $entityProxy = $this->entityProxyProvider->getEntityProxy($entity, $businessEntity, $em);
292
            //we update the url of the page
293
            $page->setTranslatableLocale($businessTemplate->getLocale());
294
            $page->setUrl($pageUrl);
295
            $page->setSlug($pageSlug);
296
            $page->setName($pageName);
297
            $page->setEntityProxy($entityProxy);
298
            $page->setTemplate($businessTemplate);
299
            $page->setReferences([$page->getLocale() => $this->viewReferenceBuilder->buildViewReference($page, $em)]);
0 ignored issues
show
Documentation introduced by
$page is of type object|array, but the function expects a object<Victoire\Bundle\CoreBundle\Entity\View>.

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...
300
            if ($seo = $businessTemplate->getSeo()) {
301
                $pageSeo = clone $seo;
302
                $page->setSeo($pageSeo);
303
            }
304
        }
305
306
        return $page;
307
    }
308
}
309