src/NormalizeStringableCapableTrait.php
<?php
namespace Dhii\Util\Normalization;
use Dhii\Util\String\StringableInterface as Stringable;
use Exception as RootException;
use InvalidArgumentException;
/**
* Functionality for normalizing stringable values.
*
* @since [*next-version*]
*/
trait NormalizeStringableCapableTrait
{
/**
* Normalizes a stringable value.
*
* Useful to make sure that a value can be converted to string in a meaningful way.
*
* @since [*next-version*]
*
* @param Stringable|string|int|float|bool $stringable The value to normalize.
* Can be an object that implements {@see Stringable}, or scalar type -
* basically anything that can be converted to a string in a meaningful way.
*
* @throws InvalidArgumentException If the value could not be normalized.
*
* @return Stringable|string|int|float|bool The normalized stringable.
* If the original value was stringable, that same value will be returned without any modification.
*/
protected function _normalizeStringable($stringable)
{
if (!is_scalar($stringable)
&& !($stringable instanceof Stringable)
) {
throw $this->_createInvalidArgumentException($this->__('Not a stringable value'), null, null, $stringable);
}
return $stringable;
}
/**
* Creates a new invalid argument exception.
*
* @since [*next-version*]
*
* @param string|Stringable|null $message The error message, if any.
* @param int|null $code The error code, if any.
* @param RootException|null $previous The inner exception for chaining, if any.
* @param mixed|null $argument The invalid argument, if any.
*
* @return InvalidArgumentException The new exception.
*/
abstract protected function _createInvalidArgumentException(
$message = null,
$code = null,
RootException $previous = null,
$argument = null
);
/**
* Translates a string, and replaces placeholders.
*
* @since [*next-version*]
* @see sprintf()
*
* @param string $string The format string to translate.
* @param array $args Placeholder values to replace in the string.
* @param mixed $context The context for translation.
*
* @return string The translated string.
*/
abstract protected function __($string, $args = [], $context = null);
}