GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( 951ad1...29ba67 )
by Alexey
08:55
created

Utils::finishRequest()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 0
loc 11
ccs 0
cts 9
cp 0
rs 9.4285
cc 3
eloc 5
nc 3
nop 0
crap 12
1
<?php
2
/**
3
 * @author Sergey Glagolev <[email protected]>
4
 * @link https://github.com/shogodev/argilla/
5
 * @copyright Copyright &copy; 2003-2014 Shogo
6
 * @license http://argilla.ru/LICENSE
7
 * @package frontend.share.helpers
8
 */
9
class Utils
10
{
11
  public static function pre()
12
  {
13
    if( PHP_SAPI !== 'cli' )
14
    {
15
      echo '<div style="padding: 5px;margin: 5px;border: 1px solid #333333;background-color: #DFEEFF;color: #000000" id="debug">';
16
      echo '<pre>';
17
    }
18
19
    foreach( func_get_args() as $data )
20
      if( is_array($data) || is_object($data) )
21
        print_r($data);
22
      else
23
        var_dump($data);
0 ignored issues
show
Security Debugging Code introduced by
var_dump($data); looks like debug code. Are you sure you do not want to remove it? This might expose sensitive data.
Loading history...
24
25
    if( PHP_SAPI !== 'cli' )
26
    {
27
      echo '</pre>';
28
      echo "</div>";
29
    }
30
  }
31
32
  /**
33
   * @param string $str
34
   * @param bool $methodFormat
35
   *
36
   * @return string
37
   */
38 18
  public static function toCamelCase($str, $methodFormat = false)
39
  {
40 18
    $arr  = explode("_", $str);
41 18
    $name = array_shift($arr);
42
43 18
    if( !$methodFormat )
44 18
      $name = ucfirst($name);
45
46 18
    if( count($arr) )
47 18
      foreach($arr as $value)
48
        $name .= ucfirst($value);
49
50 18
    return $name;
51
  }
52
53
  /**
54
   * @param string $class
55
   * @return string
56
   */
57 145
  public static function toSnakeCase($class)
58
  {
59 145
    return strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $class));
60
  }
61
62
  /**
63
   * Обрезаем текст до нужной длины по пробелу
64
   *
65
   * @param $str
66
   * @param integer $n
67
   *
68
   * @return string
69
   */
70
  public static function stripText($str, $n = 150)
71
  {
72
    if( mb_strlen($str, 'UTF-8') > $n )
73
    {
74
      $str = mb_substr($str, 0, $n + 1, 'UTF-8');
75
      $str = mb_substr($str, 0, mb_strrpos($str, " ", 'UTF-8') - $n - 1, 'UTF-8');
76
      $str = trim(trim($str), "., ").'...';
77
    }
78
79
    return $str;
80
  }
81
82
  /**
83
   * @param $date
84
   * @param string $defaultValue
85
   *
86
   * @return string
87
   */
88
  public static function dayBegin($date, $defaultValue = '')
89
  {
90
    return date("Y-m-d 00:00:00", strtotime($date ? $date : $defaultValue));
91
  }
92
93
  /**
94
   * @param $date
95
   * @param string $defaultValue
96
   *
97
   * @return string
98
   */
99
  public static function dayEnd($date, $defaultValue = '31.12.2999')
100
  {
101
    return date("Y-m-d 23:59:59", strtotime($date ? $date : $defaultValue));
102
  }
103
104 15
  public static function translite($text, $urlFormat = true)
105
  {
106
    $trans = array(
107 15
      'а' => 'a', 'б' => 'b', 'в' => 'v', 'г' => 'g', 'д' => 'd', 'е' => 'e', 'ё' => 'jo', 'ж' => 'zh', 'з' => 'z', 'и' => 'i',
108 15
      'й' => 'j', 'к' => 'k', 'л' => 'l', 'м' => 'm', 'н' => 'n', 'о' => 'o', 'п' => 'p', 'р' => 'r', 'с' => 's', 'т' => 't', 'у' => 'u', 'ф' => 'f',
109 15
      'х' => 'x', 'ц' => 'c', 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'th', 'ъ' => '', 'ь' => '', 'ы' => 'y', 'э' => 'e', 'ю' => 'ju', 'я' => 'ya',
110 15
      'А' => 'A', 'Б' => 'B', 'В' => 'V', 'Г' => 'G', 'Д' => 'D', 'Е' => 'E', 'Ё' => 'JO', 'Ж' => 'ZH', 'З' => 'Z', 'И' => 'I',
111 15
      'Й' => 'J', 'К' => 'K', 'Л' => 'L', 'М' => 'M', 'Н' => 'N', 'О' => 'O', 'П' => 'P', 'Р' => 'R', 'С' => 'S', 'Т' => 'T', 'У' => 'U', 'Ф' => 'F',
112 15
      'Х' => 'X', 'Ц' => 'C', 'Ч' => 'CH', 'Ш' => 'SH', 'Щ' => 'TH', 'Ъ' => '', 'Ь' => '', 'Ы' => 'Y', 'Э' => 'E', 'Ю' => 'JU', 'Я' => 'YA', ' ' => '_');
113
114 15
    $newStr = "";
115
116 15
    for($i = 0; $i < mb_strlen($text, 'UTF-8'); $i++)
0 ignored issues
show
Performance Best Practice introduced by
Consider avoiding function calls on each iteration of the for loop.

If you have a function call in the test part of a for loop, this function is executed on each iteration. Often such a function, can be moved to the initialization part and be cached.

// count() is called on each iteration
for ($i=0; $i < count($collection); $i++) { }

// count() is only called once
for ($i=0, $c=count($collection); $i<$c; $i++) { }
Loading history...
117
    {
118 15
      $tmp = mb_substr($text, $i, 1, 'UTF-8');
119
120 15
      if( isset($trans[$tmp]) )
121 15
      {
122 13
        $newStr .= $trans[$tmp];
123 13
      }
124
      else
125
      {
126
        if( $urlFormat )
127 5
          $replaceCondition = preg_match("/[^\w]/", $tmp);
128
        else
129
          $replaceCondition = (ord($tmp) < 32) || (ord($tmp) > 126);
130
131
        if( $replaceCondition )
132 5
          $newStr .= '_';
133
        else
134 5
          $newStr .= $tmp;
135
      }
136 15
    }
137
138 15
    $newStr = preg_replace("/_+/", '_', $newStr);
139
140 15
    return $urlFormat ? mb_strtolower($newStr, 'UTF-8') : $newStr;
141
  }
142
143
  public static function unserialize($string)
144
  {
145
    return unserialize(preg_replace('!s:(\d+):"(.*)";!esmU', "'s:'.strlen('$2').':\"$2\";'", $string));
146
  }
147
148
  /**
149
   * Удаляем из строки запроса набор get параметров
150
   *
151
   * @param       $query
152
   * @param array $params
153
   *
154
   * @return string
155
   */
156 1
  public static function cutQueryParams($query, array $params)
157
  {
158 1
    $url = parse_url($query);
159
160 1
    if( !empty($url['query']) )
161 1
    {
162
      parse_str($url['query'], $query);
163
      foreach($params as $param)
164
        if( isset($query[$param]) )
165
          unset($query[$param]);
166
167
      $url = $url['path'].(!empty($query) ? "?".http_build_query($query) : "");
168
    }
169
    else
170 1
      $url = $url['path'];
171
172 1
    return $url;
173
  }
174
175 32
  public static function buildUrl(array $parts)
176
  {
177 32
    $url  = isset($parts['scheme']) ? $parts['scheme'] . '://' : '';
178 32
    $url .= isset($parts['host']) ? $parts['host'] : '';
179 32
    $url .= isset($parts['user']) ? $parts['user'] . (isset($parts['pass'])) ? ':' . $parts['pass'] : '' .'@' : '';
180 32
    $url .= isset($parts['port']) ? ':' . $parts['port'] : '';
181 32
    $url .= isset($parts['path']) ? $parts['path'] : '';
182 32
    $url .= !empty($parts['query']) ? '?' . (is_array($parts['query']) ? http_build_query($parts['query']) : $parts['query']) : '';
183 32
    $url .= isset($parts['fragment']) ? '#' . $parts['fragment'] : '';
184
185 32
    return $url;
186
  }
187
188
  /**
189
   * Преобразуем ссылку к стандартному формату
190
   *
191
   * @param $url
192
   *
193
   * @return string
194
   */
195 22
  public static function normalizeUrl($url)
196
  {
197 22
    $url = rtrim($url, '/');
198 22
    $url = str_replace('/?', '?', $url);
199
200 22
    $components = parse_url(rtrim($url, '/'));
201
202 22
    if( !isset($components['path']) )
203 22
      $components['path'] = '';
204
205 22
    $components['path'] .= preg_match("/.+\.\w+$/", $components['path']) ? "" : '/';
206 22
    $components['path']  = preg_replace("/\/+/", "/", $components['path']);
207
208 22
    return self::buildUrl($components);
0 ignored issues
show
Security Bug introduced by
It seems like $components defined by parse_url(rtrim($url, '/')) on line 200 can also be of type false; however, Utils::buildUrl() does only seem to accept array, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
209
  }
210
211
  /**
212
   * Преобразуем абсолютную ссылку в относительную
213
   *
214
   * @param string $url
215
   *
216
   * @return string
217
   */
218 1
  public static function getRelativeUrl($url)
219
  {
220 1
    $parts = Arr::extract(parse_url($url), array('path', 'query', 'fragment'));
0 ignored issues
show
Security Bug introduced by
It seems like parse_url($url) targeting parse_url() can also be of type false; however, Arr::extract() does only seem to accept array, did you maybe forget to handle an error condition?
Loading history...
221 1
    $parts['path'] = self::normalizeUrl($parts['path']);
222
223 1
    return self::buildUrl($parts);
224
  }
225
226 2
  public static function generatePassword($length = 8)
227
  {
228 2
    $randKey  = "";
229 2
    $keyChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_";
230 2
    $max      = strlen($keyChars) - 1;
231
232 2
    for($i = 0; $i < $length; $i++)
233 2
      $randKey .= $keyChars{rand(0, $max)};
234
235 2
    return $randKey;
236
  }
237
238
  /**
239
   * Возводит первый символ строки в верхний регистр
240
   * @param $string
241
   * @return string
242
   */
243 19
  public static function ucfirst($string)
244
  {
245 19
    return mb_strlen($string) > 1 ? mb_strtoupper(mb_substr($string, 0, 1)).mb_substr($string, 1) : mb_strtoupper(mb_substr($string, 0, 1));
246
  }
247
248
  /**
249
   * Приводит первый символ строки к нижнему регистру
250
   * @param $string
251
   * @return string
252
   */
253 1
  public static function lcfirst($string)
254
  {
255 1
    return mb_strlen($string) > 1 ? mb_strtolower(mb_substr($string, 0, 1)).mb_substr($string, 1) : mb_strtolower(mb_substr($string, 0, 1));
256
  }
257
258
  /**
259
   * Возвращает домен
260
   * @param integer $level если указан уровень, то домен обрезается до указанного уровня
261
   * @return mixed|string
262
   */
263
  public static function getDomain($level = null)
264
  {
265
    $domain = str_replace('http://', '', Yii::app()->request->getHostInfo());
266
267
    $elements = explode('.', $domain);
268
269
    if( $level === null || count($elements) < $level )
270
      return $domain;
271
272
    return implode('.', array_slice($elements, $level * -1));
273
  }
274
275
  /**
276
   * @param $number
277
   * @param array|string $titles
278
   * @return string
279
   */
280
  public static function plural($number, $titles = array())
281
  {
282
    if( !is_array($titles) )
283
    {
284
      $delimiter = strpos($titles, '|') !== false ? '|' : ',';
285
      $titles = explode($delimiter, $titles);
286
    }
287
288
    return Yii::t('app', implode('|', $titles), $number);
289
  }
290
291
  /**
292
   * @param string $date date in YYYY-MM-DD format
293
   *
294
   * @return bool
295
   */
296
  public static function dateUntil($date)
297
  {
298
    return strtotime('now') < strtotime($date);
299
  }
300
301
  /**
302
   * @param string $dateFrom date in YYYY-MM-DD format
303
   * @param string $dateTo date in YYYY-MM-DD format
304
   *
305
   * @return bool
306
   */
307
  public static function dateBetween($dateFrom, $dateTo)
308
  {
309
    return (strtotime('now') > strtotime($dateFrom)) && (strtotime('now') < strtotime($dateTo));
310
  }
311
312
  /**
313
   * @param CModel $class
314
   *
315
   * @return string
316
   */
317
  public static function modelToSnakeCase(CModel $class)
318
  {
319
    return self::toSnakeCase(get_class($class));
320
  }
321
322
  /**
323
   * Результат сравнения 2-x объектов или массивов
324
   * @param $a
325
   * @param $b
326
   *
327
   * @return bool
328
   */
329
  public static function compareObjects($a, $b)
330
  {
331
    if( (is_array($a) && is_array($b)) || (is_scalar($a) && is_scalar($b)) )
332
      return $a == $b;
333
334
    if( is_object($a) && is_object($b) )
335
      return serialize($a) == serialize($b);
336
337
    return false;
338
  }
339
340
  /**
341
   * Отдает ответ клиенту с продолжением работы скрипта (работает тольео на php-fpm)
342
   */
343
  public static function finishRequest()
344
  {
345
    if( function_exists('fastcgi_finish_request') )
346
    {
347
      session_write_close();
348
      if( !fastcgi_finish_request() )
349
      {
350
        throw new CException('Ошибка вызова fastcgi_finish_request!');
351
      }
352
    }
353
  }
354
355
  /**
356
   * Увеличивает время жизни скрипта
357
   * @param int $timeLimitMinutes
358
   * @param bool $ignoreUserAbort
359
   */
360
  public static function longLife($timeLimitMinutes = 0, $ignoreUserAbort = true)
361
  {
362
    set_time_limit($timeLimitMinutes * 60);
363
    ignore_user_abort($ignoreUserAbort);
364
  }
365
}