| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- <?php
- namespace yiins\helpers;
- use yiins\exceptions\InvalidConfigException;
- class VariableHelper
- {
- /**
- * Initializes variable with default value if it is null
- * @param mixed $variable to be initialized
- * @param mixed|callable $default default value for variable or callable for creation of it
- */
- public static function initialize(&$variable, $default = null)
- {
- if ($variable === null) {
- if (is_callable($default)) {
- $variable = call_user_func($default, $variable);
- } else {
- $variable = $default;
- }
- }
- }
- /**
- * Checks if variable is null and throws InvalidConfigException if it is null
- * @param mixed $variable variable to check
- * @param string $message message to print if variable is null
- * @throws InvalidConfigException
- */
- public static function required(&$variable, $message = null)
- {
- if ($variable === null) {
- throw new InvalidConfigException($message ?? 'Required param not found.');
- }
- }
- public static function cast($object, $class)
- {
- $objectClass = get_class($object);
- if ($objectClass === $class) {
- return $object;
- }
- if (!is_subclass_of($class, $objectClass) && !is_subclass_of($objectClass, $class)) {
- throw new \InvalidArgumentException(sprintf('Object of class %s is incompatible with class %s',
- $objectClass, $class));
- }
- $result = unserialize(
- preg_replace(
- '/^O:\d+:"[^"]++"/',
- 'O:' . strlen($class) . ':"' . $class . '"',
- serialize($object)
- )
- );
- return $result;
- }
- }
|