BusinessPageBuilder::setEntityAttributeValue()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 3
nc 1
nop 3
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 Symfony\Component\PropertyAccess\PropertyAccessor;
9
use Victoire\Bundle\BlogBundle\Entity\Article;
10
use Victoire\Bundle\BusinessEntityBundle\Converter\ParameterConverter;
11
use Victoire\Bundle\BusinessEntityBundle\Entity\BusinessEntity;
12
use Victoire\Bundle\BusinessEntityBundle\Entity\BusinessProperty;
13
use Victoire\Bundle\BusinessEntityBundle\Helper\BusinessEntityHelper;
14
use Victoire\Bundle\BusinessEntityBundle\Provider\EntityProxyProvider;
15
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessPage;
16
use Victoire\Bundle\BusinessPageBundle\Entity\BusinessTemplate;
17
use Victoire\Bundle\BusinessPageBundle\Entity\VirtualBusinessPage;
18
use Victoire\Bundle\CoreBundle\Exception\IdentifierNotDefinedException;
19
use Victoire\Bundle\CoreBundle\Helper\UrlBuilder;
20
use Victoire\Bundle\ViewReferenceBundle\Builder\ViewReferenceBuilder;
21
22
class BusinessPageBuilder
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
23
{
24
    protected $businessEntityHelper;
25
    protected $urlBuilder;
26
    protected $parameterConverter;
27
    protected $entityProxyProvider;
28
    protected $viewReferenceBuilder;
29
30
    //@todo Make it dynamic please
31
    protected $pageParameters = [
32
        'name',
33
        'bodyId',
34
        'bodyClass',
35
        'slug',
36
        'currentLocale',
37
    ];
38
39
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$viewReferenceBuilder" missing
Loading history...
40
     * @param BusinessEntityHelper $businessEntityHelper
41
     * @param UrlBuilder           $urlBuilder
42
     * @param ParameterConverter   $parameterConverter
43
     * @param EntityProxyProvider  $entityProxyProvider
44
     */
45
    public function __construct(BusinessEntityHelper $businessEntityHelper,
0 ignored issues
show
Coding Style introduced by
The first parameter of a multi-line function declaration must be on the line after the opening bracket
Loading history...
46
        UrlBuilder $urlBuilder,
47
        ParameterConverter $parameterConverter,
48
        EntityProxyProvider $entityProxyProvider,
49
        ViewReferenceBuilder $viewReferenceBuilder)
0 ignored issues
show
Coding Style introduced by
The closing parenthesis of a multi-line function declaration must be on a new line
Loading history...
50
    {
0 ignored issues
show
Coding Style introduced by
The closing parenthesis and the opening brace of a multi-line function declaration must be on the same line
Loading history...
51
        $this->businessEntityHelper = $businessEntityHelper;
52
        $this->urlBuilder = $urlBuilder;
53
        $this->parameterConverter = $parameterConverter;
54
        $this->entityProxyProvider = $entityProxyProvider;
55
        $this->viewReferenceBuilder = $viewReferenceBuilder;
56
    }
57
58
    /**
59
     * Generate update the page parameters with the entity.
60
     *
61
     * @param BusinessTemplate $businessTemplate
62
     * @param mixed            $entity
63
     * @param EntityManager    $em
64
     *
65
     * @return VirtualBusinessPage
66
     */
67
    public function generateEntityPageFromTemplate(BusinessTemplate $businessTemplate, $entity, EntityManager $em)
68
    {
69
        $page = new VirtualBusinessPage();
70
        $currentLocale = $businessTemplate->getCurrentLocale();
71
72
        $reflect = new \ReflectionClass($businessTemplate);
73
        $templateProperties = $reflect->getProperties();
74
        $accessor = PropertyAccess::createPropertyAccessor();
75
76
        foreach ($templateProperties as $property) {
77
            if (!in_array($property->getName(), ['id', 'widgetMap', 'slots', 'seo', 'i18n', 'widgets', 'translations']) && !$property->isStatic()) {
78
                $value = $accessor->getValue($businessTemplate, $property->getName());
79
                $setMethod = 'set'.ucfirst($property->getName());
80
                if (method_exists($page, $setMethod)) {
81
                    $accessor->setValue($page, $property->getName(), $value);
82
                }
83
            }
84
        }
85
86
        //find Victoire\Bundle\BusinessEntityBundle\Entity\BusinessEntity object according to the given $entity
87
        $businessEntity = $businessTemplate->getBusinessEntity();
88
        //the business properties usable in a url
89
        $businessProperties = $this->getBusinessProperties($businessEntity);
90
91
        $entityProxy = $this->entityProxyProvider->getEntityProxy($entity, $businessEntity, $em);
92
93
        $page->setEntityProxy($entityProxy);
94
        $page->setTemplate($businessTemplate);
95
        /*
96
         * Returns class and parent's uses
97
         *
98
         * @param $class
99
         * @param bool $autoload
100
         * @return array
101
         */
102
        $class_uses_deep = function ($class, $autoload = true) {
0 ignored issues
show
Coding Style introduced by
Variable "class_uses_deep" is not in valid camel caps format
Loading history...
103
            $traits = [];
104
            do {
105
                $traits = array_merge(class_uses($class, $autoload), $traits);
106
            } while ($class = get_parent_class($class));
107
            foreach ($traits as $trait => $same) {
108
                $traits = array_merge(class_uses($trait, $autoload), $traits);
109
            }
110
111
            return array_unique($traits);
112
        };
113
114
        $isTranslatableEntity = in_array(Translatable::class, $class_uses_deep($entity));
0 ignored issues
show
Coding Style introduced by
Variable "class_uses_deep" is not in valid camel caps format
Loading history...
115
        foreach ($businessTemplate->getTranslations() as $translation) {
116
            if ($entity instanceof Article &&
117
                    !in_array($translation->getLocale(), $entity->getBlog()->getAvailableLocales())
118
                ) {
119
                continue;
120
            }
121
122
            if ($isTranslatableEntity) {
123
                $entity->setCurrentLocale($translation->getLocale());
124
            }
125
            $page->setCurrentLocale($translation->getLocale());
126
            $businessTemplate->setCurrentLocale($translation->getLocale());
127
            $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...
128
        }
129
130
        if ($isTranslatableEntity) {
131
            $entity->setCurrentLocale($currentLocale);
132
        }
133
        $page->setCurrentLocale($currentLocale);
134
        $businessTemplate->setCurrentLocale($currentLocale);
135
136
        if ($seo = $businessTemplate->getSeo()) {
137
            $pageSeo = clone $seo;
138
            $page->setSeo($pageSeo);
139
        }
140
141
        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...
142
    }
143
144
    /**
145
     * Get the list of business properties usable for the url.
146
     *
147
     * @param BusinessEntity $businessEntity
148
     *
149
     * @return BusinessProperty[] The list of business properties
150
     */
151 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...
152
    {
153
        //the business properties usable in a url
154
        $businessProperties = $businessEntity->getBusinessPropertiesByType('businessParameter');
155
156
        //the business properties usable in a url
157
        $seoBusinessProps = $businessEntity->getBusinessPropertiesByType('seoable');
158
159
        //the business properties are the identifier and the seoables properties
160
        $businessProperties = array_merge($businessProperties->toArray(), $seoBusinessProps->toArray());
161
162
        return $businessProperties;
163
    }
164
165
    /**
166
     * Generate update the page parameters with the entity.
167
     *
168
     * @param BusinessPage $page
169
     * @param Entity       $entity
170
     */
171
    public function updatePageParametersByEntity(BusinessPage $page, $entity)
172
    {
173
        //if no entity is provided
174
        if ($entity === null) {
175
            //we look for the entity of the page
176
            if ($page->getEntity() !== null) {
177
                $entity = $page->getEntity();
178
            }
179
        }
180
181
        //only if we have an entity instance
182
        if ($entity !== null) {
183
            $businessEntity = $page->getBusinessEntity();
184
185
            if ($businessEntity !== null) {
186
                $businessProperties = $this->getBusinessProperties($businessEntity);
0 ignored issues
show
Documentation introduced by
$businessEntity is of type string, but the function expects a object<Victoire\Bundle\B...\Entity\BusinessEntity>.

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...
187
188
                //parse the business properties
189
                foreach ($businessProperties as $businessProperty) {
190
                    //parse of seo attributes
191
                    foreach ($this->pageParameters as $pageAttribute) {
192
                        $accessor = new PropertyAccessor();
193
                        $string = $accessor->getValue($page, $pageAttribute);
194
                        $updatedString = $this->parameterConverter->convertFromEntity($string, $businessProperty, $entity);
195
                        $this->setEntityAttributeValue($page, $pageAttribute, $updatedString);
196
                    }
197
                }
198
            }
199
        }
200
    }
201
202
    /**
203
     * Update the value of the entity.
204
     *
205
     * @param BusinessPage $entity
206
     * @param string       $field
207
     * @param string       $value
208
     *
209
     * @return mixed
210
     */
211
    protected function setEntityAttributeValue($entity, $field, $value)
212
    {
213
        $functionName = 'set'.ucfirst($field);
214
215
        call_user_func([$entity, $functionName], $value);
216
    }
217
218
    /**
219
     * @param VirtualBusinessPage $page
220
     * @param BusinessTemplate    $businessTemplate
221
     * @param array               $businessProperties
222
     * @param EntityManager       $em
223
     * @param                     $entity
224
     *
225
     * @throws IdentifierNotDefinedException
226
     * @throws \Exception
227
     *
228
     * @return VirtualBusinessPage
229
     */
230
    private function populatePage(VirtualBusinessPage $page, BusinessTemplate $businessTemplate, array $businessProperties, EntityManager $em, $entity)
231
    {
232
        $pageName = $businessTemplate->getName();
233
        $pageSlug = $businessTemplate->getSlug();
234
        $page->setSlug($pageSlug);
235
        $page->setName($pageName);
236
        $pageUrl = $this->urlBuilder->buildUrl($page);
237
        //parse the business properties
238
        foreach ($businessProperties as $businessProperty) {
239
            $pageUrl = $this->parameterConverter->convertFromEntity($pageUrl, $businessProperty, $entity);
240
            $pageSlug = $this->parameterConverter->convertFromEntity($pageSlug, $businessProperty, $entity);
241
            $pageName = $this->parameterConverter->convertFromEntity($pageName, $businessProperty, $entity);
242
        }
243
        //Check that all twig variables in pattern url was removed for it's generated BusinessPage
244
        preg_match_all('/\{\%\s*([^\%\}]*)\s*\%\}|\{\{\s*([^\}\}]*)\s*\}\}/i', $pageUrl, $matches);
245
246
        if (count($matches[2])) {
247
            throw new IdentifierNotDefinedException($matches[2]);
248
        }
249
250
        $page->setUrl($pageUrl);
251
        $page->setSlug($pageSlug);
252
        $page->setName($pageName);
253
        $page->setReference($this->viewReferenceBuilder->buildViewReference($page, $em));
254
255
        return $page;
256
    }
257
}
258