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
|
<?php
declare(strict_types=1);
namespace SimpleSAML\Error;
/**
* Class for creating exceptions from assertion failures.
*
* @author Olav Morken, UNINETT AS.
* @package SimpleSAMLphp
*/
class Assertion extends Exception
{
/**
* The assertion which failed, or null if only an expression was passed to the
* assert-function.
*/
private $assertion;
/**
* Constructor for the assertion exception.
*
* Should only be called from the onAssertion handler.
*
* @param string|null $assertion The assertion which failed, or null if the assert-function was
* given an expression.
*/
public function __construct($assertion = null)
{
assert($assertion === null || is_string($assertion));
$msg = 'Assertion failed: ' . var_export($assertion, true);
parent::__construct($msg);
$this->assertion = $assertion;
}
/**
* Retrieve the assertion which failed.
*
* @return string|null The assertion which failed, or null if the assert-function was called with an expression.
*/
public function getAssertion()
{
return $this->assertion;
}
/**
* Install this assertion handler.
*
* This function will register this assertion handler. If will not enable assertions if they are
* disabled.
* @return void
*/
public static function installHandler()
{
assert_options(ASSERT_WARNING, 0);
if (version_compare(PHP_VERSION, '8.0.0', '<')) {
assert_options(ASSERT_QUIET_EVAL, 0);
} else {
ini_set('assert.exception', '0');
ini_set('assert.warning', '1');
}
assert_options(ASSERT_CALLBACK, [Assertion::class, 'onAssertion']);
}
/**
* Handle assertion.
*
* This function handles an assertion.
*
* @param string $file The file assert was called from.
* @param int $line The line assert was called from.
* @param mixed $message The expression which was passed to the assert-function.
* @return void
*/
public static function onAssertion($file, $line, $message)
{
if (!empty($message)) {
$exception = new self($message);
} else {
$exception = new self();
}
$exception->logError();
}
}
|