PcreException.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. <?php
  2. /*
  3. * This file is part of composer/pcre.
  4. *
  5. * (c) Composer <https://github.com/composer>
  6. *
  7. * For the full copyright and license information, please view
  8. * the LICENSE file that was distributed with this source code.
  9. */
  10. namespace Composer\Pcre;
  11. class PcreException extends \RuntimeException
  12. {
  13. /**
  14. * @param string $function
  15. * @param string|string[] $pattern
  16. * @return self
  17. */
  18. public static function fromFunction($function, $pattern)
  19. {
  20. $code = preg_last_error();
  21. if (is_array($pattern)) {
  22. $pattern = implode(', ', $pattern);
  23. }
  24. return new PcreException($function.'(): failed executing "'.$pattern.'": '.self::pcreLastErrorMessage($code), $code);
  25. }
  26. /**
  27. * @param int $code
  28. * @return string
  29. */
  30. private static function pcreLastErrorMessage($code)
  31. {
  32. if (function_exists('preg_last_error_msg')) {
  33. return preg_last_error_msg();
  34. }
  35. // older php versions did not set the code properly in all cases
  36. if (PHP_VERSION_ID < 70201 && $code === 0) {
  37. return 'UNDEFINED_ERROR';
  38. }
  39. $constants = get_defined_constants(true);
  40. if (!isset($constants['pcre'])) {
  41. return 'UNDEFINED_ERROR';
  42. }
  43. foreach ($constants['pcre'] as $const => $val) {
  44. if ($val === $code && substr($const, -6) === '_ERROR') {
  45. return $const;
  46. }
  47. }
  48. return 'UNDEFINED_ERROR';
  49. }
  50. }