. */ namespace App\Exceptions; use Doctrine\DBAL\Exception\DriverException; use ErrorException; class InvalidRegexException extends \RuntimeException { public function __construct(private readonly ?string $reason = null) { parent::__construct('Invalid regular expression'); } /** * Returns the reason for the exception (what the regex driver deemed invalid) */ public function getReason(): ?string { return $this->reason; } /** * Creates a new exception from a driver exception happening, when MySQL encounters an invalid regex */ public static function fromDriverException(DriverException $exception): self { //1139 means invalid regex error if ($exception->getCode() !== 1139) { throw new \InvalidArgumentException('The given exception is not a driver exception', 0, $exception); } //Reason is the part after the erorr code $reason = preg_replace('/^.*1139 /', '', $exception->getMessage()); return new self($reason); } /** * Creates a new exception from the errorException thrown by mb_ereg */ public static function fromMBRegexError(ErrorException $ex): self { //Ensure that the error is really a mb_ereg error if ($ex->getSeverity() !== E_WARNING || !strpos($ex->getMessage(), 'mb_ereg()')) { throw new \InvalidArgumentException('The given exception is not a mb_ereg error', 0, $ex); } //Reason is the part after the erorr code $reason = preg_replace('/^.*mb_ereg\(\): /', '', $ex->getMessage()); return new self($reason); } }