StringWidget   A
last analyzed

Complexity

Total Complexity 25

Size/Duplication

Total Lines 196
Duplicated Lines 8.67 %

Coupling/Cohesion

Components 1
Dependencies 7

Importance

Changes 4
Bugs 0 Features 0
Metric Value
dl 17
loc 196
rs 10
c 4
b 0
f 0
wmc 25
lcom 1
cbo 7

5 Methods

Rating   Name   Duplication   Size   Complexity  
B getEditHtml() 0 32 3
B getMultipleEditHtml() 7 55 5
B getMultipleValueReadonly() 7 25 5
D generateRow() 3 32 9
B showFilterHtml() 0 28 3

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
0 ignored issues
show
Coding Style Compatibility introduced by
For compatibility and reusability of your code, PSR1 recommends that a file should introduce either new symbols (like classes, functions, etc.) or have side-effects (like outputting something, or including other files), but not both at the same time. The first symbol is defined on line 34 and the first side effect is on line 10.

The PSR-1: Basic Coding Standard recommends that a file should either introduce new symbols, that is classes, functions, constants or similar, or have side effects. Side effects are anything that executes logic, like for example printing output, changing ini settings or writing to a file.

The idea behind this recommendation is that merely auto-loading a class should not change the state of an application. It also promotes a cleaner style of programming and makes your code less prone to errors, because the logic is not spread out all over the place.

To learn more about the PSR-1, please see the PHP-FIG site on the PSR-1.

Loading history...
2
3
namespace DigitalWand\AdminHelper\Widget;
4
5
use Bitrix\Main\Localization\Loc;
6
use DigitalWand\AdminHelper\Helper\AdminEditHelper;
7
use DigitalWand\AdminHelper\Helper\AdminListHelper;
8
use DigitalWand\AdminHelper\Helper\AdminSectionListHelper;
9
10
Loc::loadMessages(__FILE__);
11
12
/**
13
 * Виджет строки с текстом.
14
 *
15
 * Доступные опции:
16
 * <ul>
17
 * <li> <b>EDIT_LINK</b> - отображать в виде ссылки на редактирование элемента </li>
18
 * <li> <b>STYLE</b> - inline-стили для input </li>
19
 * <li> <b>SIZE</b> - значение атрибута size для input </li>
20
 * <li> <b>TRANSLIT</b> - true, если поле будет транслитерироваться в символьный код</li>
21
 * <li> <b>MULTIPLE</b> - поддерживается множественный ввод. В таблице требуется наличие поля VALUE</li>
22
 * </ul>
23
 */
24
class StringWidget extends HelperWidget
0 ignored issues
show
Bug introduced by
Possible parse error: class missing opening or closing brace
Loading history...
25
{
26
    static protected $defaults = array(
27
        'FILTER' => '%', //Фильтрация по подстроке, а не по точному соответствию.
28
        'EDIT_IN_LIST' => true
29
    );
30
31
    /**
32
     * @inheritdoc
33
     */
34
    protected function getEditHtml()
35
    {
36
        $style = $this->getSettings('STYLE');
37
        $size = $this->getSettings('SIZE');
38
39
        $link = '';
40
41
        if ($this->getSettings('TRANSLIT')) {
42
43
            //TODO: refactor this!
44
            $uniqId = get_class($this->entityName) . '_' . $this->getCode();
45
            $nameId = 'name_link_' . $uniqId;
46
            $linkedFunctionName = 'set_linked_' . get_class($this->entityName) . '_CODE';//FIXME: hardcode here!!!
0 ignored issues
show
Unused Code Comprehensibility introduced by
38% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
47
48
            if (isset($this->entityName->{$this->entityName->pk()})) {
0 ignored issues
show
Bug introduced by
The method pk() does not seem to exist on object<Bitrix\Main\Entity\DataManager>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
49
                $pkVal = $this->entityName->{$this->entityName->pk()};
0 ignored issues
show
Bug introduced by
The method pk() does not seem to exist on object<Bitrix\Main\Entity\DataManager>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
50
            } else {
51
                $pkVal = '_new_';
52
            }
53
54
            $nameId .= $pkVal;
55
            $linkedFunctionName .= $pkVal;
56
57
            $link = '<image id="' . $nameId . '" title="' . Loc::getMessage("IBSEC_E_LINK_TIP") . '" class="linked" src="/bitrix/themes/.default/icons/iblock/link.gif" onclick="' . $linkedFunctionName . '()" />';
58
        }
59
60
        return '<input type="text"
61
                       name="' . $this->getEditInputName() . '"
62
                       value="' . static::prepareToTagAttr($this->getValue()) . '"
63
                       size="' . $size . '"
64
                       style="' . $style . '"/>' . $link;
65
    }
66
67
    protected function getMultipleEditHtml()
68
    {
69
        $style = $this->getSettings('STYLE');
70
        $size = $this->getSettings('SIZE');
71
        $uniqueId = $this->getEditInputHtmlId();
72
73
        $rsEntityData = null;
74
75 View Code Duplication
        if (!empty($this->data['ID'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
76
            $entityName = $this->entityName;
77
            $rsEntityData = $entityName::getList(array(
78
                'select' => array('REFERENCE_' => $this->getCode() . '.*'),
79
                'filter' => array('=ID' => $this->data['ID'])
80
            ));
81
        }
82
83
        ob_start();
84
        ?>
85
86
        <div id="<?= $uniqueId ?>-field-container" class="<?= $uniqueId ?>">
87
        </div>
88
89
        <script>
90
            var multiple = new MultipleWidgetHelper(
91
                '#<?= $uniqueId ?>-field-container',
92
                '{{field_original_id}}<input type="text" name="<?= $this->getCode()?>[{{field_id}}][<?=$this->getMultipleField('VALUE')?>]" style="<?=$style?>" size="<?=$size?>" value="{{value}}">'
93
            );
94
            <?
0 ignored issues
show
Security Best Practice introduced by
It is not recommend to use PHP's short opening tag <?, better use <?php, or <?= in case of outputting.

Short opening tags are disabled in PHP’s default configuration. In such a case, all content of this file is output verbatim to the browser without being parsed, or executed.

As a precaution to avoid these problems better use the long opening tag <?php.

Loading history...
95
            if ($rsEntityData)
96
            {
97
                while($referenceData = $rsEntityData->fetch())
98
                {
99
                    if (empty($referenceData['REFERENCE_' . $this->getMultipleField('ID')]))
100
                    {
101
                        continue;
102
                    }
103
104
                    ?>
105
            multiple.addField({
106
                value: '<?= static::prepareToJs($referenceData['REFERENCE_' . $this->getMultipleField('VALUE')]) ?>',
107
                field_original_id: '<input type="hidden" name="<?= $this->getCode()?>[{{field_id}}][<?= $this->getMultipleField('ID') ?>]"' +
108
                ' value="<?= $referenceData['REFERENCE_' . $this->getMultipleField('ID')] ?>">',
109
                field_id: <?= $referenceData['REFERENCE_' . $this->getMultipleField('ID')] ?>
110
            });
111
            <?
112
                           }
113
                       }
114
                       ?>
115
116
            // TODO Добавление созданных полей
117
            multiple.addField();
118
        </script>
119
        <?
120
        return ob_get_clean();
121
    }
122
123
    protected function getMultipleValueReadonly()
124
    {
125
        $rsEntityData = null;
126 View Code Duplication
        if (!empty($this->data['ID'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
127
            $entityName = $this->entityName;
128
            $rsEntityData = $entityName::getList(array(
129
                'select' => array('REFERENCE_' => $this->getCode() . '.*'),
130
                'filter' => array('=ID' => $this->data['ID'])
131
            ));
132
        }
133
134
        $result = '';
135
        if ($rsEntityData) {
136
            while ($referenceData = $rsEntityData->fetch()) {
137
                if (empty($referenceData['REFERENCE_VALUE'])) {
138
                    continue;
139
                }
140
141
                $result .= '<div class="wrap_text" style="margin-bottom: 5px">' .
142
                    static::prepareToOutput($referenceData['REFERENCE_VALUE']) . '</div>';
143
            }
144
        }
145
146
        return $result;
147
    }
148
149
    /**
150
     * Генерирует HTML для поля в списке
151
     * @see AdminListHelper::addRowCell();
152
     * @param \CAdminListRow $row
153
     * @param array $data - данные текущей строки
154
     */
155
    public function generateRow(&$row, $data)
0 ignored issues
show
Coding Style introduced by
generateRow uses the super-global variable $_GET which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

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

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
156
    {
157
        if ($this->getSettings('MULTIPLE')) {
158
        } else {
159
            if ($this->getSettings('EDIT_LINK') || $this->getSettings('SECTION_LINK')) {
160
                $pk = $this->helper->pk();
161
162
                if ($this->getSettings('SECTION_LINK')) {
163
                    $params = $this->helper->isPopup() ? $_GET : array();
0 ignored issues
show
Bug introduced by
The method isPopup does only exist in DigitalWand\AdminHelper\Helper\AdminListHelper, but not in DigitalWand\AdminHelper\...\Helper\AdminEditHelper.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
164
                    $params['ID'] = $this->data[$pk];
165
                    $listHelper = $this->helper->getHelperClass($this->helper->isPopup() ? AdminSectionListHelper::className() : AdminListHelper::className());
166
                    $pageUrl = $listHelper::getUrl($params);
167
                    $value = '<span class="adm-submenu-item-link-icon adm-list-table-icon iblock-section-icon"></span>';
168
                } else {
169
                    $editHelper = $this->helper->getHelperClass(AdminEditHelper::className());
170
                    $pageUrl = $editHelper::getUrl(array(
171
                        'ID' => $this->data[$pk]
172
                    ));
173
                }
174
175
                $value .= '<a href="' . $pageUrl . '">' . static::prepareToOutput($this->getValue()) . '</a>';
0 ignored issues
show
Bug introduced by
The variable $value does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
176
            } else {
177
                $value = static::prepareToOutput($this->getValue());
178
            }
179
180 View Code Duplication
            if ($this->getSettings('EDIT_IN_LIST') AND !$this->getSettings('READONLY')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
181
                $row->AddInputField($this->getCode(), array('style' => 'width:90%'));
182
            }
183
184
            $row->AddViewField($this->getCode(), $value);
185
        }
186
    }
187
188
    /**
189
     * @inheritdoc
190
     */
191
    public function showFilterHtml()
192
    {
193
        if ($this->getSettings('MULTIPLE')) {
194
        } else {
195
            print '<tr>';
196
            print '<td>' . $this->getSettings('TITLE') . '</td>';
197
198
            if ($this->isFilterBetween()) {
199
                list($from, $to) = $this->getFilterInputName();
200
                print '<td>
201
            <div class="adm-filter-box-sizing">
202
                <span style="display: inline-block; left: 11px; top: 5px; position: relative;">От:</span>
203
                <div class="adm-input-wrap" style="display: inline-block">
204
                    <input type="text" class="adm-input" name="' . $from . '" value="' . $$from . '">
205
                </div>
206
                <span style="display: inline-block; left: 11px; top: 5px; position: relative;">До:</span>
207
                <div class="adm-input-wrap" style="display: inline-block">
208
                    <input type="text" class="adm-input" name="' . $to . '" value="' . $$to . '">
209
                </div>
210
            </div>
211
            </td> ';
212
            } else {
213
                print '<td><input type="text" name="' . $this->getFilterInputName() . '" size="47" value="' . $this->getCurrentFilterValue() . '"></td>';
214
            }
215
216
            print '</tr>';
217
        }
218
    }
219
}