Completed
Push — master ( 171474...8d265e )
by Michael
01:31
created

RandomquoteUtility::checkVerXoops()   D

Complexity

Conditions 9
Paths 40

Size

Total Lines 39
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
eloc 27
nc 40
nop 2
dl 0
loc 39
rs 4.909
c 0
b 0
f 0

1 Method

Rating   Name   Duplication   Size   Complexity  
B Utility::selectSorting() 0 30 4
1
<?php namespace Xoopsmodules\randomquote;
2
3
/*
4
 You may not change or alter any portion of this comment or credits
5
 of supporting developers from this source code or any supporting source code
6
 which is considered copyrighted (c) material of the original comment or credit authors.
7
8
 This program is distributed in the hope that it will be useful,
9
 but WITHOUT ANY WARRANTY; without even the implied warranty of
10
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
11
*/
12
/**
13
 * Module: randomquote
14
 *
15
 * @category        Module
16
 * @package         randomquote
17
 * @author          XOOPS Development Team <[email protected]> - <https://xoops.org>
18
 * @copyright       {@link https://xoops.org/ XOOPS Project}
19
 * @license         GPL 2.0 or later
20
 * @link            https://xoops.org/
21
 * @since           1.0.0
22
 */
23
24
use Xmf\Request;
25
use Xoopsmodules\randomquote;
26
use Xoopsmodules\randomquote\common;
27
28
/**
29
 * Class Utility
30
 */
31
class Utility
32
{
33
34
    use common\VersionChecks; //checkVerXoops, checkVerPhp Traits
35
36
    use common\ServerStats; // getServerStats Trait
37
38
    use common\FilesManagement; // Files Management Trait
39
40
    //--------------- Custom module methods -----------------------------
41
42
    /**
43
     * @param $text
44
     * @param $form_sort
45
     * @return string
46
     */
47
    public static function selectSorting($text, $form_sort)
48
    {
49
        global $start, $order, $file_cat, $sort, $xoopsModule;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
50
51
        $select_view   = '';
0 ignored issues
show
Unused Code introduced by
$select_view 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...
52
        $moduleDirName = basename(dirname(__DIR__));
53
54
        //        if (false !== ($helper = Xmf\Module\Helper::getHelper($moduleDirName))) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
55% 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...
55
        //        } else {
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
56
        //            $helper = Xmf\Module\Helper::getHelper('system');
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% 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...
57
        //        }
58
        $helper = randomquote\Helper::getInstance();
59
60
        $pathModIcon16 = XOOPS_URL . '/modules/' . $moduleDirName . '/' . $helper->getModule()->getInfo('modicons16');
61
62
        $select_view = '<form name="form_switch" id="form_switch" action="' . Request::getString('REQUEST_URI', '', 'SERVER') . '" method="post"><span style="font-weight: bold;">' . $text . '</span>';
63
        //$sorts =  $sort ==  'asc' ? 'desc' : 'asc';
0 ignored issues
show
Unused Code Comprehensibility introduced by
45% 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...
64
        if ($form_sort == $sort) {
65
            $sel1 = 'asc' === $order ? 'selasc.png' : 'asc.png';
66
            $sel2 = 'desc' === $order ? 'seldesc.png' : 'desc.png';
67
        } else {
68
            $sel1 = 'asc.png';
69
            $sel2 = 'desc.png';
70
        }
71
        $select_view .= '  <a href="' . Request::getString('PHP_SELF', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=asc" /><img src="' . $pathModIcon16 . '/' . $sel1 . '" title="ASC" alt="ASC"></a>';
72
        $select_view .= '<a href="' . Request::getString('PHP_SELF', '', 'SERVER') . '?start=' . $start . '&sort=' . $form_sort . '&order=desc" /><img src="' . $pathModIcon16 . '/' . $sel2 . '" title="DESC" alt="DESC"></a>';
73
        $select_view .= '</form>';
74
75
        return $select_view;
76
    }
77
78
    /***************Blocks***************/
79
    /**
80
     * @param array $cats
81
     * @return string
82
     */
83
    public static function block_addCatSelect($cats)
84
    {
85
        $cat_sql = '';
86
        if (is_array($cats)) {
87
            $cat_sql = '(' . current($cats);
88
            array_shift($cats);
89
            foreach ($cats as $cat) {
90
                $cat_sql .= ',' . $cat;
91
            }
92
            $cat_sql .= ')';
93
        }
94
95
        return $cat_sql;
96
    }
97
98
    /**
99
     * @param $content
100
     */
101 View Code Duplication
    public static function meta_keywords($content)
0 ignored issues
show
Duplication introduced by
This method 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...
102
    {
103
        global $xoopsTpl, $xoTheme;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
104
        $myts    = \MyTextSanitizer::getInstance();
105
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
106
        if (null !== $xoTheme && is_object($xoTheme)) {
107
            $xoTheme->addMeta('meta', 'keywords', strip_tags($content));
108
        } else {    // Compatibility for old Xoops versions
109
            $xoopsTpl->assign('xoops_meta_keywords', strip_tags($content));
110
        }
111
    }
112
113
    /**
114
     * @param $content
115
     */
116 View Code Duplication
    public static function meta_description($content)
0 ignored issues
show
Duplication introduced by
This method 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...
117
    {
118
        global $xoopsTpl, $xoTheme;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
119
        $myts    = \MyTextSanitizer::getInstance();
120
        $content = $myts->undoHtmlSpecialChars($myts->displayTarea($content));
121
        if (null !== $xoTheme && is_object($xoTheme)) {
122
            $xoTheme->addMeta('meta', 'description', strip_tags($content));
123
        } else {    // Compatibility for old Xoops versions
124
            $xoopsTpl->assign('xoops_meta_description', strip_tags($content));
125
        }
126
    }
127
128
    /**
129
     * @param $tableName
130
     * @param $columnName
131
     *
132
     * @return array
0 ignored issues
show
Documentation introduced by
Should the return type not be null|array?

This check compares the return type specified in the @return annotation of a function or method doc comment with the types returned by the function and raises an issue if they mismatch.

Loading history...
133
     */
134
    public static function enumerate($tableName, $columnName)
0 ignored issues
show
Coding Style introduced by
enumerate uses the super-global variable $GLOBALS 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...
135
    {
136
        $table = $GLOBALS['xoopsDB']->prefix($tableName);
137
138
        //    $result = $GLOBALS['xoopsDB']->query("SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS
139
        //        WHERE TABLE_NAME = '" . $table . "' AND COLUMN_NAME = '" . $columnName . "'")
140
        //    || exit ($GLOBALS['xoopsDB']->error());
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% 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...
141
142
        $sql    = 'SELECT COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = "' . $table . '" AND COLUMN_NAME = "' . $columnName . '"';
143
        $result = $GLOBALS['xoopsDB']->query($sql);
144
        if (!$result) {
145
            exit ($GLOBALS['xoopsDB']->error());
0 ignored issues
show
Coding Style Compatibility introduced by
The method enumerate() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
146
        }
147
148
        $row      = $GLOBALS['xoopsDB']->fetchBoth($result);
149
        $enumList = explode(',', str_replace("'", '', substr($row['COLUMN_TYPE'], 5, -6)));
150
        return $enumList;
151
    }
152
153
    /**
154
     * @param array|string $tableName
155
     * @param int          $id_field
156
     * @param int          $id
157
     *
158
     * @return mixed
159
     */
160
    public static function cloneRecord($tableName, $id_field, $id)
0 ignored issues
show
Coding Style introduced by
cloneRecord uses the super-global variable $GLOBALS 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...
161
    {
162
        $new_id = false;
163
        $table  = $GLOBALS['xoopsDB']->prefix($tableName);
164
        // copy content of the record you wish to clone 
165
        $tempTable = $GLOBALS['xoopsDB']->fetchArray($GLOBALS['xoopsDB']->query("SELECT * FROM $table WHERE $id_field='$id' "), MYSQLI_ASSOC) or exit('Could not select record');
0 ignored issues
show
Coding Style Compatibility introduced by
The method cloneRecord() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
166
        // set the auto-incremented id's value to blank.
167
        unset($tempTable[$id_field]);
168
        // insert cloned copy of the original  record 
169
        $result = $GLOBALS['xoopsDB']->queryF("INSERT INTO $table (" . implode(', ', array_keys($tempTable)) . ") VALUES ('" . implode("', '", array_values($tempTable)) . "')") or exit ($GLOBALS['xoopsDB']->error());
0 ignored issues
show
Coding Style Compatibility introduced by
The method cloneRecord() contains an exit expression.

An exit expression should only be used in rare cases. For example, if you write a short command line script.

In most cases however, using an exit expression makes the code untestable and often causes incompatibilities with other libraries. Thus, unless you are absolutely sure it is required here, we recommend to refactor your code to avoid its usage.

Loading history...
Comprehensibility Best Practice introduced by
Using logical operators such as or instead of || is generally not recommended.

PHP has two types of connecting operators (logical operators, and boolean operators):

  Logical Operators Boolean Operator
AND - meaning and &&
OR - meaning or ||

The difference between these is the order in which they are executed. In most cases, you would want to use a boolean operator like &&, or ||.

Let’s take a look at a few examples:

// Logical operators have lower precedence:
$f = false or true;

// is executed like this:
($f = false) or true;


// Boolean operators have higher precedence:
$f = false || true;

// is executed like this:
$f = (false || true);

Logical Operators are used for Control-Flow

One case where you explicitly want to use logical operators is for control-flow such as this:

$x === 5
    or die('$x must be 5.');

// Instead of
if ($x !== 5) {
    die('$x must be 5.');
}

Since die introduces problems of its own, f.e. it makes our code hardly testable, and prevents any kind of more sophisticated error handling; you probably do not want to use this in real-world code. Unfortunately, logical operators cannot be combined with throw at this point:

// The following is currently a parse error.
$x === 5
    or throw new RuntimeException('$x must be 5.');

These limitations lead to logical operators rarely being of use in current PHP code.

Loading history...
170
171
        if ($result) {
172
            // Return the new id
173
            $new_id = $GLOBALS['xoopsDB']->getInsertId();
174
        }
175
        return $new_id;
176
    }
177
178
    /**
179
     * truncateHtml can truncate a string up to a number of characters while preserving whole words and HTML tags
180
     * www.gsdesign.ro/blog/cut-html-string-without-breaking-the-tags
181
     * www.cakephp.org
182
     *
183
     * @param string  $text         String to truncate.
184
     * @param integer $length       Length of returned string, including ellipsis.
185
     * @param string  $ending       Ending to be appended to the trimmed string.
186
     * @param boolean $exact        If false, $text will not be cut mid-word
187
     * @param boolean $considerHtml If true, HTML tags would be handled correctly
188
     *
189
     * @return string Trimmed string.
190
     */
191
    public static function truncateHtml($text, $length = 100, $ending = '...', $exact = false, $considerHtml = true)
192
    {
193
        if ($considerHtml) {
194
            // if the plain text is shorter than the maximum length, return the whole text
195
            if (strlen(preg_replace('/<.*?' . '>/', '', $text)) <= $length) {
196
                return $text;
197
            }
198
            // splits all html-tags to scanable lines
199
            preg_match_all('/(<.+?' . '>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
200
            $total_length = strlen($ending);
201
            $open_tags    = [];
202
            $truncate     = '';
203
            foreach ($lines as $line_matchings) {
0 ignored issues
show
Bug introduced by
The expression $lines of type null|array<integer,array<integer,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...
204
                // if there is any html-tag in this line, handle it and add it (uncounted) to the output
205
                if (!empty($line_matchings[1])) {
206
                    // if it's an "empty element" with or without xhtml-conform closing slash
207
                    if (preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $line_matchings[1])) {
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
208
                        // do nothing
209
                        // if tag is a closing tag
210
                    } elseif (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $line_matchings[1], $tag_matchings)) {
211
                        // delete tag from $open_tags list
212
                        $pos = array_search($tag_matchings[1], $open_tags);
213
                        if (false !== $pos) {
214
                            unset($open_tags[$pos]);
215
                        }
216
                        // if tag is an opening tag
217
                    } elseif (preg_match('/^<\s*([^\s>!]+).*?' . '>$/s', $line_matchings[1], $tag_matchings)) {
218
                        // add tag to the beginning of $open_tags list
219
                        array_unshift($open_tags, strtolower($tag_matchings[1]));
220
                    }
221
                    // add html-tag to $truncate'd text
222
                    $truncate .= $line_matchings[1];
223
                }
224
                // calculate the length of the plain text part of the line; handle entities as one character
225
                $content_length = strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', ' ', $line_matchings[2]));
226
                if ($total_length + $content_length > $length) {
227
                    // the number of characters which are left
228
                    $left            = $length - $total_length;
229
                    $entities_length = 0;
230
                    // search for html entities
231
                    if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|[0-9a-f]{1,6};/i', $line_matchings[2], $entities, PREG_OFFSET_CAPTURE)) {
232
                        // calculate the real length of all entities in the legal range
233
                        foreach ($entities[0] as $entity) {
234
                            if ($entity[1] + 1 - $entities_length <= $left) {
235
                                $left--;
236
                                $entities_length += strlen($entity[0]);
237
                            } else {
238
                                // no more characters left
239
                                break;
240
                            }
241
                        }
242
                    }
243
                    $truncate .= substr($line_matchings[2], 0, $left + $entities_length);
244
                    // maximum lenght is reached, so get off the loop
245
                    break;
246
                } else {
247
                    $truncate     .= $line_matchings[2];
248
                    $total_length += $content_length;
249
                }
250
                // if the maximum length is reached, get off the loop
251
                if ($total_length >= $length) {
252
                    break;
253
                }
254
            }
255
        } else {
256
            if (strlen($text) <= $length) {
257
                return $text;
258
            } else {
259
                $truncate = substr($text, 0, $length - strlen($ending));
260
            }
261
        }
262
        // if the words shouldn't be cut in the middle...
263
        if (!$exact) {
264
            // ...search the last occurance of a space...
265
            $spacepos = strrpos($truncate, ' ');
266
            if (isset($spacepos)) {
267
                // ...and cut the text in this position
268
                $truncate = substr($truncate, 0, $spacepos);
269
            }
270
        }
271
        // add the defined ending to the text
272
        $truncate .= $ending;
273
        if ($considerHtml) {
274
            // close all unclosed html-tags
275
            foreach ($open_tags as $tag) {
0 ignored issues
show
Bug introduced by
The variable $open_tags 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...
276
                $truncate .= '</' . $tag . '>';
277
            }
278
        }
279
280
        return $truncate;
281
    }
282
}
283