| 1 |
<?php |
| 2 |
|
| 3 |
namespace Wikimedia\NormalizedException; |
| 4 |
|
| 5 |
/** |
| 6 |
* Trait for creating a normalized exception |
| 7 |
*/ |
| 8 |
trait NormalizedExceptionTrait { |
| 9 |
|
| 10 |
/** @var string */ |
| 11 |
protected $normalizedMessage; |
| 12 |
|
| 13 |
/** @var (int|float|string|bool)[] */ |
| 14 |
protected $messageContext; |
| 15 |
|
| 16 |
/** |
| 17 |
* Turn a PSR-3 style normalized message and context into a real message, |
| 18 |
* by interpolating the context variables into the message string. |
| 19 |
* |
| 20 |
* Intended for use in exception constructors to construct the message |
| 21 |
* that's passed to the parent constructor. |
| 22 |
* |
| 23 |
* @stable to call |
| 24 |
* @param string $normalizedMessage A message string with zero or more |
| 25 |
* {}-wrapped tokens in it. |
| 26 |
* @param array $context An array mapping tokens (without the braces) to |
| 27 |
* values. Fields not used in the message are allowed. Values that are |
| 28 |
* used in the message should be scalars or have a __toString() method. |
| 29 |
* @return string |
| 30 |
*/ |
| 31 |
public static function getMessageFromNormalizedMessage( string $normalizedMessage, array $context ) { |
| 32 |
$replacements = []; |
| 33 |
foreach ( $context as $placeholder => $value ) { |
| 34 |
if ( is_bool( $value ) ) { |
| 35 |
$stringValue = $value ? '<true>' : '<false>'; |
| 36 |
} elseif ( $value === null ) { |
| 37 |
$stringValue = '<null>'; |
| 38 |
} else { |
| 39 |
$stringValue = (string)$value; |
| 40 |
} |
| 41 |
$replacements['{' . $placeholder . '}'] = $stringValue; |
| 42 |
} |
| 43 |
return strtr( $normalizedMessage, $replacements ); |
| 44 |
} |
| 45 |
|
| 46 |
/** @inheritDoc */ |
| 47 |
public function getNormalizedMessage(): string { |
| 48 |
return $this->normalizedMessage; |
| 49 |
} |
| 50 |
|
| 51 |
/** @inheritDoc */ |
| 52 |
public function getMessageContext(): array { |
| 53 |
return $this->messageContext; |
| 54 |
} |
| 55 |
|
| 56 |
} |