Completed
Push — trunk ( 91a948...0e7a2e )
by SuperNova.WS
05:44
created

debug::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 0
dl 0
loc 3
ccs 0
cts 3
cp 0
crap 2
rs 10
c 0
b 0
f 0
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 31 and the first side effect is on line 28.

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
 * debug.php ::  Clase Debug, maneja reporte de eventos
4
 *
5
 * V4.0 copyright 2010-2011 by Gorlum for http://supernova.ws
6
 *  [!] Merged `errors` to `logs`
7
 *  [+] Now debugger can work with database detached. All messages would be dumped to page
8
 *  [+] Now `logs` has both human-readable and machine-readable fields
9
 *
10
 * V3.0 copyright 2010 by Gorlum for http://supernova.ws
11
 *  [+] Full rewrtie & optimize
12
 *  [*] Now there is fallback procedure if no link to db detected
13
 *
14
 * V2.0 copyright 2010 by Gorlum for http://supernova.ws
15
 *  [*] Now error also contains backtrace - to see exact way problem comes
16
 *  [*] New method 'warning' sends message to dedicated SQL-table for non-errors
17
 *
18
 * V1.0 Created by Perberos. All rights reversed (C) 2006
19
 *
20
 *  Experiment code!!!
21
 *
22
 * vamos a experimentar >:)
23
 * le veo futuro a las classes, ayudaria mucho a tener un codigo mas ordenado...
24
 * que esperabas!!! soy newbie!!! D':<
25
*/
26
27
if(!defined('INSIDE')) {
28
  die("attemp hacking");
29
}
30
31
class debug {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
32
  var $log, $numqueries;
0 ignored issues
show
Coding Style introduced by
It is generally advisable to only define one property per statement.

Only declaring a single property per statement allows you to later on add doc comments more easily.

It is also recommended by PSR2, so it is a common style that many people expect.

Loading history...
Coding Style introduced by
The visibility should be declared for property $log.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

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

Loading history...
33
  var $log_array;
0 ignored issues
show
Coding Style introduced by
The visibility should be declared for property $log_array.

The PSR-2 coding standard requires that all properties in a class have their visibility explicitly declared. If you declare a property using

class A {
    var $property;
}

the property is implicitly global.

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

Loading history...
34
35
  private $log_file_handler = null;
36
37
  function log_file($message, $ident_change = 0) {
38
    static $ident = 0;
39
40
    if(!defined('SN_DEBUG_LOG')) {
41
      return;
42
    }
43
44
    if($this->log_file_handler === null) {
45
      $this->log_file_handler = @fopen(SN_ROOT_PHYSICAL . '/.logs/supernova.log', 'a+');
46
      @fwrite($this->log_file_handler, "\r\n\r\n");
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition for fwrite(). This can introduce security issues, and is generally not recommended. ( Ignorable by Annotation )

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

46
      /** @scrutinizer ignore-unhandled */ @fwrite($this->log_file_handler, "\r\n\r\n");

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
Bug introduced by
It seems like $this->log_file_handler can also be of type false; however, parameter $handle of fwrite() does only seem to accept resource, maybe add an additional type check? ( Ignorable by Annotation )

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

46
      @fwrite(/** @scrutinizer ignore-type */ $this->log_file_handler, "\r\n\r\n");
Loading history...
47
    }
48
    $ident_change < 0 ? $ident += $ident_change * 2 : false;
49
    if($this->log_file_handler) {
50
      @fwrite($this->log_file_handler, date(FMT_DATE_TIME_SQL, time()) . str_repeat(' ', $ident + 1) . $message . "\r\n");
51
    }
52
    $ident_change > 0 ? $ident += $ident_change * 2 : false;
53
  }
54
55
  public function __construct() {
56
    $this->vars = $this->log = '';
0 ignored issues
show
Bug Best Practice introduced by
The property vars does not exist. Although not strictly required by PHP, it is generally a best practice to declare properties explicitly.
Loading history...
57
    $this->numqueries = 0;
58
  }
59
60
  function add($mes) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
61
    $this->log .= $mes;
62
    $this->numqueries++;
63
  }
64
65
  function add_to_array($mes) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
66
    $this->log_array[] = $mes;
67
  }
68
69
  function echo_log() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
70
    echo '<br><table><tr><td class=k colspan=4><a href="' . SN_ROOT_PHYSICAL . "admin/settings.php\">Debug Log</a>:</td></tr>{$this->log}</table>";
71
    die();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
72
  }
73
74
  function compact_backtrace($backtrace, $long_comment = false) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
75
    static $exclude_functions = array(
76
//      'doquery',
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
77
//      'db_query_select', 'db_query_delete', 'db_query_insert', 'db_query_update',
78
//      'db_get_record_list', 'db_user_by_id', 'db_get_user_by_id'
79
    );
80
81
    $result = array();
82
    $transaction_id = SN::db_transaction_check(false) ? SN::$transaction_id : SN::$transaction_id++;
83
    $result[] = "tID {$transaction_id}";
84
    foreach($backtrace as $a_trace) {
85
      if(in_array($a_trace['function'], $exclude_functions)) {
86
        continue;
87
      }
88
      $function =
89
        (!empty($a_trace['type'])
90
          ? ($a_trace['type'] == '->'
91
            ? "({$a_trace['class']})" . get_class($a_trace['object'])
92
            : $a_trace['class']
93
          ) . $a_trace['type']
94
          : ''
95
        ) . $a_trace['function'] . '()';
96
97
      $file = str_replace(SN_ROOT_PHYSICAL, '', str_replace('\\', '/', !empty($a_trace['file']) ? $a_trace['file'] : ''));
98
99
      $line = !empty($a_trace['line']) ? $a_trace['line'] : '_UNDEFINED_';
100
      $result[] = "{$function} - '{$file}' Line {$line}";
101
102
      if(!$long_comment) {
103
        break;
104
      }
105
    }
106
107
    return $result;
108
  }
109
110
  function dump($dump = false, $force_base = false, $deadlock = false) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
111
    if($dump === false) {
112
      return;
113
    }
114
115
    $error_backtrace = array();
116
    $base_dump = false;
117
118
    if($force_base === true) {
119
      $base_dump = true;
120
    }
121
122
    if($dump === true) {
123
      $base_dump = true;
124
    } else {
125
      if(!is_array($dump)) {
126
        $dump = array('var' => $dump);
127
      }
128
129
      foreach($dump as $dump_var_name => $dump_var) {
130
        if($dump_var_name == 'base_dump') {
131
          $base_dump = $dump_var;
132
        } else {
133
          $error_backtrace[$dump_var_name] = $dump_var;
134
        }
135
      }
136
    }
137
138
    if($deadlock && ($q = db_fetch(SN::$db->mysql_get_innodb_status()))) {
0 ignored issues
show
Bug introduced by
SN::db->mysql_get_innodb_status() cannot be passed to db_fetch() as the parameter $query expects a reference. ( Ignorable by Annotation )

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

138
    if($deadlock && ($q = db_fetch(/** @scrutinizer ignore-type */ SN::$db->mysql_get_innodb_status()))) {
Loading history...
139
      $error_backtrace['deadlock'] = explode("\n", $q['Status']);
140
      $error_backtrace['locks'] = _SnCacheInternal::$locks;
141
      $error_backtrace['cSN_data'] = _SnCacheInternal::$data;
142
      foreach($error_backtrace['cSN_data'] as &$location) {
143
        foreach($location as $location_id => &$location_data) //          $location_data = $location_id;
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% 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...
144
        {
145
          $location_data = isset($location_data['username']) ? $location_data['username'] :
146
            (isset($location_data['name']) ? $location_data['name'] : $location_id);
147
        }
148
      }
149
    }
150
151
    if($base_dump) {
152
      if(!is_array($this->log_array) || empty($this->log_array)) {
153
        $this->log_array = [];
154
      } else {
155
        foreach($this->log_array as $log) {
156
          $error_backtrace['queries'][] = $log;
157
        }
158
      }
159
160
      $error_backtrace['backtrace'] = debug_backtrace();
161
      unset($error_backtrace['backtrace'][1]);
162
      unset($error_backtrace['backtrace'][0]);
163
164
      // Converting object instances to object names
165
166
      foreach ($error_backtrace['backtrace'] as &$backtrace) {
167
        if(is_object($backtrace['object'])) {
168
          $backtrace['object'] = get_class($backtrace['object']);
169
        }
170
171
        if(empty($backtrace['args'])) {
172
          continue;
173
        }
174
175
        // Doing same conversion for backtrace params
176
        foreach($backtrace['args'] as &$arg) {
177
          if(is_object($arg)) {
178
            $arg = 'object::' . get_class($arg);
179
          }
180
        }
181
      }
182
183
      // $error_backtrace['query_log'] = "\r\n\r\nQuery log\r\n<table><tr><th>Number</th><th>Query</th><th>Page</th><th>Table</th><th>Rows</th></tr>{$this->log}</table>\r\n";
0 ignored issues
show
Unused Code Comprehensibility introduced by
60% 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...
184
      $error_backtrace['$_GET'] = $_GET;
185
      $error_backtrace['$_POST'] = $_POST;
186
      $error_backtrace['$_REQUEST'] = $_REQUEST;
187
      $error_backtrace['$_COOKIE'] = $_COOKIE;
188
      $error_backtrace['$_SESSION'] = $_SESSION;
189
      $error_backtrace['$_SERVER'] = $_SERVER;
190
      global $user, $planetrow;
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...
191
      $error_backtrace['user'] = $user;
192
      $error_backtrace['planetrow'] = $planetrow;
193
    }
194
195
    return $error_backtrace;
196
  }
197
198
  function error_fatal($die_message, $details = 'There is a fatal error on page') {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Unused Code introduced by
The parameter $details 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

198
  function error_fatal($die_message, /** @scrutinizer ignore-unused */ $details = 'There is a fatal error on page') {

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...
199
    // TODO - Записывать детали ошибки в лог-файл
200
    die($die_message);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
201
  }
202
203
  function error($message = 'There is a error on page', $title = 'Internal Error', $error_code = 500, $dump = true) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
204
    global $config, $sys_stop_log_hit, $lang, $sys_log_disabled, $user;
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...
205
206
    if(empty(SN::$db->connected)) {
207
      // TODO - писать ошибку в файл
208
      die('SQL server currently unavailable. Please contact Administration...');
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
209
    }
210
211
    sn_db_transaction_rollback();
212
213
    if(SN::$config->debug == 1) {
0 ignored issues
show
Bug Best Practice introduced by
The property debug does not exist on classConfig. Since you implemented __get, consider adding a @property annotation.
Loading history...
214
      echo "<h2>{$title}</h2><br><font color=red>" . htmlspecialchars($message) . "</font><br><hr>";
215
      echo "<table>{$this->log}</table>";
216
    }
217
218
    $fatal_error = 'Fatal error: cannot write to `logs` table. Please contact Administration...';
219
220
    $error_text = db_escape($message);
221
    $error_backtrace = $this->dump($dump, true, strpos($message, 'Deadlock') !== false);
222
223
    if(!$sys_log_disabled) {
224
      $query = "INSERT INTO `{{logs}}` SET
225
        `log_time` = '" . time() . "', `log_code` = '" . db_escape($error_code) . "', `log_sender` = '" . ($user['id'] ? db_escape($user['id']) : 0) . "',
226
        `log_username` = '" . db_escape($user['user_name']) . "', `log_title` = '" . db_escape($title) . "',  `log_text` = '" . db_escape($message) . "',
227
        `log_page` = '" . db_escape(strpos($_SERVER['SCRIPT_NAME'], SN_ROOT_RELATIVE) === false ? $_SERVER['SCRIPT_NAME'] : substr($_SERVER['SCRIPT_NAME'], strlen(SN_ROOT_RELATIVE))) . "'" .
228
        ", `log_dump` = '" . ($error_backtrace ? db_escape(serialize($error_backtrace)) : '') . "'" . ";";
229
      doquery($query, '', false, true) or die($fatal_error . db_error());
0 ignored issues
show
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...
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
230
231
      $message = "Пожалуйста, свяжитесь с админом, если ошибка повторится. Ошибка №: <b>" . db_insert_id() . "</b>";
232
233
      $sys_stop_log_hit = true;
234
      $sys_log_disabled = true;
235
      !function_exists('messageBox') ? die($message) : messageBox($message, 'Ошибка', '', 0, false);
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
236
    } else {
237
//        // TODO Здесь надо писать в файло
238
      ob_start();
239
      print("<hr>User ID {$user['id']} raised error code {$error_code} titled '{$title}' with text '{$error_text}' on page {$_SERVER['SCRIPT_NAME']}");
240
241
      foreach($error_backtrace as $name => $value) {
242
        print('<hr>');
243
        pdump($value, $name);
244
      }
245
      ob_end_flush();
246
      die();
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
247
    }
248
  }
249
250
  function warning($message, $title = 'System Message', $log_code = 300, $dump = false) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
251
    global $user, $lang, $sys_log_disabled;
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...
252
253
    if(empty(SN::$db->connected)) {
254
      // TODO - писать ошибку в файл
255
      die('SQL server currently unavailable. Please contact Administration...');
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
256
    }
257
258
    $error_backtrace = $this->dump($dump, false);
259
260
    if(!$sys_log_disabled) {
261
      $query = "INSERT INTO `{{logs}}` SET
262
        `log_time` = '" . time() . "', `log_code` = '" . db_escape($log_code) . "', `log_sender` = '" . ($user['id'] ? db_escape($user['id']) : 0) . "',
263
        `log_username` = '" . db_escape($user['user_name']) . "', `log_title` = '" . db_escape($title) . "',  `log_text` = '" . db_escape($message) . "',
264
        `log_page` = '" . db_escape(strpos($_SERVER['SCRIPT_NAME'], SN_ROOT_RELATIVE) === false ? $_SERVER['SCRIPT_NAME'] : substr($_SERVER['SCRIPT_NAME'], strlen(SN_ROOT_RELATIVE))) . "'" .
265
        ", `log_dump` = '" . ($error_backtrace ? db_escape(serialize($error_backtrace)) : '') . "'" . ";";
266
      doquery($query, '', false, true);
267
    } else {
268
//        // TODO Здесь надо писать в файло
269
      print("<hr>User ID {$user['id']} made log entry with code {$log_code} titled '{$title}' with text '{$message}' on page {$_SERVER['SCRIPT_NAME']}");
270
    }
271
  }
272
}
273
274
// Copyright (c) 2009-2010 Gorlum for http://supernova.ws
275
// Dump variables nicer then var_dump()
276
277
function dump($value, $varname = null, $level = 0, $dumper = '') {
278
  if(isset($varname)) {
279
    $varname .= " = ";
280
  }
281
282
  if($level == -1) {
283
    $trans[' '] = '&there4;';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$trans was never initialized. Although not strictly required by PHP, it is generally a good practice to add $trans = array(); before regardless.
Loading history...
284
    $trans["\t"] = '&rArr;';
285
    $trans["\n"] = '&para;;';
286
    $trans["\r"] = '&lArr;';
287
    $trans["\0"] = '&oplus;';
288
289
    return strtr(htmlspecialchars($value), $trans);
290
  }
291
  if($level == 0) {
292
//    $dumper = '<pre>' . mt_rand(10, 99) . '|' . $varname;
0 ignored issues
show
Unused Code Comprehensibility introduced by
40% 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...
293
    $dumper = mt_rand(10, 99) . '|' . $varname;
294
  }
295
296
  $type = gettype($value);
297
  $dumper .= $type;
298
299
  if($type == 'string') {
300
    $dumper .= '(' . strlen($value) . ')';
301
    $value = dump($value, '', -1);
302
  } elseif($type == 'boolean') {
303
    $value = ($value ? 'true' : 'false');
304
  } elseif($type == 'object') {
305
    $props = get_class_vars(get_class($value));
306
    $dumper .= '(' . count($props) . ') <u>' . get_class($value) . '</u>';
307
    foreach($props as $key => $val) {
308
      $dumper .= "\n" . str_repeat("\t", $level + 1) . $key . ' => ';
309
      $dumper .= dump($value->$key, '', $level + 1);
310
    }
311
    $value = '';
312
  } elseif($type == 'array') {
313
    $dumper .= '(' . count($value) . ')';
314
    foreach($value as $key => $val) {
315
      $dumper .= "\n" . str_repeat("\t", $level + 1) . dump($key, '', -1) . ' => ';
316
      $dumper .= dump($val, '', $level + 1);
317
    }
318
    $value = '';
319
  }
320
  $dumper .= " <b>$value</b>";
321
//  if($level == 0) {
0 ignored issues
show
Unused Code Comprehensibility introduced by
44% 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...
322
//    $dumper .= '</pre>';
323
//  }
324
325
  return $dumper;
326
}
327
328
function pdump($value, $varname = null) {
329
  $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
330
//  print_rr($backtrace);
0 ignored issues
show
Unused Code Comprehensibility introduced by
59% 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...
331
//  $backtrace = $backtrace[1];
332
333
  $caller = '';
334
  if(defined('SN_DEBUG_PDUMP_CALLER') && SN_DEBUG_PDUMP_CALLER) {
0 ignored issues
show
Bug introduced by
The constant SN_DEBUG_PDUMP_CALLER was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
335
    $caller = (!empty($backtrace[1]['class']) ? $backtrace[1]['class'] : '') .
336
      (!empty($backtrace[1]['type']) ? $backtrace[1]['type'] : '') .
337
      $backtrace[1]['function'] .
338
      (!empty($backtrace[0]['file'])
339
        ? (
340
          ' (' . substr($backtrace[0]['file'], SN_ROOT_PHYSICAL_STR_LEN) .
341
          (!empty($backtrace[0]['line']) ? ':' . $backtrace[0]['line'] : '') .
342
          ')'
343
        )
344
        : ''
345
      );
346
    $caller = "\r\n" . $caller;
347
  }
348
349
  print('<pre style="text-align: left; background-color: #111111; color: #0A0; font-family: Courier, monospace !important; padding: 1em 0; font-weight: 800; font-size: 14px;">' .
350
    dump($value, $varname) .
351
    $caller .
352
    '</pre>'
353
  );
354
}
355
356
function debug($value, $varname = null) {
357
  pdump($value, $varname);
358
}
359
360
function pr($prePrint = false) {
361
  if($prePrint) {
362
    print("<br>");
363
  }
364
  print(mt_rand() . "<br>");
365
}
366
367
function pc($prePrint = false) {
368
  global $_PRINT_COUNT_VALUE;
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...
369
  $_PRINT_COUNT_VALUE++;
370
371
  if($prePrint) {
372
    print("<br>");
373
  }
374
  print($_PRINT_COUNT_VALUE . "<br>");
375
}
376
377
function prep($message) {
378
  print('<pre>' . $message . '</pre>');
379
}
380
381
function backtrace_no_arg() {
382
  $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
383
  array_shift($trace);
384
  return $trace;
385
}