Completed
Pull Request — master (#433)
by Paul
11:06 queued 04:27
created

generateEntityPageFromTemplate()   B

Complexity

Conditions 9
Paths 20

Size

Total Lines 55
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 9
Bugs 2 Features 1
Metric Value
c 9
b 2
f 1
dl 0
loc 55
rs 7.2446
cc 9
eloc 33
nc 20
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 Knp\DoctrineBehaviors\Model\Translatable\Translatable;
7
use Symfony\Component\PropertyAccess\PropertyAccess;
8
use Victoire\Bundle\BusinessEntityBundle\Converter\ParameterConverter;
9
use Victoire\Bundle\BusinessEntityBundle\Entity\BusinessEntity;
10
use Victoire\Bundle\BusinessEntityBundle\Entity\BusinessProperty;
11
use Victoire\Bundle\BusinessEntityBundle\Helper\BusinessEntityHelper;
12
use Victoire\Bundle\BusinessEntityBundle\Provider\EntityProxyProvider;
13
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessPage;
14
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessTemplate;
15
use Victoire\Bundle\BusinessPageBundle\Entity\VirtualBusinessPage;
16
use Victoire\Bundle\CoreBundle\Exception\IdentifierNotDefinedException;
17
use Victoire\Bundle\CoreBundle\Helper\UrlBuilder;
18
use Victoire\Bundle\I18nBundle\Entity\ViewTranslation;
19
use Victoire\Bundle\ViewReferenceBundle\Builder\ViewReferenceBuilder;
20
21
/**
22
 * @property mixed entityProxyProvider
23
 */
24
class BusinessPageBuilder
25
{
26
    protected $businessEntityHelper;
27
    protected $urlBuilder;
28
    protected $parameterConverter;
29
    protected $entityProxyProvider;
30
    protected $viewReferenceBuilder;
31
32
    //@todo Make it dynamic please
33
    protected $pageParameters = [
34
        'name',
35
        'bodyId',
36
        'bodyClass',
37
        'slug',
38
        'currentLocale',
39
    ];
40
41
    /**
42
     * @param BusinessEntityHelper $businessEntityHelper
43
     * @param UrlBuilder           $urlBuilder
44
     * @param ParameterConverter   $parameterConverter
45
     * @param EntityProxyProvider  $entityProxyProvider
46
     */
47 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...
48
        UrlBuilder $urlBuilder,
49
        ParameterConverter $parameterConverter,
50
        EntityProxyProvider $entityProxyProvider,
51
        ViewReferenceBuilder $viewReferenceBuilder)
52
    {
53
        $this->businessEntityHelper = $businessEntityHelper;
54
        $this->urlBuilder = $urlBuilder;
55
        $this->parameterConverter = $parameterConverter;
56
        $this->entityProxyProvider = $entityProxyProvider;
57
        $this->viewReferenceBuilder = $viewReferenceBuilder;
58
    }
59
60
    /**
61
     * Generate update the page parameters with the entity.
62
     *
63
     * @param BusinessTemplate $businessTemplate
64
     * @param mixed            $entity
65
     * @param EntityManager    $em
66
     *
67
     * @return VirtualBusinessPage
68
     */
69
    public function generateEntityPageFromTemplate(BusinessTemplate $businessTemplate, $entity, EntityManager $em)
70
    {
71
        $page = new VirtualBusinessPage();
72
        $currentLocale = $businessTemplate->getCurrentLocale();
73
74
        $reflect = new \ReflectionClass($businessTemplate);
75
        $templateProperties = $reflect->getProperties();
76
        $accessor = PropertyAccess::createPropertyAccessor();
77
78
        foreach ($templateProperties as $property) {
79
            if (!in_array($property->getName(), ['id', 'widgetMap', 'slots', 'seo', 'i18n', 'widgets', 'translations']) && !$property->isStatic()) {
80
                $value = $accessor->getValue($businessTemplate, $property->getName());
81
                $setMethod = 'set'.ucfirst($property->getName());
82
                if (method_exists($page, $setMethod)) {
83
                    $accessor->setValue($page, $property->getName(), $value);
84
                }
85
            }
86
        }
87
88
        //find Victoire\Bundle\BusinessEntityBundle\Entity\BusinessEntity object according to the given $entity
89
        $businessEntity = $this->businessEntityHelper->findByEntityInstance($entity);
90
91
        if ($businessEntity !== null) {
92
            //the business properties usable in a url
93
            $businessProperties = $this->getBusinessProperties($businessEntity);
94
95
            $entityProxy = $this->entityProxyProvider->getEntityProxy($entity, $businessEntity, $em);
96
97
            $page->setEntityProxy($entityProxy);
98
            $page->setTemplate($businessTemplate);
99
100
            if (in_array(Translatable::class, class_uses($entity))) {
101
102
                foreach ($entity->getTranslations() as $translation) {
103
                    $page->setCurrentLocale($translation->getLocale());
104
                    $entity->setCurrentLocale($translation->getLocale());
105
                    $businessTemplate->setCurrentLocale($translation->getLocale());
106
                    $page = $this->populatePage($page, $businessTemplate, $businessProperties, $em, $entity);
0 ignored issues
show
Documentation introduced by
$page is of type object|array, but the function expects a object<Victoire\Bundle\B...ty\VirtualBusinessPage>.

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...
107
                }
108
                $page->setCurrentLocale($currentLocale);
109
                $entity->setCurrentLocale($currentLocale);
110
                $businessTemplate->setCurrentLocale($currentLocale);
111
            } else {
112
                $page = $this->populatePage($page, $businessTemplate, $businessProperties, $em, $entity);
0 ignored issues
show
Documentation introduced by
$page is of type object|array, but the function expects a object<Victoire\Bundle\B...ty\VirtualBusinessPage>.

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...
113
            }
114
115
116
            if ($seo = $businessTemplate->getSeo()) {
117
                $pageSeo = clone $seo;
118
                $page->setSeo($pageSeo);
119
            }
120
        }
121
122
        return $page;
0 ignored issues
show
Bug Compatibility introduced by
The expression return $page; of type object|array is incompatible with the return type documented by Victoire\Bundle\Business...eEntityPageFromTemplate of type Victoire\Bundle\Business...ity\VirtualBusinessPage as it can also be of type array which is not included in this return type.
Loading history...
123
    }
124
125
    /**
126
     * Get the list of business properties usable for the url.
127
     *
128
     * @param BusinessEntity $businessEntity
129
     *
130
     * @return BusinessProperty[] The list of business properties
131
     */
132 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...
133
    {
134
        //the business properties usable in a url
135
        $businessProperties = $businessEntity->getBusinessPropertiesByType('businessParameter');
136
137
        //the business properties usable in a url
138
        $seoBusinessProps = $businessEntity->getBusinessPropertiesByType('seoable');
139
140
        //the business properties are the identifier and the seoables properties
141
        $businessProperties = array_merge($businessProperties, $seoBusinessProps);
142
143
        return $businessProperties;
144
    }
145
146
    /**
147
     * Generate update the page parameters with the entity.
148
     *
149
     * @param BusinessPage $page
150
     * @param Entity       $entity
151
     */
152
    public function updatePageParametersByEntity(BusinessPage $page, $entity)
153
    {
154
        //if no entity is provided
155
        if ($entity === null) {
156
            //we look for the entity of the page
157
            if ($page->getBusinessEntity() !== null) {
158
                $entity = $page->getBusinessEntity();
159
            }
160
        }
161
162
        //only if we have an entity instance
163
        if ($entity !== null) {
164
            $businessEntity = $this->businessEntityHelper->findByEntityInstance($entity);
165
166
            if ($businessEntity !== null) {
167
                $businessProperties = $this->getBusinessProperties($businessEntity);
168
169
                //parse the business properties
170
                foreach ($businessProperties as $businessProperty) {
171
                    //parse of seo attributes
172
                    foreach ($this->pageParameters as $pageAttribute) {
173
                        $string = $this->getEntityAttributeValue($page, $pageAttribute);
174
                        $updatedString = $this->parameterConverter->setBusinessPropertyInstance($string, $businessProperty, $entity);
175
                        $this->setEntityAttributeValue($page, $pageAttribute, $updatedString);
176
                    }
177
                }
178
            }
179
        }
180
    }
181
182
    /**
183
     * Get the content of an attribute of an entity given.
184
     *
185
     * @param BusinessPage $entity
186
     * @param string       $field
187
     *
188
     * @return mixed
189
     */
190 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...
191
    {
192
        $functionName = 'get'.ucfirst($field);
193
194
        $fieldValue = call_user_func([$entity, $functionName]);
195
196
        return $fieldValue;
197
    }
198
199
    /**
200
     * Update the value of the entity.
201
     *
202
     * @param BusinessPage $entity
203
     * @param string       $field
204
     * @param string       $value
205
     *
206
     * @return mixed
207
     */
208
    protected function setEntityAttributeValue($entity, $field, $value)
209
    {
210
        $functionName = 'set'.ucfirst($field);
211
212
        call_user_func([$entity, $functionName], $value);
213
    }
214
215
    /**
216
     * @param VirtualBusinessPage $page
217
     * @param BusinessTemplate    $businessTemplate
218
     * @param array               $businessProperties
219
     * @param EntityManager       $em
220
     * @param                     $entity
221
     *
222
     * @return VirtualBusinessPage
223
     * @throws IdentifierNotDefinedException
224
     * @throws \Exception
225
     */
226
    private function populatePage(VirtualBusinessPage $page, BusinessTemplate $businessTemplate, array $businessProperties, EntityManager $em, $entity)
227
    {
228
229
        $pageName = $businessTemplate->getName();
230
        $pageSlug = $businessTemplate->getSlug();
231
        $page->setSlug($pageSlug);
232
        $page->setName($pageName);
233
        $pageUrl = $this->urlBuilder->buildUrl($page);
234
        //parse the business properties
235
        foreach ($businessProperties as $businessProperty) {
236
            $pageUrl = $this->parameterConverter->setBusinessPropertyInstance($pageUrl, $businessProperty, $entity);
237
            $pageSlug = $this->parameterConverter->setBusinessPropertyInstance($pageSlug, $businessProperty, $entity);
238
            $pageName = $this->parameterConverter->setBusinessPropertyInstance($pageName, $businessProperty, $entity);
239
        }
240
        //Check that all twig variables in pattern url was removed for it's generated BusinessPage
241
        preg_match_all('/\{\%\s*([^\%\}]*)\s*\%\}|\{\{\s*([^\}\}]*)\s*\}\}/i', $pageUrl, $matches);
242
243
        if (count($matches[2])) {
244
            throw new IdentifierNotDefinedException($matches[2]);
245
        }
246
247
        $page->setUrl($pageUrl);
248
        $page->setSlug($pageSlug);
249
        $page->setName($pageName);
250
        $page->setReference($this->viewReferenceBuilder->buildViewReference($page, $em));
251
252
        return $page;
253
    }
254
}
255