ICanBoogie/Common v1.2.2.1
  • Namespace
  • Class

Namespaces

  • ICanBoogie

Classes

  • FormattedString

Interfaces

  • ToArray
  • ToArrayRecursive

Traits

  • ToArrayRecursiveTrait

Exceptions

  • OffsetError
  • OffsetNotDefined
  • OffsetNotReadable
  • OffsetNotWritable
  • PropertyError
  • PropertyIsReserved
  • PropertyNotDefined
  • PropertyNotReadable
  • PropertyNotWritable

Functions

  • array_flatten
  • array_insert
  • array_merge_recursive
  • capitalize
  • downcase
  • dump
  • escape
  • escape_all
  • exact_array_merge_recursive
  • format
  • generate_v4_uuid
  • normalize
  • normalize_url_path
  • remove_accents
  • shorten
  • sort_by_weight
  • stable_sort
  • unaccent_compare
  • unaccent_compare_ci
  • upcase
  1   2   3   4   5   6   7   8   9  10  11  12  13  14  15  16  17  18  19  20  21  22  23  24  25  26  27  28  29  30  31  32  33  34  35  36  37  38  39  40  41  42  43  44  45  46  47  48  49  50  51  52  53  54  55  56  57  58  59  60  61  62  63  64  65  66  67  68  69  70  71  72  73  74  75  76  77  78  79  80  81  82  83  84  85  86  87  88  89  90  91  92  93  94  95  96  97  98  99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 
<?php

/*
 * This file is part of the ICanBoogie package.
 *
 * (c) Olivier Laviale <olivier.laviale@gmail.com>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace ICanBoogie;

/**
 * Escape HTML special characters.
 *
 * HTML special characters are escaped using the {@link htmlspecialchars()} function with the
 * {@link ENT_COMPAT} flag.
 *
 * @param string $str The string to escape.
 * @param string $charset The charset of the string to escape. Defaults to
 * {@link ICanBoogie\CHARSET} (utf-8).
 *
 * @return string
 */
function escape($str, $charset=CHARSET)
{
    return htmlspecialchars($str, ENT_COMPAT, $charset);
}

/**
 * Escape all applicable characters to HTML entities.
 *
 * Applicable characters are escaped using the {@link htmlentities()} function with the {@link ENT_COMPAT} flag.
 *
 * @param string $str The string to escape.
 * @param string $charset The charset of the string to escape. Defaults to
 * {@link ICanBoogie\CHARSET} (utf-8).
 *
 * @return string
 */
function escape_all($str, $charset=CHARSET)
{
    return htmlentities($str, ENT_COMPAT, $charset);
}

if (!function_exists(__NAMESPACE__ . '\downcase'))
{
    /**
     * Returns a lowercase string.
     *
     * @param string $str
     *
     * @return string
     */
    function downcase($str)
    {
        return mb_strtolower($str);
    }
}

if (!function_exists(__NAMESPACE__ . '\upcase'))
{
    /**
     * Returns an uppercase string.
     *
     * @param string $str
     *
     * @return string
     */
    function upcase($str)
    {
        return mb_strtoupper($str);
    }
}

if (!function_exists(__NAMESPACE__ . '\capitalize'))
{
    /**
     * Returns a copy of str with the first character converted to uppercase and the
     * remainder to lowercase.
     *
     * @param string $str
     */
    function capitalize($str)
    {
        return upcase(mb_substr($str, 0, 1)) . downcase(mb_substr($str, 1));
    }
}

/**
 * Shortens a string at a specified position.
 *
 * @param string $str The string to shorten.
 * @param int $length The desired length of the string.
 * @param float $position Position at which characters can be removed.
 * @param bool $shortened `true` if the string was shortened, `false` otherwise.
 *
 * @return string
 */
function shorten($str, $length=32, $position=.75, &$shortened=null)
{
    $l = mb_strlen($str);

    if ($l <= $length)
    {
        return $str;
    }

    $length--;
    $position = (int) ($position * $length);

    if ($position == 0)
    {
        $str = '…' . mb_substr($str, $l - $length);
    }
    else if ($position == $length)
    {
        $str = mb_substr($str, 0, $length) . '…';
    }
    else
    {
        $str = mb_substr($str, 0, $position) . '…' . mb_substr($str, $l - ($length - $position));
    }

    $shortened = true;

    return $str;
}

/**
 * Removes the accents of a string.
 *
 * @param string $str
 * @param string $charset Defaults to {@link ICanBoogie\CHARSET}.
 *
 * @return string
 */
function remove_accents($str, $charset=CHARSET)
{
    $str = htmlentities($str, ENT_NOQUOTES, $charset);

    $str = preg_replace('#&([A-za-z])(?:acute|cedil|caron|circ|grave|orn|ring|slash|th|tilde|uml);#', '\1', $str);
    $str = preg_replace('#&([A-za-z]{2})(?:lig);#', '\1', $str); // pour les ligatures e.g. '&oelig;'
    $str = preg_replace('#&[^;]+;#', '', $str); // supprime les autres caractères

    return $str;
}

/**
 * Binary-safe case-sensitive accents-insensitive string comparison.
 *
 * Accents are removed using the {@link remove_accents()} function.
 *
 * @param string $a
 * @param string $b
 *
 * @return bool
 */
function unaccent_compare($a, $b)
{
    return strcmp(remove_accents($a), remove_accents($b));
}

/**
 * Binary-safe case-insensitive accents-insensitive string comparison.
 *
 * Accents are removed using the {@link remove_accents()} function.
 *
 * @param string $a
 * @param string $b
 *
 * @return bool
 */
function unaccent_compare_ci($a, $b)
{
    return strcasecmp(remove_accents($a), remove_accents($b));
}

/**
 * Normalizes a string.
 *
 * Accents are removed, the string is downcased and characters that don't match [a-z0-9] are
 * replaced by the separator character.
 *
 * @param string $str The string to normalize.
 * @param string $separator The separator characters replaces characters the don't match [a-z0-9].
 * @param string $charset The charset of the string to normalize.
 *
 * @return string
 */
function normalize($str, $separator='-', $charset=CHARSET)
{
    static $cache;

    $cache_key = $charset . '|' . $separator . '|' . $str;

    if (isset($cache[$cache_key]))
    {
        return $cache[$cache_key];
    }

    $str = str_replace('\'', '', $str);
    $str = remove_accents($str, $charset);
    $str = strtolower($str);
    $str = preg_replace('#[^a-z0-9]+#', $separator, $str);
    $str = trim($str, $separator);

    return $cache[$cache_key] = $str;
}

/**
 * Returns information about a variable.
 *
 * The function uses xdebug_var_dump() if [Xdebug](http://xdebug.org/) is installed, otherwise it
 * uses print_r() output wrapped in a PRE element.
 *
 * @param mixed $value
 *
 * @return string
 */
function dump($value)
{
    if (function_exists('xdebug_var_dump'))
    {
        ob_start();

        xdebug_var_dump($value);

        $value = ob_get_clean();
    }
    else
    {
        $value = '<pre>' . escape(print_r($value, true)) . '</pre>';
    }

    return $value;
}

/**
 * Formats the given string by replacing placeholders with the values provided.
 *
 * @param string $str The string to format.
 * @param array $args An array of replacements for the placeholders. Occurrences in $str of any
 * key in $args are replaced with the corresponding sanitized value. The sanitization function
 * depends on the first character of the key:
 *
 * * :key: Replace as is. Use this for text that has already been sanitized.
 * * !key: Sanitize using the `ICanBoogie\escape()` function.
 * * %key: Sanitize using the `ICanBoogie\escape()` function and wrap inside a "EM" markup.
 *
 * Numeric indexes can also be used e.g '\2' or "{2}" are replaced by the value of the index
 * "2".
 *
 * @return string
 */
function format($str, array $args=array())
{
    static $quotation_start;
    static $quotation_end;

    if ($quotation_start === null)
    {
        if (PHP_SAPI == 'cli')
        {
            $quotation_start = '"';
            $quotation_end = '"';
        }
        else
        {
            $quotation_start = '<q>';
            $quotation_end = '</q>';
        }
    }

    if (!$args)
    {
        return $str;
    }

    $holders = array();
    $i = 0;

    foreach ($args as $key => $value)
    {
        if (is_object($value) && method_exists($value, '__toString'))
        {
            $value = (string) $value;
        }

        if (is_array($value) || is_object($value))
        {
            $value = dump($value);
        }
        else if (is_bool($value))
        {
            $value = $value ? '<em>true</em>' : '<em>false</em>';
        }
        else if (is_null($value))
        {
            $value = '<em>null</em>';
        }

        if (is_string($key))
        {
            switch ($key{0})
            {
                case ':': break;
                case '!': $value = escape($value); break;
                case '%': $value = $quotation_start . escape($value) . $quotation_end; break;

                default:
                {
                    $escaped_value = escape($value);

                    $holders['!' . $key] = $escaped_value;
                    $holders['%' . $key] = $quotation_start . $escaped_value . $quotation_end;

                    $key = ':' . $key;
                }
            }
        }

        $holders[$key] = $value;
        $holders['\\' . $i] = $value;
        $holders['{' . $i . '}'] = $value;

        $i++;
    }

    return strtr($str, $holders);
}

/**
 * Sorts an array using a stable sorting algorithm while preserving its keys.
 *
 * A stable sorting algorithm maintains the relative order of values with equal keys.
 *
 * The array is always sorted in ascending order but one can use the array_reverse() function to
 * reverse the array. Also keys are preserved, even numeric ones, use the array_values() function
 * to create an array with an ascending index.
 *
 * @param array &$array
 * @param callable $picker
 */
function stable_sort(&$array, $picker=null)
{
    static $transform, $restore;

    $i = 0;

    if (!$transform)
    {
        $transform = function(&$v, $k) use (&$i)
        {
            $v = array($v, ++$i, $k, $v);
        };

        $restore = function(&$v, $k)
        {
            $v = $v[3];
        };
    }

    if ($picker)
    {
        array_walk
        (
            $array, function(&$v, $k) use (&$i, $picker)
            {
                $v = array($picker($v, $k), ++$i, $k, $v);
            }
        );
    }
    else
    {
        array_walk($array, $transform);
    }

    asort($array);

    array_walk($array, $restore);
}

/**
 * Sort an array according to the weight of its items.
 *
 * The weight of the items is defined as an integer; a position relative to another member of the
 * array `before:<key>` or `after:<key>`; the special words `top` and `bottom`.
 *
 * @param array $array
 * @param callable $weight_picker The callback function used to pick the weight of the item. The
 * function is called with the following arguments: `$value`, `$key`.
 *
 * @return array A sorted copy of the array.
 */
function sort_by_weight(array $array, $weight_picker)
{
    if (!$array)
    {
        return $array;
    }

    $order = array();

    foreach ($array as $k => $v)
    {
        $order[$k] = $weight_picker($v, $k);
    }

    $n = count($order);
    $top = min($order) - $n;
    $bottom = max($order) + $n;

    foreach ($order as &$weight)
    {
        if ($weight === 'top')
        {
            $weight = --$top;
        }
        else if ($weight === 'bottom')
        {
            $weight = ++$bottom;
        }
    }

    foreach ($order as $k => &$weight)
    {
        if (strpos($weight, 'before:') === 0)
        {
            $target = substr($weight, 7);

            if (isset($order[$target]))
            {
                $order = array_insert($order, $target, $order[$target], $k);
            }
            else
            {
                $weight = 0;
            }
        }
        else if (strpos($weight, 'after:') === 0)
        {
            $target = substr($weight, 6);

            if (isset($order[$target]))
            {
                $order = array_insert($order, $target, $order[$target], $k, true);
            }
            else
            {
                $weight = 0;
            }
        }
    }

    stable_sort($order);

    array_walk($order, function(&$v, $k) use($array) {

        $v = $array[$k];

    });

    return $order;
}

/**
 * Inserts a value in a array before, or after, a given key.
 *
 * Numeric keys are not preserved.
 *
 * @param $array
 * @param $relative
 * @param $value
 * @param $key
 * @param $after
 *
 * @return array
 */
function array_insert($array, $relative, $value, $key=null, $after=false)
{
    if ($key)
    {
        unset($array[$key]);
    }

    $keys = array_keys($array);
    $pos = array_search($relative, $keys, true);

    if ($after)
    {
        $pos++;
    }

    $spliced = array_splice($array, $pos);

    if ($key !== null)
    {
        $array = array_merge($array, array($key => $value));
    }
    else
    {
        array_unshift($spliced, $value);
    }

    return array_merge($array, $spliced);
}

/**
 * Flattens an array.
 *
 * @param array $array
 * @param string|array $separator
 * @param int $depth
 *
 * @return array
 */
function array_flatten($array, $separator='.', $depth=0)
{
    $rc = array();

    if (is_array($separator))
    {
        foreach ($array as $key => $value)
        {
            if (!is_array($value))
            {
                $rc[$key . ($depth ? $separator[1] : '')] = $value;

                continue;
            }

            $values = array_flatten($value, $separator, $depth + 1);

            foreach ($values as $vkey => $value)
            {
                $rc[$key . ($depth ? $separator[1] : '') . $separator[0] . $vkey] = $value;
            }
        }
    }
    else
    {
        foreach ($array as $key => $value)
        {
            if (!is_array($value))
            {
                $rc[$key] = $value;

                continue;
            }

            $values = array_flatten($value, $separator);

            foreach ($values as $vkey => $value)
            {
                $rc[$key . $separator . $vkey] = $value;
            }
        }
    }

    return $rc;
}

/**
 * Merge arrays recursively with a different algorithm than PHP.
 *
 * @param array $array1
 * @param array $array2 ...
 *
 * @return array
 */
function array_merge_recursive(array $array1, array $array2=array())
{
    $arrays = func_get_args();

    $merge = array_shift($arrays);

    foreach ($arrays as $array)
    {
        foreach ($array as $key => $val)
        {
            #
            # if the value is an array and the key already exists
            # we have to make a recursion
            #

            if (is_array($val) && array_key_exists($key, $merge))
            {
                $val = array_merge_recursive((array) $merge[$key], $val);
            }

            #
            # if the key is numeric, the value is pushed. Otherwise, it replaces
            # the value of the _merge_ array.
            #

            if (is_numeric($key))
            {
                $merge[] = $val;
            }
            else
            {
                $merge[$key] = $val;
            }
        }
    }

    return $merge;
}

function exact_array_merge_recursive(array $array1, array $array2=array())
{
    $arrays = func_get_args();

    $merge = array_shift($arrays);

    foreach ($arrays as $array)
    {
        foreach ($array as $key => $val)
        {
            #
            # if the value is an array and the key already exists
            # we have to make a recursion
            #

            if (is_array($val) && array_key_exists($key, $merge))
            {
                $val = exact_array_merge_recursive((array) $merge[$key], $val);
            }

            $merge[$key] = $val;
        }
    }

    return $merge;
}

/**
 * Normalizes the path of a URL.
 *
 * @param string $path
 *
 * @return string
 *
 * @see http://en.wikipedia.org/wiki/URL_normalization
 */
function normalize_url_path($path)
{
    static $cache = array();

    $path = (string) $path;

    if (isset($cache[$path]))
    {
        return $cache[$path];
    }

    $normalized = preg_replace('#\/index\.(html|php)$#', '/', $path);
    $normalized = rtrim($normalized, '/');

    if (!preg_match('#\.[a-z]+$#', $normalized))
    {
        $normalized .= '/';
    }

    $cache[$path] = $normalized;

    return $normalized;
}

/**
 * Generates a v4 UUID.
 *
 * @return string
 *
 * @origin http://stackoverflow.com/questions/2040240/php-function-to-generate-v4-uuid#answer-15875555
 */
function generate_v4_uuid()
{
    $data = openssl_random_pseudo_bytes(16);
    $data[6] = chr(ord($data[6]) & 0x0f | 0x40); // set version to 0010
    $data[8] = chr(ord($data[8]) & 0x3f | 0x80); // set bits 6-7 to 10
    return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
ICanBoogie/Common v1.2.2.1 API documentation generated by ApiGen