CakeFest 2025 Madrid: The Official CakePHP Conference

Voting

: max(nine, zero)?
(Example: nine)

The Note You're Voting On

zerodahero at gmail dot com
5 years ago
In PHP 7.3+, and depending on the environment, there may be other constants that aren't ints which will cause errors with array_flip. I opted to go with a RegexException and a filter on gk's note.

<?php

class RegexException extends \Exception {

public
$errorCode;

public function
__construct(
int $errorCode,
string $additionalMessage = null
) {
$this->errorCode = $errorCode;

$errorMessage = $this->getErrorString($errorCode) ?? 'Unknown regex error';
$additionalMessage = $additionalMessage ? " $additionalMessage" : '';

parent::__construct("Regex error thrown: $errorMessage." . $additionalMessage);
}

/**
* Gets an error string (const name) for the PCRE error code
*
* @param int $errorCode
*
* @return string|null
*/
private function getErrorString(int $errorCode): ?string
{
$pcreConstants = get_defined_constants(true)['pcre'] ?? [];

/*
* NOTE: preg_last_error() returns an int, but there are constants
* in PHP 7.3+ that are strings, bools, or otherwise. We can pretty
* safely filter out the non-integers to fetch the appropriate
* error constant name.
*/
$pcreConstants = array_filter($pcreConstants, function ($code) {
return
is_int($code);
});

$errorStrings = array_flip($pcreConstants);

return
$errorStrings[$errorCode] ?? null;
}

Usage:

throw new
RegexException(preg_last_error());

<< Back to user notes page

To Top