InstructionsGuesser   A
last analyzed

Complexity

Total Complexity 24

Size/Duplication

Total Lines 116
Duplicated Lines 100 %

Coupling/Cohesion

Components 0
Dependencies 4

Importance

Changes 0
Metric Value
dl 116
loc 116
rs 10
c 0
b 0
f 0
wmc 24
lcom 0
cbo 4

1 Method

Rating   Name   Duplication   Size   Complexity  
D guess() 107 107 24

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

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 InstructionsGuesser
9
 *
10
 * @link   http://pyrocms.com/
11
 * @author PyroCMS, Inc. <[email protected]>
12
 * @author Ryan Thompson <[email protected]>
13
 */
14 View Code Duplication
class InstructionsGuesser
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 instructions.
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 instructions are already set then use it.
32
             */
33
            if (isset($field['instructions'])) {
34
                if (str_is('*::*', $field['instructions'])) {
35
                    $field['instructions'] = trans($field['instructions'], [], 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
             * instructions system as generated verbatim.
71
             */
72
            $instructions = $assignment->getInstructions() . '.default';
73
74
            if (!isset($field['instructions']) && str_is('*::*', $instructions) && 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
                    $instructions,
76
                    $locale
77
                )
78
            ) {
79
                $field['instructions'] = trans($instructions, [], null, $locale);
80
            }
81
82
            /*
83
             * Next try using the default assignment
84
             * instructions system as generated verbatim.
85
             */
86
            $instructions = $assignment->getInstructions();
87
88
            if (
89
                !isset($field['instructions'])
90
                && str_is('*::*', $instructions)
91
                && trans()->has($instructions, $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($instructions, [], null, $locale))
93
            ) {
94
                $field['instructions'] = $translated;
95
            }
96
97
            /*
98
             * Check if it's just a standard string.
99
             */
100
            if (!isset($field['instructions']) && $instructions && !str_is('*::*', $instructions)) {
101
                $field['instructions'] = $instructions;
102
            }
103
104
            /*
105
             * Next try using the default field
106
             * instructions system as generated verbatim.
107
             */
108
            $instructions = $object->getInstructions();
109
110
            if (
111
                !isset($field['instructions'])
112
                && str_is('*::*', $instructions)
113
                && trans()->has($instructions, $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($instructions, [], null, $locale))
115
            ) {
116
                $field['instructions'] = $translated;
117
            }
118
119
            /*
120
             * Check if it's just a standard string.
121
             */
122
            if (!isset($field['instructions']) && $instructions && !str_is('*::*', $instructions)) {
123
                $field['instructions'] = $instructions;
124
            }
125
        }
126
127
        $builder->setFields($fields);
128
    }
129
}
130