PlaceholdersGuesser::guess()   D
last analyzed

Complexity

Conditions 24
Paths 38

Size

Total Lines 107
Code Lines 41

Duplication

Lines 107
Ratio 100 %

Importance

Changes 0
Metric Value
cc 24
eloc 41
nc 38
nop 1
dl 107
loc 107
rs 4.5989
c 0
b 0
f 0

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 namespace Anomaly\Streams\Platform\Ui\Form\Component\Field\Guesser;
2
3
use Anomaly\Streams\Platform\Assignment\Contract\AssignmentInterface;
4
use Anomaly\Streams\Platform\Stream\Contract\StreamInterface;
5
use Anomaly\Streams\Platform\Ui\Form\FormBuilder;
6
7
/**
8
 * Class PlaceholdersGuesser
9
 *
10
 * @link   http://pyrocms.com/
11
 * @author PyroCMS, Inc. <[email protected]>
12
 * @author Ryan Thompson <[email protected]>
13
 */
14 View Code Duplication
class PlaceholdersGuesser
0 ignored issues
show
Duplication introduced by
This class 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...
15
{
16
17
    /**
18
     * Guess the field placeholders.
19
     *
20
     * @param FormBuilder $builder
21
     */
22
    public function guess(FormBuilder $builder)
23
    {
24
        $fields = $builder->getFields();
25
        $stream = $builder->getFormStream();
26
27
        foreach ($fields as &$field) {
0 ignored issues
show
Bug introduced by
The expression $fields of type array|string is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
28
            $locale = array_get($field, 'locale');
29
30
            /*
31
             * If the placeholder are already set then use it.
32
             */
33
            if (isset($field['placeholder'])) {
34
                if (str_is('*::*', $field['placeholder'])) {
35
                    $field['placeholder'] = trans($field['placeholder'], [], null, $locale);
36
                }
37
38
                continue;
39
            }
40
41
            /*
42
             * If we don't have a field then we
43
             * can not really guess anything here.
44
             */
45
            if (!isset($field['field'])) {
46
                continue;
47
            }
48
49
            /*
50
             * No stream means we can't
51
             * really do much here.
52
             */
53
            if (!$stream instanceof StreamInterface) {
54
                continue;
55
            }
56
57
            $assignment = $stream->getAssignment($field['field']);
58
            $object     = $stream->getField($field['field']);
59
60
            /*
61
             * No assignment means we still do
62
             * not have anything to do here.
63
             */
64
            if (!$assignment instanceof AssignmentInterface) {
65
                continue;
66
            }
67
68
            /*
69
             * Next try using the fallback assignment
70
             * placeholder system as generated verbatim.
71
             */
72
            $placeholder = $assignment->getPlaceholder() . '.default';
73
74
            if (!isset($field['placeholder']) && str_is('*::*', $placeholder) && trans()->has(
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Translation\TranslatorInterface as the method has() does only exist in the following implementations of said interface: Illuminate\Translation\Translator.

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...
75
                    $placeholder,
76
                    $locale
77
                )
78
            ) {
79
                $field['placeholder'] = trans($placeholder, [], null, $locale);
80
            }
81
82
            /*
83
             * Next try using the default assignment
84
             * placeholder system as generated verbatim.
85
             */
86
            $placeholder = $assignment->getPlaceholder();
87
88
            if (
89
                !isset($field['placeholder'])
90
                && str_is('*::*', $placeholder)
91
                && trans()->has($placeholder, $locale)
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Translation\TranslatorInterface as the method has() does only exist in the following implementations of said interface: Illuminate\Translation\Translator.

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
                && is_string($translated = trans($placeholder, [], null, $locale))
93
            ) {
94
                $field['placeholder'] = $translated;
95
            }
96
97
            /*
98
             * Check if it's just a standard string.
99
             */
100
            if (!isset($field['placeholder']) && $placeholder && !str_is('*::*', $placeholder)) {
101
                $field['placeholder'] = $placeholder;
102
            }
103
104
            /*
105
             * Next try using the default field
106
             * placeholder system as generated verbatim.
107
             */
108
            $placeholder = $object->getPlaceholder();
109
110
            if (
111
                !isset($field['placeholder'])
112
                && str_is('*::*', $placeholder)
113
                && trans()->has($placeholder, $locale)
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Translation\TranslatorInterface as the method has() does only exist in the following implementations of said interface: Illuminate\Translation\Translator.

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...
114
                && is_string($translated = trans($placeholder, [], null, $locale))
115
            ) {
116
                $field['placeholder'] = $translated;
117
            }
118
119
            /*
120
             * Check if it's just a standard string.
121
             */
122
            if (!isset($field['placeholder']) && $placeholder && !str_is('*::*', $placeholder)) {
123
                $field['placeholder'] = $placeholder;
124
            }
125
        }
126
127
        $builder->setFields($fields);
128
    }
129
}
130