| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | /** |
| 6 | * This file is part of phpDocumentor. |
| 7 | * |
| 8 | * For the full copyright and license information, please view the LICENSE |
| 9 | * file that was distributed with this source code. |
| 10 | * |
| 11 | * @link http://phpdoc.org |
| 12 | */ |
| 13 | |
| 14 | namespace phpDocumentor\Reflection; |
| 15 | |
| 16 | use phpDocumentor\Reflection\Exception\PcreException; |
| 17 | use Webmozart\Assert\Assert; |
| 18 | |
| 19 | use function preg_last_error; |
| 20 | use function preg_split as php_preg_split; |
| 21 | |
| 22 | abstract class Utils |
| 23 | { |
| 24 | /** |
| 25 | * Wrapper function for phps preg_split |
| 26 | * |
| 27 | * This function is inspired by {@link https://github.com/thecodingmachine/safe/blob/master/generated/pcre.php}. But |
| 28 | * since this library is all about performance we decided to strip everything we don't need. Reducing the amount |
| 29 | * of files that have to be loaded, etc. |
| 30 | * |
| 31 | * @param string $pattern The pattern to search for, as a string. |
| 32 | * @param string $subject The input string. |
| 33 | * @param int $limit If specified, then only substrings up to limit are returned with the |
| 34 | * rest of the string being placed in the last substring. A limit of -1 or 0 means "no limit". |
| 35 | * @param int $flags flags can be any combination of the following flags (combined with the | bitwise operator): |
| 36 | * *PREG_SPLIT_NO_EMPTY* |
| 37 | * If this flag is set, only non-empty pieces will be returned by preg_split(). |
| 38 | * *PREG_SPLIT_DELIM_CAPTURE* |
| 39 | * If this flag is set, parenthesized expression in the delimiter pattern will be captured |
| 40 | * and returned as well. |
| 41 | * *PREG_SPLIT_OFFSET_CAPTURE* |
| 42 | * If this flag is set, for every occurring match the appendant string offset will also be returned. |
| 43 | * Note that this changes the return value in an array where every element is an array consisting of the |
| 44 | * matched string at offset 0 and its string offset into subject at offset 1. |
| 45 | * |
| 46 | * @return string[] Returns an array containing substrings of subject |
| 47 | * split along boundaries matched by pattern |
| 48 | * |
| 49 | * @throws PcreException |
| 50 | */ |
| 51 | public static function pregSplit(string $pattern, string $subject, int $limit = -1, int $flags = 0): array |
| 52 | { |
| 53 | $parts = php_preg_split($pattern, $subject, $limit, $flags); |
| 54 | if ($parts === false) { |
| 55 | throw PcreException::createFromPhpError(preg_last_error()); |
| 56 | } |
| 57 | |
| 58 | Assert::allString($parts); |
| 59 | |
| 60 | return $parts; |
| 61 | } |
| 62 | } |