Completed
Push — develop ( b4fd40...785f8f )
by greg
03:10
created

Formgen::getServiceManager()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 4
rs 10
cc 1
eloc 2
nc 1
nop 0
1
<?php
2
3
namespace PlaygroundCore\Service;
4
5
use Zend\Form\Form;
6
use Zend\ServiceManager\ServiceManager;
7
use ZfcBase\EventManager\EventProvider;
8
use PlaygroundCore\Options\ModuleOptions;
9
use Zend\Form\Element;
10
use Zend\InputFilter\Factory as InputFactory;
11
use Zend\ServiceManager\ServiceLocatorInterface;
12
13
class Formgen extends EventProvider
14
{
15
16
    /**
17
     * @var formgenMapper
18
     */
19
    protected $formgenMapper;
20
21
     /**
22
     * @var localeService
23
     */
24
    protected $localeService;
25
26
    /**
27
     * @var UserServiceOptionsInterface
28
     */
29
    protected $options;
30
31
    /**
32
     *
33
     * @var ServiceManager
34
     */
35
    protected $serviceLocator;
36
37
    public function __construct(ServiceLocatorInterface $locator)
38
    {
39
        $this->serviceLocator = $locator;
0 ignored issues
show
Documentation Bug introduced by
$locator is of type object<Zend\ServiceManag...erviceLocatorInterface>, but the property $serviceLocator was declared to be of type object<Zend\ServiceManager\ServiceManager>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
40
    }
41
42
    public function insert($data)
43
    {
44
        $formgen = new \PlaygroundCore\Entity\Formgen();
45
        $data = $this->getData($data);
46
        $formgen->populate($data);
47
        if (!empty($data['locale'])) {
48
            $formgen->setLocale($this->getLocaleService()->getLocaleMapper()->findById($data['locale']));
49
        }
50
        return $this->getFormgenMapper()->insert($formgen);
51
    }
52
53
    public function update($formgen, $data)
54
    {
55
        $data = $this->getData($data);
56
        $formgen->setTitle($data['title']);
57
        $formgen->setDescription($data['description']);
58
        $formgen->setFormjsonified($data['formjsonified']);
59
        $formgen->setFormTemplate($data['formtemplate']);
60
        if (!empty($data['locale'])) {
61
            $formgen->setLocale($this->getLocaleService()->getLocaleMapper()->findById($data['locale']));
62
        }
63
        return $this->getFormgenMapper()->update($formgen);
64
    }
65
66
    private function getData($data)
67
    {
68
        $title = '';
69
        $description = '';
70
        if (isset($data['form_jsonified']) && $data['form_jsonified']) {
71
            $jsonTmp = str_replace('\\', '_', $data['form_jsonified']);
72
            $jsonPV = json_decode($jsonTmp);
73
            foreach ($jsonPV as $element) {
74
                if ($element->form_properties) {
75
                    $attributes = $element->form_properties[0];
76
                    $title = $attributes->title;
77
                    $description = $attributes->description;
78
                    $locale = $attributes->locale;
79
                    break;
80
                }
81
            }
82
        }
83
        $return = array();
84
        $return['title'] = $title;
85
        $return['description'] = $description;
86
        $return['locale'] = isset($locale) ? $locale : null;
87
        $return['formjsonified'] = isset($data['form_jsonified']) ? $data['form_jsonified'] : null;
88
        $return['formtemplate'] = isset($data['form_template']) ? $data['form_template'] : null;
89
        $return['active'] = true;
90
        return $return;
91
    }
92
93
    public function getAttributes($attributes)
94
    {
95
        $a = array();
96
97
        $a['name']          = isset($attributes->name)? $attributes->name : '';
98
        $a['placeholder']   = isset($attributes->data->placeholder)? $attributes->data->placeholder : '';
99
        $a['label']         = isset($attributes->data->label)? $attributes->data->label : '';
100
        $a['required']      = (isset($attributes->data->required) && $attributes->data->required == 'true')?
101
            true:
102
            false;
103
        $a['class']         = isset($attributes->data->class)? $attributes->data->class : '';
104
        $a['id']            = isset($attributes->data->id)? $attributes->data->id : '';
105
        $a['lengthMin']     = isset($attributes->data->length)? $attributes->data->length->min : '';
106
        $a['lengthMax']     = isset($attributes->data->length)? $attributes->data->length->max : '';
107
        $a['validator']     = isset($attributes->data->validator)? $attributes->data->validator : '';
108
        $a['innerData']     = isset($attributes->data->innerData)? $attributes->data->innerData : array();
109
        $a['dropdownValues']= isset($attributes->data->dropdownValues)?
110
            $attributes->data->dropdownValues :
111
            array();
112
        $a['filesizeMin']   = isset($attributes->data->filesize)? $attributes->data->filesize->min : 0;
113
        $a['filesizeMax']   = isset($attributes->data->filesize)? $attributes->data->filesize->max : 10*1024*1024;
114
115
        return $a;
116
    }
117
118
    /**
119
     * @param \Zend\InputFilter\InputFilter $inputFilter
120
     */
121
    public function decorate($element, $attr, $inputFilter)
122
    {
123
        $factory = new InputFactory();
124
        $element->setName($attr['label']);
125
        $element->setLabel($attr['label']);
126
        $element->setAttributes(
127
            array(
128
                'placeholder'   => $attr['placeholder'],
129
                'required'      => $attr['required'],
130
                'class'         => $attr['class'],
131
                'id'            => $attr['id']
132
            )
133
        );
134
135
        $options = array();
136
        $options['encoding'] = 'UTF-8';
137
        if ($attr['lengthMin'] && $attr['lengthMin'] > 0) {
138
            $options['min'] = $attr['lengthMin'];
139
        }
140
        if ($attr['lengthMax'] && $attr['lengthMax'] > $attr['lengthMin']) {
141
            $options['max'] = $attr['lengthMax'];
142
            $element->setAttribute('maxlength', $attr['lengthMax']);
143
            $options['messages'] = array(
144
                \Zend\Validator\StringLength::TOO_LONG => sprintf(
145
                    $this->serviceLocator->get('translator')->translate(
146
                        'This field contains more than %s characters',
147
                        'playgroundcore'
148
                    ),
149
                    $attr['lengthMax']
150
                )
151
            );
152
        }
153
154
        $validators = array(
155
            array(
156
                'name'    => 'StringLength',
157
                'options' => $options,
158
            ),
159
        );
160
        if ($attr['validator']) {
161
            $regex = "/.*\(([^)]*)\)/";
162
            preg_match($regex, $attr['validator'], $matches);
163
            $valArray = array(
164
                'name' => str_replace(
165
                    '('.$matches[1].')',
166
                    '',
167
                    $attr['validator']
168
                ),
169
                'options' => array($matches[1])
170
            );
171
            $validators[] = $valArray;
172
        }
173
174
        $inputFilter->add($factory->createInput(array(
175
            'name'     => $attr['name'],
176
            'required' => $attr['required'],
177
            'filters'  => array(
178
                array('name' => 'StripTags'),
179
                array('name' => 'StringTrim'),
180
            ),
181
            'validators' => $validators,
182
        )));
183
184
        return $element;
185
    }
186
187
    public function render($formPV, $id)
188
    {
189
        $form = new Form();
190
        $form->setAttribute('id', $id);
191
        $inputFilter = new \Zend\InputFilter\InputFilter();
192
        $factory = new InputFactory();
193
194
        foreach ($formPV as $element) {
195 View Code Duplication
            if (isset($element->line_text)) {
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...
196
                $attr  = $this->getAttributes($element->line_text[0]);
197
                $element = new Element\Text($attr['name']);
198
                $element = $this->decorate($element, $attr, $inputFilter);
199
                $form->add($element);
200
            }
201 View Code Duplication
            if (isset($element->line_password)) {
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
                $attr = $this->getAttributes($element->line_password[0]);
203
                $element = new Element\Password($attr['name']);
204
                $element = $this->decorate($element, $attr, $inputFilter);
205
                $form->add($element);
206
            }
207 View Code Duplication
            if (isset($element->line_hidden)) {
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...
208
                $attr = $this->getAttributes($element->line_hidden[0]);
209
                $element = new Element\Hidden($attr['name']);
210
                $element = $this->decorate($element, $attr, $inputFilter);
211
                $form->add($element);
212
            }
213 View Code Duplication
            if (isset($element->line_email)) {
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...
214
                $attr = $this->getAttributes($element->line_email[0]);
215
                $element = new Element\Email($attr['name']);
216
                $element = $this->decorate($element, $attr, $inputFilter);
217
                $form->add($element);
218
            }
219 View Code Duplication
            if (isset($element->line_radio)) {
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...
220
                $attr = $this->getAttributes($element->line_radio[0]);
221
                $element = new Element\Radio($attr['name']);
222
223
                $element->setLabel($attr['label']);
224
                $element->setAttributes(
225
                    array(
226
                        'name'      => $attr['name'],
227
                        'required'  => $attr['required'],
228
                        'allowEmpty'=> !$attr['required'],
229
                        'class'     => $attr['class'],
230
                        'id'        => $attr['id']
231
                    )
232
                );
233
                $values = array();
234
                foreach ($attr['innerData'] as $value) {
235
                    $values[] = $value->label;
236
                }
237
                $element->setValueOptions($values);
238
        
239
                $options = array();
240
                $options['encoding'] = 'UTF-8';
241
                $options['disable_inarray_validator'] = true;
242
        
243
                $element->setOptions($options);
244
        
245
                $form->add($element);
246
        
247
                $inputFilter->add($factory->createInput(array(
248
                    'name'     => $attr['name'],
249
                    'required' => $attr['required'],
250
                    'allowEmpty' => !$attr['required'],
251
                )));
252
            }
253 View Code Duplication
            if (isset($element->line_checkbox)) {
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...
254
                $attr = $this->getAttributes($element->line_checkbox[0]);
255
                $element = new Element\MultiCheckbox($attr['name']);
256
        
257
                $element->setLabel($attr['label']);
258
                $element->setAttributes(
259
                    array(
260
                        'name'      => $attr['name'],
261
                        'required'  => $attr['required'],
262
                        'allowEmpty'=> !$attr['required'],
263
                        'class'     => $attr['class'],
264
                        'id'        => $attr['id']
265
                    )
266
                );
267
268
                $values = array();
269
                foreach ($attr['innerData'] as $value) {
270
                    $values[] = $value->label;
271
                }
272
                $element->setValueOptions($values);
273
                $form->add($element);
274
        
275
                $options = array();
276
                $options['encoding'] = 'UTF-8';
277
                $options['disable_inarray_validator'] = true;
278
        
279
                $element->setOptions($options);
280
        
281
                $inputFilter->add($factory->createInput(array(
282
                    'name'      => $attr['name'],
283
                    'required'  => $attr['required'],
284
                    'allowEmpty'=> !$attr['required'],
285
                )));
286
            }
287 View Code Duplication
            if (isset($element->line_dropdown)) {
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...
288
                $attr = $this->getAttributes($element->line_dropdown[0]);
289
                $element = new Element\Select($attr['name']);
290
291
                $element->setLabel($attr['label']);
292
                $element->setAttributes(
293
                    array(
294
                        'name'      => $attr['name'],
295
                        'required'  => $attr['required'],
296
                        'allowEmpty'=> !$attr['required'],
297
                        'class'     => $attr['class'],
298
                        'id'        => $attr['id']
299
                    )
300
                );
301
                $values = array();
302
                foreach ($attr['dropdownValues'] as $value) {
303
                    $values[] = $value->dropdown_label;
304
                }
305
                $element->setValueOptions($values);
306
                $form->add($element);
307
        
308
                $options = array();
309
                $options['encoding'] = 'UTF-8';
310
                $options['disable_inarray_validator'] = true;
311
        
312
                $element->setOptions($options);
313
        
314
                $inputFilter->add($factory->createInput(array(
315
                    'name'     => $attr['name'],
316
                    'required' => $attr['required'],
317
                    'allowEmpty' => !$attr['required'],
318
                )));
319
            }
320 View Code Duplication
            if (isset($element->line_paragraph)) {
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...
321
                $attr = $this->getAttributes($element->line_paragraph[0]);
322
                $element = new Element\Textarea($attr['name']);
323
                $element = $this->decorate($element, $attr, $inputFilter);
324
                $form->add($element);
325
            }
326
            if (isset($element->line_upload)) {
327
                $attr = $this->getAttributes($element->line_upload[0]);
328
                $element = new Element\File($attr['name']);
329
330
                $element->setLabel($attr['label']);
331
                $element->setAttributes(
332
                    array(
333
                        'name'      => $attr['name'],
334
                        'required'  => $attr['required'],
335
                        'class'     => $attr['class'],
336
                        'id'        => $attr['id']
337
                    )
338
                );
339
                $form->add($element);
340
        
341
                $inputFilter->add($factory->createInput(array(
342
                    'name'     => $attr['name'],
343
                    'required' => $attr['required'],
344
                    'validators' => array(
345
                        array(
346
                            'name' => '\Zend\Validator\File\Size',
347
                            'options' => array('min' => $attr['filesizeMin'], 'max' => $attr['filesizeMax'])
348
                        ),
349
                        array(
350
                            'name' => '\Zend\Validator\File\Extension',
351
                            'options'  => array(
352
                                'png,PNG,jpg,JPG,jpeg,JPEG,gif,GIF',
353
                                'messages' => array(
354
                                    \Zend\Validator\File\Extension::FALSE_EXTENSION =>'Veuillez télécharger une image'
355
                                )
356
                            )
357
                        ),
358
                    ),
359
                )));
360
            }
361
        }
362
363
        $form->setInputFilter($inputFilter);
364
365
        return $form;
366
    }
367
368
    /**
369
     * getFormgenMapper
370
     *
371
     * @return FormgenMapper
372
     */
373
    public function getFormgenMapper()
374
    {
375
        if (null === $this->formgenMapper) {
376
            $this->formgenMapper = $this->serviceLocator->get('playgroundcore_formgen_mapper');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->serviceLocator->g...ndcore_formgen_mapper') can also be of type array. However, the property $formgenMapper is declared as type object<PlaygroundCore\Service\FormgenMapper>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
377
        }
378
379
        return $this->formgenMapper;
0 ignored issues
show
Bug Compatibility introduced by
The expression $this->formgenMapper; of type object|array adds the type array to the return on line 379 which is incompatible with the return type documented by PlaygroundCore\Service\Formgen::getFormgenMapper of type PlaygroundCore\Service\FormgenMapper.
Loading history...
380
    }
381
382
383
    public function getLocaleService()
384
    {
385
        if (null === $this->localeService) {
386
            $this->localeService = $this->serviceLocator->get('playgroundcore_locale_service');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->serviceLocator->g...ndcore_locale_service') can also be of type array. However, the property $localeService is declared as type object<PlaygroundCore\Service\localeService>. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

    public function __construct($id)
    {
        $this->id = $id;
    }

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
387
        }
388
389
        return $this->localeService;
390
    }
391
392
    /**
393
     * setFormgenMapper
394
     * @param  FormgenMapper $formgenMapper
395
     *
396
     * @return PlaygroundCore\Mapper\FormGen FormGen
397
     */
398
    public function setFormgenMapper($formgenMapper)
399
    {
400
        $this->formgenMapper = $formgenMapper;
401
402
        return $this;
403
    }
404
405
    /**
406
     * setOptions
407
     * @param  ModuleOptions $options
408
     *
409
     * @return PlaygroundCore\Service\Locale $this
410
     */
411
    public function setOptions(ModuleOptions $options)
412
    {
413
        $this->options = $options;
0 ignored issues
show
Documentation Bug introduced by
It seems like $options of type object<PlaygroundCore\Options\ModuleOptions> is incompatible with the declared type object<PlaygroundCore\Se...erviceOptionsInterface> of property $options.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
414
415
        return $this;
416
    }
417
418
    /**
419
     * getOptions
420
     *
421
     * @return ModuleOptions $optins
422
     */
423
    public function getOptions()
424
    {
425
        if (!$this->options instanceof ModuleOptions) {
426
            $this->setOptions($this->serviceLocator->get('playgroundcore_module_options'));
0 ignored issues
show
Documentation introduced by
$this->serviceLocator->g...ndcore_module_options') is of type object|array, but the function expects a object<PlaygroundCore\Options\ModuleOptions>.

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...
427
        }
428
429
        return $this->options;
430
    }
431
}
432