Completed
Push — master ( a45e4d...280ae8 )
by Martin
8s
created

Columns::translate()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 1 Features 1
Metric Value
c 4
b 1
f 1
dl 0
loc 18
rs 9.2
cc 4
eloc 10
nc 4
nop 1
1
<?php
2
namespace ZfcDatagrid\Renderer\JqGrid\View\Helper;
3
4
use Zend\ServiceManager\ServiceLocatorAwareInterface;
5
use Zend\ServiceManager\ServiceLocatorAwareTrait;
6
use Zend\View\Helper\AbstractHelper;
7
use ZfcDatagrid\Column;
8
use ZfcDatagrid\Column\Type;
9
use ZfcDatagrid\Filter;
10
11
/**
12
 * View Helper
13
 */
14
class Columns extends AbstractHelper implements ServiceLocatorAwareInterface
15
{
16
    /** @var  \Zend\I18n\Translator\Translator|null|false */
17
    private $translator;
18
19
    const STYLE_BOLD = 'cellvalue = \'<span style="font-weight: bold;">\' + cellvalue + \'</span>\';';
20
21
    const STYLE_ITALIC = 'cellvalue = \'<span style="font-style: italic;">\' + cellvalue + \'</span>\';';
22
23
    const STYLE_STRIKETHROUGH = 'cellvalue = \'<span style="text-decoration: line-through;">\' + cellvalue + \'</span>\';';
24
25
    use ServiceLocatorAwareTrait;
26
27
    /**
28
     *
29
     * @param  string $message
30
     * @return string
31
     */
32
    private function translate($message)
33
    {
34
        if (false === $this->translator) {
35
            return $message;
36
        }
37
38
        if (null === $this->translator) {
39
            if ($this->getServiceLocator()->has('translator')) {
40
                $this->translator = $this->getServiceLocator()->get('translator');
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->getServiceLocator()->get('translator') can also be of type array. However, the property $translator is declared as type object<Zend\I18n\Transla...\Translator>|null|false. Maybe add an additional type check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a mixed type is assigned to a property that is type hinted more strictly.

For example, imagine you have a variable $accountId that can either hold an Id object or false (if there is no account id yet). Your code now assigns that value to the id property of an instance of the Account class. This class holds a proper account, so the id value must no longer be false.

Either this assignment is in error or a type check should be added for that assignment.

class Id
{
    public $id;

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

}

class Account
{
    /** @var  Id $id */
    public $id;
}

$account_id = false;

if (starsAreRight()) {
    $account_id = new Id(42);
}

$account = new Account();
if ($account instanceof Id)
{
    $account->id = $account_id;
}
Loading history...
41
            } else {
42
                $this->translator = false;
43
44
                return $message;
45
            }
46
        }
47
48
        return $this->translator->translate($message);
49
    }
50
51
    /**
52
     *
53
     * @param  array  $columns
54
     * @return string
55
     */
56
    public function __invoke(array $columns)
57
    {
58
        $return = [];
59
60
        foreach ($columns as $column) {
61
            /* @var $column \ZfcDatagrid\Column\AbstractColumn */
62
63
            $options = [
64
                'name'  => (string) $column->getUniqueId(),
65
                'index' => (string) $column->getUniqueId(),
66
                'label' => $this->translate((string) $column->getLabel()),
67
68
                'width'    => $column->getWidth(),
69
                'hidden'   => (bool) $column->isHidden(),
70
                'sortable' => (bool) $column->isUserSortEnabled(),
71
                'search'   => (bool) $column->isUserFilterEnabled(),
72
            ];
73
74
            /*
75
             * Formatting
76
             */
77
            $formatter = $this->getFormatter($column);
78
            if ($formatter != '') {
79
                $options['formatter'] = (string) $formatter;
80
            }
81
82
            $alignAlreadyDefined = false;
83
            if ($column->hasStyles()) {
84
                foreach ($column->getStyles() as $style) {
85
                    /** @var \ZfcDatagrid\Column\Style\Align $style */
86
                    if (get_class($style) == 'ZfcDatagrid\Column\Style\Align') {
87
                        $options['align']    = $style->getAlignment();
88
                        $alignAlreadyDefined = true;
89
                        break;
90
                    }
91
                }
92
            }
93
94
            if (!$alignAlreadyDefined && $column->getType() instanceof Type\Number) {
95
                $options['align'] = Column\Style\Align::$RIGHT;
96
            }
97
98
            /*
99
             * Cellattr
100
             */
101
            $rendererParameters = $column->getRendererParameters('jqGrid');
102
            if (isset($rendererParameters['cellattr'])) {
103
                $options['cellattr'] = (string) $rendererParameters['cellattr'];
104
            }
105
            if (isset($rendererParameters['classes'])) {
106
                $options['classes'] = (string) $rendererParameters['classes'];
107
            }
108
109
            /*
110
             * Filtering
111
             */
112
            $searchoptions                = [];
113
            $searchoptions['clearSearch'] = false;
114
            if ($column->hasFilterSelectOptions() === true) {
115
                $options['stype']       = 'select';
116
                $searchoptions['value'] = $column->getFilterSelectOptions();
117
118
                if ($column->hasFilterDefaultValue() === true) {
119
                    $searchoptions['defaultValue'] = $column->getFilterDefaultValue();
120
                } else {
121
                    $searchoptions['defaultValue'] = '';
122
                }
123
            } elseif ($column->hasFilterDefaultValue() === true) {
124
                $filter = new \ZfcDatagrid\Filter();
125
                $filter->setFromColumn($column, $column->getFilterDefaultValue());
126
127
                $searchoptions['defaultValue'] = $filter->getDisplayColumnValue();
128
            }
129
130
            if (count($searchoptions) > 0) {
131
                $options['searchoptions'] = $searchoptions;
132
            }
133
134
            /**
135
             * Because with json_encode we get problems, it's custom made!
136
             */
137
            $colModel = [];
138
            foreach ($options as $key => $value) {
139
                if (is_array($value)) {
140
                    $value = json_encode($value);
141
                } elseif (is_bool($value)) {
142
                    if (true === $value) {
143
                        $value = 'true';
144
                    } else {
145
                        $value = 'false';
146
                    }
147
                } elseif ('formatter' == $key) {
148
                    if (stripos($value, 'formatter') === false && stripos($value, 'function') === false) {
149
                        $value = '"' . $value . '"';
150
                    }
151
                } elseif ('cellattr' == $key) {
152
                    // SKIP THIS
153
                } else {
154
                    $value = '"' . $value . '"';
155
                }
156
157
                $colModel[] = (string) $key . ': ' . $value;
158
            }
159
160
            $return[] = '{' . implode(',', $colModel) . '}';
161
        }
162
163
        return '[' . implode(',', $return) . ']';
164
    }
165
166
    /**
167
     *
168
     * @param  Column\AbstractColumn $column
169
     * @return string
170
     */
171
    private function getFormatter(Column\AbstractColumn $column)
172
    {
173
        /*
174
         * User defined formatter
175
         */
176
        $rendererParameters = $column->getRendererParameters('jqGrid');
177
        if (isset($rendererParameters['formatter'])) {
178
            return $rendererParameters['formatter'];
179
        }
180
181
        /*
182
         * Formatter based on column options + styles
183
         */
184
        $formatter = '';
185
186
        $formatter .= implode(' ', $this->getStyles($column));
187
188
        switch (get_class($column->getType())) {
189
190
            case 'ZfcDatagrid\Column\Type\PhpArray':
191
                $formatter .= 'cellvalue = \'<pre>\' + cellvalue.join(\'<br />\') + \'</pre>\';';
192
                break;
193
        }
194
195
        if ($column instanceof Column\Action) {
196
            $formatter .= ' cellvalue = cellvalue; ';
197
        }
198
199
        if ($formatter != '') {
200
            $prefix = 'function (cellvalue, options, rowObject) {';
201
            $suffix = ' return cellvalue; }';
202
203
            $formatter = $prefix . $formatter . $suffix;
204
        }
205
206
        return $formatter;
207
    }
208
209
    /**
210
     *
211
     * @param  Column\AbstractColumn $col
212
     * @throws \Exception
213
     * @return array
214
     */
215
    private function getStyles(Column\AbstractColumn $col)
216
    {
217
        $styleFormatter = [];
218
219
        /*
220
         * First all based on value (only one works) @todo
221
         */
222
        foreach ($col->getStyles() as $style) {
223
            $prepend = '';
224
            $append  = '';
225
226
            /* @var $style \ZfcDatagrid\Column\Style\AbstractStyle */
227
            foreach ($style->getByValues() as $rule) {
228
                $colString = $rule['column']->getUniqueId();
229
                $operator  = '';
0 ignored issues
show
Unused Code introduced by
$operator is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
230
                switch ($rule['operator']) {
231
232
                    case Filter::EQUAL:
233
                        $operator = '==';
234
                        break;
235
236
                    case Filter::NOT_EQUAL:
237
                        $operator = '!=';
238
                        break;
239
240
                    default:
241
                        throw new \Exception('Currently not supported filter operation: "' . $rule['operator'] . '"');
242
                        break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
243
                }
244
245
                $prepend = 'if (rowObject.' . $colString . ' ' . $operator . ' \'' . $rule['value'] . '\') {';
246
                $append .= '}';
247
            }
248
249
            $styleString = '';
250
            switch (get_class($style)) {
251
252
                case 'ZfcDatagrid\Column\Style\Bold':
253
                    $styleString = self::STYLE_BOLD;
254
                    break;
255
256
                case 'ZfcDatagrid\Column\Style\Italic':
257
                    $styleString = self::STYLE_ITALIC;
258
                    break;
259
260
                case 'ZfcDatagrid\Column\Style\Strikethrough':
261
                    $styleString = self::STYLE_STRIKETHROUGH;
262
                    break;
263
264
                case 'ZfcDatagrid\Column\Style\Color':
265
                    $styleString = 'cellvalue = \'<span style="color: #' . $style->getRgbHexString() . ';">\' + cellvalue + \'</span>\';';
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class ZfcDatagrid\Column\Style\AbstractStyle as the method getRgbHexString() does only exist in the following sub-classes of ZfcDatagrid\Column\Style\AbstractStyle: ZfcDatagrid\Column\Style\AbstractColor, ZfcDatagrid\Column\Style\BackgroundColor, ZfcDatagrid\Column\Style\Color. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
266
                    break;
267
268
                case 'ZfcDatagrid\Column\Style\CSSClass':
269
                    $styleString = 'cellvalue = \'<span class="' . $style->getClass() . '">\' + cellvalue + \'</span>\';';
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class ZfcDatagrid\Column\Style\AbstractStyle as the method getClass() does only exist in the following sub-classes of ZfcDatagrid\Column\Style\AbstractStyle: ZfcDatagrid\Column\Style\CSSClass. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

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

class MyUser extends 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 sub-classes 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 parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
270
                    break;
271
272
                case 'ZfcDatagrid\Column\Style\BackgroundColor':
273
                    // do NOTHING! this is done by loadComplete event...
274
                    // At this stage jqgrid haven't created the columns...
275
                    break;
276
277
                case 'ZfcDatagrid\Column\Style\Html':
278
                    // do NOTHING! just pass the HTML!
279
                    break;
280
281
                case 'ZfcDatagrid\Column\Style\Align':
282
                    // do NOTHING! we have to add the align style in the gridcell and not in a span!
283
                    break;
284
285
                default:
286
                    throw new \Exception('Not defined style: "' . get_class($style) . '"');
287
                    break;
0 ignored issues
show
Unused Code introduced by
break; does not seem to be reachable.

This check looks for unreachable code. It uses sophisticated control flow analysis techniques to find statements which will never be executed.

Unreachable code is most often the result of return, die or exit statements that have been added for debug purposes.

function fx() {
    try {
        doSomething();
        return true;
    }
    catch (\Exception $e) {
        return false;
    }

    return false;
}

In the above example, the last return false will never be executed, because a return statement has already been met in every possible execution path.

Loading history...
288
            }
289
290
            $styleFormatter[] = $prepend . $styleString . $append;
291
        }
292
293
        return $styleFormatter;
294
    }
295
}
296