WarningsGuesser::guess()   D
last analyzed

Complexity

Conditions 27
Paths 39

Size

Total Lines 109
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 27
eloc 42
nc 39
nop 1
dl 0
loc 109
rs 4.509
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\Ui\Form\FormBuilder;
4
5
/**
6
 * Class WarningsGuesser
7
 *
8
 * @link   http://pyrocms.com/
9
 * @author PyroCMS, Inc. <[email protected]>
10
 * @author Ryan Thompson <[email protected]>
11
 */
12
class WarningsGuesser
13
{
14
15
    /**
16
     * Guess the field warnings.
17
     *
18
     * @param FormBuilder $builder
19
     */
20
    public function guess(FormBuilder $builder)
21
    {
22
        $fields = $builder->getFields();
23
        $stream = $builder->getFormStream();
24
25
        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...
26
            $locale = array_get($field, 'locale');
27
28
            /*
29
             * If the warning is already set then use it.
30
             */
31
            if (isset($field['warning'])) {
32
                if (str_is('*::*', $field['warning'])) {
33
                    $field['warning'] = trans($field['warning'], [], null, $locale);
34
                }
35
36
                continue;
37
            }
38
39
            /*
40
             * If we don't have a field then we
41
             * can not really guess anything here.
42
             */
43
            if (!isset($field['field'])) {
44
                continue;
45
            }
46
47
            /*
48
             * No stream means we can't
49
             * really do much here.
50
             */
51
            if (!$stream || !$stream->getAssignment($field['field'])) {
52
                $warning = "module::field.{$field['field']}.warning";
53
54
                if (str_is('*::*', $warning) && trans()->has($warning)) {
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...
55
                    $field['warning'] = trans($warning, [], null, $locale);
56
                }
57
58
                continue;
59
            }
60
61
            $assignment = $stream->getAssignment($field['field']);
62
            $object     = $stream->getField($field['field']);
63
64
            /*
65
             * No assignment means we still do
66
             * not have anything to do here.
67
             */
68
            if (!$assignment) {
69
                continue;
70
            }
71
72
            /*
73
             * Next try using the fallback assignment
74
             * warning system as generated verbatim.
75
             */
76
            $warning = $assignment->getWarning() . '.default';
77
78
            if (!isset($field['warning']) && str_is('*::*', $warning) && trans()->has($warning, $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...
79
                $field['warning'] = trans($warning, [], null, $locale);
80
            }
81
82
            /*
83
             * Next try using the default assignment
84
             * warning system as generated verbatim.
85
             */
86
            $warning = $assignment->getWarning();
87
88
            if (
89
                !isset($field['warning'])
90
                && str_is('*::*', $warning)
91
                && trans()->has($warning, $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($warning, [], null, $locale))
93
            ) {
94
                $field['warning'] = $translated;
95
            }
96
97
            /*
98
             * Check if it's just a standard string.
99
             */
100
            if (!isset($field['warning']) && $warning && !str_is('*::*', $warning)) {
101
                $field['warning'] = $warning;
102
            }
103
104
            /*
105
             * Next try using the default field
106
             * warning system as generated verbatim.
107
             */
108
            $warning = $object->getWarning();
109
110
            if (
111
                !isset($field['warning'])
112
                && str_is('*::*', $warning)
113
                && trans()->has($warning, $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($warning, [], null, $locale))
115
            ) {
116
                $field['warning'] = $translated;
117
            }
118
119
            /*
120
             * Check if it's just a standard string.
121
             */
122
            if (!isset($field['warning']) && $warning && !str_is('*::*', $warning)) {
123
                $field['warning'] = $warning;
124
            }
125
        }
126
127
        $builder->setFields($fields);
128
    }
129
}
130