Completed
Push — master ( e519e0...173396 )
by
unknown
25:55
created

MultiGroupFormGroup::formProperties()   C

Complexity

Conditions 15
Paths 121

Size

Total Lines 64

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 64
rs 5.7416
c 0
b 0
f 0
cc 15
nc 121
nop 1

How to fix   Long Method    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
namespace Charcoal\Admin\Widget\FormGroup;
4
5
// from 'charcoal-admin'
6
use Charcoal\Admin\Widget\FormPropertyWidget;
7
use Charcoal\Admin\Widget\MultiGroupWidget;
8
9
// from 'charcoal-ui'
10
use Charcoal\Ui\Form\FormInterface;
11
use Charcoal\Ui\FormGroup\FormGroupInterface;
12
use Charcoal\Ui\FormGroup\FormGroupTrait;
13
use Charcoal\Ui\UiItemInterface;
14
use Charcoal\Ui\UiItemTrait;
15
16
/**
17
 * Class NestedFormGroup
18
 */
19
class MultiGroupFormGroup extends MultiGroupWidget implements
20
    FormGroupInterface,
21
    UiItemInterface
22
{
23
    use FormGroupTrait;
24
    use UiItemTrait;
25
26
    /**
27
     * @return string
28
     */
29
    public function template()
30
    {
31
        return 'charcoal/admin/widget/multi-group';
32
    }
33
34
    /**
35
     * @return array
36
     */
37
    public function dataFromObject()
38
    {
39
        $obj         = $this->obj();
40
        $objMetadata = $obj->metadata();
41
42
        $adminMetadata   = (isset($objMetadata['admin']) ? $objMetadata['admin'] : null);
43
        $adminFormGroups = (isset($adminMetadata['form_groups']) ? $adminMetadata['form_groups'] : null);
44
45
        $groups = $this->groups();
46
47
        if (!$adminFormGroups) {
48
            return [];
49
        }
50
51
        foreach ($groups as $group) {
52
            if ($adminFormGroups && isset($adminFormGroups[$group->ident()])) {
53
                $metadata = array_replace_recursive($adminFormGroups[$group->ident()], $group->data());
54
55
                $this->updateFormGroup($group, $metadata);
56
            }
57
        }
58
59
        return [];
60
    }
61
62
    /**
63
     * @return $this|array
64
     * @throws \Exception If the model factory was not set before being accessed.
65
     */
66
    public function dataFromMetadata()
67
    {
68
        $data = $this->widgetMetadata();
69
70
        if (!$data) {
71
            return [];
72
        }
73
74
        $adminMetadata   = (isset($data['admin']) ? $data['admin'] : null);
75
        $adminFormGroups = (isset($adminMetadata['form_groups']) ? $adminMetadata['form_groups'] : null);
76
77
        if (isset($data['groups']) && isset($adminFormGroups)) {
78
            $extraFormGroups = array_intersect(
79
                array_keys($adminFormGroups),
80
                array_keys($data['groups'])
81
            );
82
            foreach ($extraFormGroups as $groupIdent) {
83
                $data['groups'][$groupIdent] = array_replace_recursive(
84
                    $adminFormGroups[$groupIdent],
85
                    $data['groups'][$groupIdent]
86
                );
87
            }
88
        }
89
90
        foreach ($data['properties'] as $ident => $property) {
91
            $this->form()->getOrCreateFormProperty($ident, $property);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Charcoal\Ui\Form\FormInterface as the method getOrCreateFormProperty() does only exist in the following implementations of said interface: Charcoal\Admin\Widget\DocWidget, Charcoal\Admin\Widget\FormWidget, Charcoal\Admin\Widget\ObjectFormWidget, Charcoal\Admin\Widget\QuickFormWidget.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
92
        }
93
94
        return $data;
95
    }
96
97
    /**
98
     * Retrieve the object's properties as form controls.
99
     *
100
     * @param  array $group An optional group to use.
101
     * @throws \UnexpectedValueException If a property data is invalid.
102
     * @return FormPropertyWidget[]
103
     */
104
    public function formProperties(array $group = null)
105
    {
106
        if (!key_exists(self::DATA_SOURCE_METADATA, array_flip($this->dataSources())) ||
107
            !$this->widgetMetadata()) {
108
            return iterator_to_array($this->form()->formProperties());
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Charcoal\Ui\Form\FormInterface as the method formProperties() does only exist in the following implementations of said interface: Charcoal\Admin\Widget\DocWidget, Charcoal\Admin\Widget\Fo...oup\MultiGroupFormGroup, Charcoal\Admin\Widget\FormWidget, Charcoal\Admin\Widget\ObjectFormWidget, Charcoal\Admin\Widget\QuickFormWidget.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
109
        }
110
111
        $propertyIdentPattern = '%1$s[%2$s]';
112
        $entry                = null;
113
114
        try {
115
            $store = $this->storageProperty();
116
        } catch (\Exception $e) {
117
            $store = null;
118
        }
119
120
        if ($store) {
121
            $entry = $this->obj()[$store->ident()];
122
            if (is_string($entry)) {
123
                $entry = $store->parseVal($entry);
124
            }
125
        }
126
127
        $props = $this->widgetMetadata()['properties'];
128
129
        // We need to sort form properties by form group property order if a group exists
130
        if (!empty($group)) {
131
            $props = array_merge(array_flip($group), $props);
132
        }
133
134
        $out = [];
135
136
        foreach ($props as $propertyIdent => $propertyMetadata) {
137
            if (!is_array($propertyMetadata)) {
138
                throw new \UnexpectedValueException(sprintf(
139
                    'Invalid property data for "%1$s", received %2$s',
140
                    $propertyIdent,
141
                    (is_object($propertyMetadata) ? get_class($propertyMetadata) : gettype($propertyMetadata))
142
                ));
143
            }
144
145
            if ($store) {
146
                $propertyMetadata['input_name'] = sprintf(
147
                    $propertyIdentPattern,
148
                    $store['input_name'] ?: $store->ident(),
149
                    $propertyIdent
150
                );
151
            }
152
153
            if (!empty($entry) && isset($entry[$propertyIdent])) {
154
                $val = $entry[$propertyIdent];
155
156
                $propertyMetadata['property_val'] = $val;
157
            }
158
159
            $formProperty = $this->form()->getOrCreateFormProperty($propertyIdent, $propertyMetadata);
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Charcoal\Ui\Form\FormInterface as the method getOrCreateFormProperty() does only exist in the following implementations of said interface: Charcoal\Admin\Widget\DocWidget, Charcoal\Admin\Widget\FormWidget, Charcoal\Admin\Widget\ObjectFormWidget, Charcoal\Admin\Widget\QuickFormWidget.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
160
161
            if (!$formProperty->hidden()) {
162
                $out[$propertyIdent] = $formProperty;
163
            }
164
        }
165
166
        return $out;
167
    }
168
169
    /**
170
     * So that the formTrait can access the current From widget.
171
     *
172
     * @return FormInterface|self
173
     */
174
    protected function formWidget()
175
    {
176
        if (!key_exists(self::DATA_SOURCE_METADATA, array_flip($this->dataSources()))) {
177
            return $this->form();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this->form(); (Charcoal\Ui\Form\FormInterface) is incompatible with the return type of the parent method Charcoal\Admin\Widget\MultiGroupWidget::formWidget of type Charcoal\Ui\Form\FormTrait.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
178
        }
179
180
        return $this;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $this; (Charcoal\Admin\Widget\Fo...oup\MultiGroupFormGroup) is incompatible with the return type of the parent method Charcoal\Admin\Widget\MultiGroupWidget::formWidget of type Charcoal\Ui\Form\FormTrait.

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

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

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
181
    }
182
}
183