ContentItemTypeType::buildView()   C
last analyzed

Complexity

Conditions 15
Paths 43

Size

Total Lines 42
Code Lines 24

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 240

Importance

Changes 0
Metric Value
cc 15
eloc 24
nc 43
nop 3
dl 0
loc 42
ccs 0
cts 26
cp 0
crap 240
rs 5.9166
c 0
b 0
f 0

How to fix   Complexity   

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
 * @author Gerard van Helden <[email protected]>
4
 * @copyright Zicht Online <http://zicht.nl>
5
 */
6
7
namespace Zicht\Bundle\PageBundle\Type;
8
9
use Sonata\AdminBundle\Admin\Pool;
10
use Symfony\Component\Form\AbstractType;
11
use Symfony\Component\Form\FormBuilderInterface;
12
use Symfony\Component\Form\FormView;
13
use Symfony\Component\Form\FormInterface;
14
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
15
use Symfony\Component\Routing\Exception\InvalidParameterException;
16
use Symfony\Component\Routing\Exception\MissingMandatoryParametersException;
17
use Zicht\Bundle\PageBundle\Entity\ContentItem;
18
use Zicht\Bundle\PageBundle\Model\ContentItemContainer;
19
use Zicht\Util\Str;
20
21
/**
22
 * Provides a "type" dropdown for creating content items, and a "edit link" for editing content items
23
 * that have their own admin.
24
 */
25
class ContentItemTypeType extends AbstractType
26
{
27
    /**
28
     * Constructor
29
     *
30
     * @param \Sonata\AdminBundle\Admin\Pool $sonata
31
     * @param string $contentItemClass
32
     */
33 1
    public function __construct($contentItemClass, Pool $sonata = null)
34
    {
35 1
        $this->contentItemClass = $contentItemClass;
0 ignored issues
show
Bug Best Practice introduced by
The property contentItemClass does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
36 1
        $this->sonata = $sonata;
0 ignored issues
show
Bug Best Practice introduced by
The property sonata does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
37 1
    }
38
39
40
    /**
41
     * @{inheritDoc}
42
     */
43 1
    public function setDefaultOptions(OptionsResolverInterface $resolver)
44
    {
45 1
        $resolver->setDefaults(
46
            array(
47 1
                'inherit_data' => true,
48 1
                'data_class' => $this->contentItemClass,
49 1
                'container' => '',
50
                'translation_domain' => 'admin'
51 1
            )
52 1
        );
53 1
    }
54
55
56
    /**
57
     * @{inheritDoc}
58
     */
59
    public function buildForm(FormBuilderInterface $builder, array $options)
60
    {
61
        if ($options['container']) {
62
            $page = $options['container'];
63
            $choiceFilter = function ($choices) use ($page) {
64
                $ret = array();
65
                if ($page instanceof ContentItemContainer && null !== $page->getContentItemMatrix()) {
66
                    $types = $page->getContentItemMatrix()->getTypes();
67
68
                    foreach ($choices as $className => $name) {
69
                        if (in_array($className, $types)) {
70
                            $ret[$className] = $name;
71
                        }
72
                    }
73
                } else {
74
                    return $choices;
75
                }
76
                return $ret;
77
            };
78
        } else {
79
            $choiceFilter = null;
80
        }
81
        $builder
82
            ->add(
83
                'convertToType',
84
                'zicht_discriminator_map',
85
                array(
86
                    'entity' => $this->contentItemClass,
87
                    'choice_filter' => $choiceFilter
88
                )
89
            );
90
    }
91
92
93
    /**
94
     * @{inheritDoc}
95
     */
96
    public function buildView(FormView $view, FormInterface $form, array $options)
97
    {
98
        if (isset($view->vars['sonata_admin']['admin'])) {
99
            $genericAdmin = $view->vars['sonata_admin']['admin'];
100
101
            $parentAdmin = $genericAdmin->getParent();
102
103
            /** @var ContentItem $subject */
104
            $subject = $form->getParent()->getData();
105
106
            $view->vars['type'] = null;
107
            $view->vars['edit_url'] = null;
108
109
            try {
110
                $isPersistedEntity = $subject->getId();
0 ignored issues
show
Bug introduced by
The method getId() does not exist on Zicht\Bundle\PageBundle\Entity\ContentItem. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

110
                /** @scrutinizer ignore-call */ 
111
                $isPersistedEntity = $subject->getId();

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
111
                // $subject->getId() does not work when the `zicht/versioning-bundle` is used, as those ContentItem entities do exist but do *not* have an id when editing a non-active version.
112
                if ($this->sonata->getContainer()->has('zicht_versioning.manager') && $this->sonata->getContainer()->get('zicht_versioning.manager')->isManaged($subject->getPage())) {
0 ignored issues
show
Bug introduced by
The method getPage() does not exist on Zicht\Bundle\PageBundle\Entity\ContentItem. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

112
                if ($this->sonata->getContainer()->has('zicht_versioning.manager') && $this->sonata->getContainer()->get('zicht_versioning.manager')->isManaged($subject->/** @scrutinizer ignore-call */ getPage())) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
The method getContainer() does not exist on null. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

112
                if ($this->sonata->/** @scrutinizer ignore-call */ getContainer()->has('zicht_versioning.manager') && $this->sonata->getContainer()->get('zicht_versioning.manager')->isManaged($subject->getPage())) {

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
113
                    if (method_exists($subject, 'getWeight')) {
114
                        // sonata adds new entries with a weight of 0.
115
                        $isPersistedEntity = $subject->getWeight() > 0 ? true : false;
116
                    } else {
117
                        // unknown how to determine this when the weight is not available. possibly update VersioningBundle to tell us this.
118
                        throw new \LogicException('Unable to determine the persisted state of this contentitem');
119
                    }
120
                }
121
                if ($isPersistedEntity && $typeAdmin = $this->sonata->getAdminByClass(get_class($subject))) {
122
                    $view->vars['type'] = Str::humanize(Str::classname($subject->getConvertToType()));
123
                    $childAdmin = $this->sonata->getAdminByAdminCode($parentAdmin->getCode() . '|' . $typeAdmin->getCode());
124
                    $childAdmin->setRequest($genericAdmin->getRequest());
125
126
                    if ($subject && $subject->getPage() && $subject->getPage()->getId()) {
127
                        try {
128
                            $view->vars['edit_url'] = $childAdmin->generateObjectUrl('edit', $subject, ['childId' => $subject->getId()]);
129
                        } catch (InvalidParameterException $e) {
130
                            //2.2 edit url not needed when generating other admins (this is done in the POST of the sonata_collection_type)
131
                        } catch (MissingMandatoryParametersException $e) {
132
                            //>= 2.3
133
                        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
134
                        }
135
                    }
136
                }
137
            } catch (\RuntimeException $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
138
            }
139
        }
140
    }
141
142
143
    /**
144
     * Returns the name of this type.
145
     *
146
     * @return string The name of this type
147
     */
148 1
    public function getName()
149
    {
150 1
        return 'zicht_content_item_type';
151
    }
152
}
153