Passed
Push — master ( da394c...44937f )
by Michael
05:20
created

Utility::truncateHtml()   F

Complexity

Conditions 19
Paths 194

Size

Total Lines 89
Code Lines 47

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 19
eloc 47
nc 194
nop 5
dl 0
loc 89
rs 3.7333
c 0
b 0
f 0

4 Methods

Rating   Name   Duplication   Size   Complexity  
A Utility::getWysiwygForm() 0 21 2
A Utility::redirect() 0 3 1
A Utility::javascriptLinkConfirm() 0 6 2
A Utility::getModule() 0 14 5

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
2
3
namespace XoopsModules\Marquee;
4
5
use XoopsModules\Marquee\{Common,
6
    Constants,
0 ignored issues
show
Bug introduced by
The type XoopsModules\Marquee\Constants was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
7
    Helper
0 ignored issues
show
Bug introduced by
This use statement conflicts with another class in this namespace, XoopsModules\Marquee\Helper. Consider defining an alias.

Let?s assume that you have a directory layout like this:

.
|-- OtherDir
|   |-- Bar.php
|   `-- Foo.php
`-- SomeDir
    `-- Foo.php

and let?s assume the following content of Bar.php:

// Bar.php
namespace OtherDir;

use SomeDir\Foo; // This now conflicts the class OtherDir\Foo

If both files OtherDir/Foo.php and SomeDir/Foo.php are loaded in the same runtime, you will see a PHP error such as the following:

PHP Fatal error:  Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.php

However, as OtherDir/Foo.php does not necessarily have to be loaded and the error is only triggered if it is loaded before OtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias:

// Bar.php
namespace OtherDir;

use SomeDir\Foo as SomeDirFoo; // There is no conflict anymore.
Loading history...
8
};
9
10
/** @var Helper $helper */
11
12
/**
13
 * Class Utility
14
 */
15
class Utility extends Common\SysUtility
16
{
17
    //--------------- Custom module methods -----------------------------
18
    public const MODULE_NAME = 'marquee';
19
20
    /**
21
     * Access the only instance of this class
22
     *
23
     * @return \XoopsModules\Marquee\Utility
24
     *
25
     * @static
26
     * @staticvar   object
27
     */
28
    public static function getInstance()
29
    {
30
        static $instance;
31
        if (null === $instance) {
32
            $instance = new static();
33
        }
34
        return $instance;
35
    }
36
37
    /**
38
     * Retreive an editor according to the module's option "form_options"
39
     *
40
     * @param string $caption Caption to give to the editor
41
     * @param string $name    Editor's name
42
     * @param string $value   Editor's value
43
     * @param string $width   Editor's width
44
     * @param string $height  Editor's height
45
     * @param string $supplemental
46
     *
47
     * @return \XoopsFormDhtmlTextArea|\XoopsFormEditor The editor to use
48
     */
49
    public static function getWysiwygForm(
50
        $caption,
51
        $name,
52
        $value = '',
53
        $width = '100%',
0 ignored issues
show
Unused Code introduced by
The parameter $width is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

53
        /** @scrutinizer ignore-unused */ $width = '100%',

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
54
        $height = '400px',
0 ignored issues
show
Unused Code introduced by
The parameter $height is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

54
        /** @scrutinizer ignore-unused */ $height = '400px',

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
55
        $supplemental = ''
0 ignored issues
show
Unused Code introduced by
The parameter $supplemental is not used and could be removed. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-unused  annotation

55
        /** @scrutinizer ignore-unused */ $supplemental = ''

This check looks for parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
56
    ) {
57
        $helper = Helper::getInstance();
58
        if (\class_exists('XoopsFormEditor')) {
59
            $options['name']   = $name;
0 ignored issues
show
Comprehensibility Best Practice introduced by
$options was never initialized. Although not strictly required by PHP, it is generally a good practice to add $options = array(); before regardless.
Loading history...
60
            $options['value']  = $value;
61
            $options['rows']   = 35;
62
            $options['cols']   = '100%';
63
            $options['width']  = '100%';
64
            $options['height'] = '400px';
65
            $editor            = new \XoopsFormEditor($caption, $helper->getConfig('form_options'), $options, $nohtml = false, $onfailure = 'textarea');
66
        } else {
67
            $editor = new \XoopsFormDhtmlTextArea($caption, $name, $value, '100%', '100%');
0 ignored issues
show
Bug introduced by
'100%' of type string is incompatible with the type integer expected by parameter $rows of XoopsFormDhtmlTextArea::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

67
            $editor = new \XoopsFormDhtmlTextArea($caption, $name, $value, /** @scrutinizer ignore-type */ '100%', '100%');
Loading history...
Bug introduced by
'100%' of type string is incompatible with the type integer expected by parameter $cols of XoopsFormDhtmlTextArea::__construct(). ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

67
            $editor = new \XoopsFormDhtmlTextArea($caption, $name, $value, '100%', /** @scrutinizer ignore-type */ '100%');
Loading history...
68
        }
69
        return $editor;
70
    }
71
72
    /**
73
     * Create (in a link) a javascript confirmation's box
74
     *
75
     * @param string $message Message to display
76
     * @param bool   $form    Is this a confirmation for a form ?
77
     *
78
     * @return string the javascript code to insert in the link (or in the form)
79
     */
80
    public static function javascriptLinkConfirm($message, $form = false)
81
    {
82
        if (!$form) {
83
            return "onclick=\"javascript:return confirm('" . \str_replace("'", ' ', $message) . "')\"";
84
        }
85
        return "onSubmit=\"javascript:return confirm('" . \str_replace("'", ' ', $message) . "')\"";
86
    }
87
88
    /**
89
     * Redirect user with a message
90
     *
91
     * @param string $message message to display
92
     * @param string $url     The place where to go
93
     * @param mixed  $time
94
     */
95
    public static function redirect($message = '', $url = 'index.php', $time = 2)
96
    {
97
        \redirect_header($url, $time, $message);
98
    }
99
100
    /**
101
     * Internal function used to get the handler of the current module
102
     * @return \XoopsModule The module
103
     * @deprecated  use $helper->getModule();
104
     */
105
    protected static function getModule()
106
    {
107
        $moduleDirName = \basename(\dirname(__DIR__));
108
        static $mymodule;
109
        if (null === $mymodule) {
110
            global $xoopsModule;
111
            if (null !== $xoopsModule && \is_object($xoopsModule) && $moduleDirName == $xoopsModule->getVar('dirname')) {
112
                $mymodule = $xoopsModule;
113
            } else {
114
                $moduleHandler = \xoops_getHandler('module');
115
                $mymodule      = $moduleHandler->getByDirname($moduleDirName);
0 ignored issues
show
Bug introduced by
The method getByDirname() does not exist on XoopsObjectHandler. It seems like you code against a sub-type of XoopsObjectHandler such as XoopsModuleHandler or XoopsPersistableObjectHandler. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

115
                /** @scrutinizer ignore-call */ 
116
                $mymodule      = $moduleHandler->getByDirname($moduleDirName);
Loading history...
116
            }
117
        }
118
        return $mymodule;
119
    }
120
121
    /**
122
     * This function indicates if the current Xoops version needs to add asterisks to required fields in forms
123
     *
124
     * @return bool Yes = we need to add them, false = no
125
     */
126
    public static function needsAsterisk()
127
    {
128
        if (false === mb_stripos(\XOOPS_VERSION, 'legacy')) {
129
            $xv = \xoops_trim(\str_replace('XOOPS ', '', \XOOPS_VERSION));
130
            if ((int)mb_substr($xv, 4, 2) >= 17) {
131
                return false;
132
            }
133
        }
134
        return true;
135
    }
136
137
    /**
138
     * Mark the mandatory fields of a form with a star
139
     *
140
     * @param \XoopsThemeForm $sform The form to modify
141
     *
142
     * @return \XoopsThemeForm The modified form
143
     * @internal param string $caracter The character to use to mark fields
144
     */
145
    public static function formMarkRequiredFields($sform)
146
    {
147
        $required = $elements = [];
0 ignored issues
show
Unused Code introduced by
The assignment to $elements is dead and can be removed.
Loading history...
148
        if (self::needsAsterisk()) {
149
            foreach ($sform->getRequired() as $item) {
150
                $required[] = $item->_name;
151
            }
152
            $elements = &$sform->getElements();
153
            foreach ($elements as $i => $iValue) {
154
                if (\is_object($elements[$i]) && \in_array($iValue->_name, $required)) {
155
                    $iValue->_caption .= ' *';
156
                }
157
            }
158
        }
159
        return $sform;
160
    }
161
162
    /**
163
     * @param        $option
164
     * @param string $repmodule
165
     * @return bool
166
     */
167
    public static function getModuleOption($option, $repmodule = 'marquee')
168
    {
169
        global $xoopsModule;
170
        $helper = Helper::getInstance();
171
        static $tbloptions = [];
172
        if (\is_array($tbloptions) && \array_key_exists($option, $tbloptions)) {
173
            return $tbloptions[$option];
174
        }
175
        $retval = false;
176
        if (null !== $helper->getModule()
177
            && (\is_object($xoopsModule) && $xoopsModule->getVar('dirname') == $repmodule
178
                && $xoopsModule->getVar('isactive'))) {
179
            if ('' !== $helper->getConfig($option)) {
180
                $retval = $helper->getConfig($option);
181
            }
182
        } else {
183
            /** @var \XoopsModuleHandler $moduleHandler */
184
            $moduleHandler = \xoops_getHandler('module');
185
            $module        = $moduleHandler->getByDirname($repmodule);
186
            /** @var \XoopsConfigHandler $configHandler */
187
            $configHandler = \xoops_getHandler('config');
188
            if ($module) {
189
                $moduleConfig = $configHandler->getConfigsByCat(0, $module->getVar('mid'));
190
                if (isset($moduleConfig[$option])) {
191
                    $retval = $moduleConfig[$option];
192
                }
193
            }
194
        }
195
        $tbloptions[$option] = $retval;
196
        return $retval;
197
    }
198
199
    /**
200
     * Verify if the current "user" is a bot or not
201
     *
202
     * If you have a problem with this function, insert the folowing code just before the line if (\Xmf\Request::hasVar('news_cache_bot', 'SESSION'))) { :
203
     * return false;
204
     *
205
     * @package          Marquee
206
     * @author           Hervé Thouzard (http://www.herve-thouzard.com)
207
     * @copyright    (c) Hervé Thouzard
208
     */
209
    public static function isBot()
210
    {
211
        if (\Xmf\Request::hasVar('marquee_cache_bot', 'SESSION')) {
212
            return $_SESSION['marquee_cache_bot'];
213
        }
214
        // Add here every bot you know separated by a pipe | (not matter with the upper or lower cases)
215
        // If you want to see the result for yourself, add your navigator's user agent at the end (mozilla for example)
216
        $botlist      = 'AbachoBOT|Arachnoidea|ASPSeek|Atomz|cosmos|crawl25-public.alexa.com|CrawlerBoy Pinpoint.com|Crawler|DeepIndex|EchO!|exabot|Excalibur Internet Spider|FAST-WebCrawler|Fluffy the spider|GAIS Robot/1.0B2|GaisLab data gatherer|Google|Googlebot-Image|googlebot|Gulliver|ia_archiver|Infoseek|Links2Go|Lycos_Spider_(modspider)|Lycos_Spider_(T-Rex)|MantraAgent|Mata Hari|Mercator|MicrosoftPrototypeCrawler|[email protected]|MSNBOT|NEC Research Agent|NetMechanic|Nokia-WAPToolkit|nttdirectory_robot|Openfind|Oracle Ultra Search|PicoSearch|Pompos|Scooter|Slider_Search_v1-de|Slurp|Slurp.so|SlySearch|Spider|Spinne|SurferF3|Surfnomore Spider|suzuran|teomaagent1|TurnitinBot|Ultraseek|VoilaBot|vspider|W3C_Validator|Web Link Validator|WebTrends|WebZIP|whatUseek_winona|WISEbot|Xenu Link Sleuth|ZyBorg';
217
        $botlist      = mb_strtoupper($botlist);
218
        $currentagent = mb_strtoupper(\xoops_getenv('HTTP_USER_AGENT'));
219
        $retval       = false;
220
        $botarray     = \explode('|', $botlist);
221
        foreach ($botarray as $onebot) {
222
            if (str_contains($currentagent, $onebot)) {
0 ignored issues
show
Bug introduced by
The function str_contains was not found. Maybe you did not declare it correctly or list all dependencies? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

222
            if (/** @scrutinizer ignore-call */ str_contains($currentagent, $onebot)) {
Loading history...
223
                $retval = true;
224
                break;
225
            }
226
        }
227
        $_SESSION['marquee_cache_bot'] = $retval;
228
        return $retval;
229
    }
230
231
    /**
232
     * Escape a string so that it can be included in a javascript string
233
     *
234
     * @param $string
235
     *
236
     * @return mixed
237
     */
238
    public static function javascriptEscape($string)
239
    {
240
        return \str_replace("'", "\\'", $string);
241
    }
242
}
243