Completed
Push — master ( 5d51b4...87fdd9 )
by Paul
10s
created

generateEntityPageFromTemplate()   B

Complexity

Conditions 9
Paths 20

Size

Total Lines 54
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Importance

Changes 10
Bugs 3 Features 1
Metric Value
c 10
b 3
f 1
dl 0
loc 54
rs 7.255
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\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
        'currentLocale',
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 mixed            $entity
64
     * @param EntityManager    $em
65
     *
66
     * @return VirtualBusinessPage
67
     */
68
    public function generateEntityPageFromTemplate(BusinessTemplate $businessTemplate, $entity, EntityManager $em)
69
    {
70
        $page = new VirtualBusinessPage();
71
        $currentLocale = $businessTemplate->getCurrentLocale();
72
73
        $reflect = new \ReflectionClass($businessTemplate);
74
        $templateProperties = $reflect->getProperties();
75
        $accessor = PropertyAccess::createPropertyAccessor();
76
77
        foreach ($templateProperties as $property) {
78
            if (!in_array($property->getName(), ['id', 'widgetMap', 'slots', 'seo', 'i18n', 'widgets', 'translations']) && !$property->isStatic()) {
79
                $value = $accessor->getValue($businessTemplate, $property->getName());
80
                $setMethod = 'set'.ucfirst($property->getName());
81
                if (method_exists($page, $setMethod)) {
82
                    $accessor->setValue($page, $property->getName(), $value);
83
                }
84
            }
85
        }
86
87
        //find Victoire\Bundle\BusinessEntityBundle\Entity\BusinessEntity object according to the given $entity
88
        $businessEntity = $this->businessEntityHelper->findByEntityInstance($entity);
89
90
        if ($businessEntity !== null) {
91
            //the business properties usable in a url
92
            $businessProperties = $this->getBusinessProperties($businessEntity);
93
94
            $entityProxy = $this->entityProxyProvider->getEntityProxy($entity, $businessEntity, $em);
95
96
            $page->setEntityProxy($entityProxy);
97
            $page->setTemplate($businessTemplate);
98
99
            if (in_array(Translatable::class, class_uses($entity))) {
100
                foreach ($entity->getTranslations() as $translation) {
101
                    $page->setCurrentLocale($translation->getLocale());
102
                    $entity->setCurrentLocale($translation->getLocale());
103
                    $businessTemplate->setCurrentLocale($translation->getLocale());
104
                    $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...
105
                }
106
                $page->setCurrentLocale($currentLocale);
107
                $entity->setCurrentLocale($currentLocale);
108
                $businessTemplate->setCurrentLocale($currentLocale);
109
            } else {
110
                $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...
111
            }
112
113
114
            if ($seo = $businessTemplate->getSeo()) {
115
                $pageSeo = clone $seo;
116
                $page->setSeo($pageSeo);
117
            }
118
        }
119
120
        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...
121
    }
122
123
    /**
124
     * Get the list of business properties usable for the url.
125
     *
126
     * @param BusinessEntity $businessEntity
127
     *
128
     * @return BusinessProperty[] The list of business properties
129
     */
130 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...
131
    {
132
        //the business properties usable in a url
133
        $businessProperties = $businessEntity->getBusinessPropertiesByType('businessParameter');
134
135
        //the business properties usable in a url
136
        $seoBusinessProps = $businessEntity->getBusinessPropertiesByType('seoable');
137
138
        //the business properties are the identifier and the seoables properties
139
        $businessProperties = array_merge($businessProperties, $seoBusinessProps);
140
141
        return $businessProperties;
142
    }
143
144
    /**
145
     * Generate update the page parameters with the entity.
146
     *
147
     * @param BusinessPage $page
148
     * @param Entity       $entity
149
     */
150
    public function updatePageParametersByEntity(BusinessPage $page, $entity)
151
    {
152
        //if no entity is provided
153
        if ($entity === null) {
154
            //we look for the entity of the page
155
            if ($page->getBusinessEntity() !== null) {
156
                $entity = $page->getBusinessEntity();
157
            }
158
        }
159
160
        //only if we have an entity instance
161
        if ($entity !== null) {
162
            $businessEntity = $this->businessEntityHelper->findByEntityInstance($entity);
163
164
            if ($businessEntity !== null) {
165
                $businessProperties = $this->getBusinessProperties($businessEntity);
166
167
                //parse the business properties
168
                foreach ($businessProperties as $businessProperty) {
169
                    //parse of seo attributes
170
                    foreach ($this->pageParameters as $pageAttribute) {
171
                        $string = $this->getEntityAttributeValue($page, $pageAttribute);
172
                        $updatedString = $this->parameterConverter->setBusinessPropertyInstance($string, $businessProperty, $entity);
173
                        $this->setEntityAttributeValue($page, $pageAttribute, $updatedString);
174
                    }
175
                }
176
            }
177
        }
178
    }
179
180
    /**
181
     * Get the content of an attribute of an entity given.
182
     *
183
     * @param BusinessPage $entity
184
     * @param string       $field
185
     *
186
     * @return mixed
187
     */
188 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...
189
    {
190
        $functionName = 'get'.ucfirst($field);
191
192
        $fieldValue = call_user_func([$entity, $functionName]);
193
194
        return $fieldValue;
195
    }
196
197
    /**
198
     * Update the value of the entity.
199
     *
200
     * @param BusinessPage $entity
201
     * @param string       $field
202
     * @param string       $value
203
     *
204
     * @return mixed
205
     */
206
    protected function setEntityAttributeValue($entity, $field, $value)
207
    {
208
        $functionName = 'set'.ucfirst($field);
209
210
        call_user_func([$entity, $functionName], $value);
211
    }
212
213
    /**
214
     * @param VirtualBusinessPage $page
215
     * @param BusinessTemplate    $businessTemplate
216
     * @param array               $businessProperties
217
     * @param EntityManager       $em
218
     * @param                     $entity
219
     *
220
     * @throws IdentifierNotDefinedException
221
     * @throws \Exception
222
     *
223
     * @return VirtualBusinessPage
224
     */
225
    private function populatePage(VirtualBusinessPage $page, BusinessTemplate $businessTemplate, array $businessProperties, EntityManager $em, $entity)
226
    {
227
        $pageName = $businessTemplate->getName();
228
        $pageSlug = $businessTemplate->getSlug();
229
        $page->setSlug($pageSlug);
230
        $page->setName($pageName);
231
        $pageUrl = $this->urlBuilder->buildUrl($page);
232
        //parse the business properties
233
        foreach ($businessProperties as $businessProperty) {
234
            $pageUrl = $this->parameterConverter->setBusinessPropertyInstance($pageUrl, $businessProperty, $entity);
235
            $pageSlug = $this->parameterConverter->setBusinessPropertyInstance($pageSlug, $businessProperty, $entity);
236
            $pageName = $this->parameterConverter->setBusinessPropertyInstance($pageName, $businessProperty, $entity);
237
        }
238
        //Check that all twig variables in pattern url was removed for it's generated BusinessPage
239
        preg_match_all('/\{\%\s*([^\%\}]*)\s*\%\}|\{\{\s*([^\}\}]*)\s*\}\}/i', $pageUrl, $matches);
240
241
        if (count($matches[2])) {
242
            throw new IdentifierNotDefinedException($matches[2]);
243
        }
244
245
        $page->setUrl($pageUrl);
246
        $page->setSlug($pageSlug);
247
        $page->setName($pageName);
248
        $page->setReference($this->viewReferenceBuilder->buildViewReference($page, $em));
249
250
        return $page;
251
    }
252
}
253