LabelsGuesser::guess()   F
last analyzed

Complexity

Conditions 33
Paths 262

Size

Total Lines 142
Code Lines 54

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 33
eloc 54
nc 262
nop 1
dl 0
loc 142
rs 3.425
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\Support\Str;
6
use Anomaly\Streams\Platform\Ui\Form\FormBuilder;
7
use Illuminate\Contracts\Config\Repository;
8
9
/**
10
 * Class LabelsGuesser
11
 *
12
 * @link   http://pyrocms.com/
13
 * @author PyroCMS, Inc. <[email protected]>
14
 * @author Ryan Thompson <[email protected]>
15
 */
16
class LabelsGuesser
17
{
18
19
    /**
20
     * The config repository.
21
     *
22
     * @var Repository
23
     */
24
    protected $config;
25
26
    /**
27
     * The string utility.
28
     *
29
     * @var Str
30
     */
31
    protected $string;
32
33
    /**
34
     * Create a new LabelsGuesser instance.
35
     *
36
     * @param Str        $string
37
     * @param Repository $config
38
     */
39
    public function __construct(Str $string, Repository $config)
40
    {
41
        $this->config = $config;
42
        $this->string = $string;
43
    }
44
45
    /**
46
     * Guess the field labels.
47
     *
48
     * @param FormBuilder $builder
49
     */
50
    public function guess(FormBuilder $builder)
51
    {
52
        $fields = $builder->getFields();
53
        $stream = $builder->getFormStream();
54
55
        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...
56
            $locale = array_get($field, 'locale');
57
58
            /*
59
             * If the label are already set then use it.
60
             */
61
            if (isset($field['label'])) {
62
                if (str_is('*::*', $field['label'])) {
63
                    $field['label'] = trans($field['label'], [], null, $locale);
64
                }
65
66
                continue;
67
            }
68
69
            /*
70
             * If we don't have a field then we
71
             * can not really guess anything here.
72
             */
73
            if (!isset($field['field'])) {
74
                continue;
75
            }
76
77
            /*
78
             * No stream means we can't
79
             * really do much here.
80
             */
81
            if (!$stream instanceof StreamInterface) {
82
                continue;
83
            }
84
85
            $assignment = $stream->getAssignment($field['field']);
86
            $object     = $stream->getField($field['field']);
87
88
            /*
89
             * No assignment means we still do
90
             * not have anything to do here.
91
             */
92
            if (!$assignment instanceof AssignmentInterface) {
93
                continue;
94
            }
95
96
            /*
97
             * Next try using the fallback assignment
98
             * label system as generated verbatim.
99
             */
100
            $label = $assignment->getLabel() . '.default';
101
102
            if (!isset($field['label']) && str_is('*::*', $label) && 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...
103
                    $label,
104
                    $locale
105
                )
106
            ) {
107
                $field['label'] = trans($label, [], null, $locale);
108
            }
109
110
            /*
111
             * Next try using the default assignment
112
             * label system as generated verbatim.
113
             */
114
            $label = $assignment->getLabel();
115
116
            if (
117
                !isset($field['label'])
118
                && str_is('*::*', $label)
119
                && trans()->has($label, $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...
120
                && is_string($translated = trans($label, [], null, $locale))
121
            ) {
122
                $field['label'] = $translated;
123
            }
124
125
            /*
126
             * Check if it's just a standard string.
127
             */
128
            if (!isset($field['label']) && $label && !str_is('*::*', $label)) {
129
                $field['label'] = $label;
130
            }
131
132
            /*
133
             * Next try using the generic assignment
134
             * label system without the stream identifier.
135
             */
136
            $label = explode('.', $assignment->getLabel());
137
138
            array_pop($label);
139
140
            $label = implode('.', $label);
141
142
            if (
143
                !isset($field['label'])
144
                && str_is('*::*', $label)
145
                && trans()->has($label, $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...
146
                && is_string($translated = trans($label, [], null, $locale))
147
            ) {
148
                $field['label'] = $translated;
149
            }
150
151
            /*
152
             * Check if it's just a standard string.
153
             */
154
            if (!isset($field['label']) && $label && !str_is('*::*', $label)) {
155
                $field['label'] = $label;
156
            }
157
158
            /*
159
             * Next try using the default field
160
             * label system as generated verbatim.
161
             */
162
            $label = $object->getName();
163
164
            if (
165
                !isset($field['label'])
166
                && str_is('*::*', $label)
167
                && trans()->has($label, $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...
168
                && is_string($translated = trans($label, [], null, $locale))
169
            ) {
170
                $field['label'] = $translated;
171
            }
172
173
            /*
174
             * Check if it's just a standard string.
175
             */
176
            if (!isset($field['label']) && $label && !str_is('*::*', $label)) {
177
                $field['label'] = $label;
178
            }
179
180
            /*
181
             * If the field is still untranslated and
182
             * we're not debugging then humanize the slug
183
             * in leu of displaying an untranslated key.
184
             */
185
            if (!isset($field['label']) && $this->config->get('streams::system.lazy_translations')) {
186
                $field['label'] = ucwords($this->string->humanize($field['field']));
187
            }
188
        }
189
190
        $builder->setFields($fields);
191
    }
192
}
193