VariableHelper.php 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. <?php
  2. namespace yiins\helpers;
  3. use yiins\exceptions\InvalidConfigException;
  4. class VariableHelper
  5. {
  6. /**
  7. * Initializes variable with default value if it is null
  8. * @param mixed $variable to be initialized
  9. * @param mixed|callable $default default value for variable or callable for creation of it
  10. */
  11. public static function initialize(&$variable, $default = null)
  12. {
  13. if ($variable === null) {
  14. if (is_callable($default)) {
  15. $variable = call_user_func($default, $variable);
  16. } else {
  17. $variable = $default;
  18. }
  19. }
  20. }
  21. /**
  22. * Checks if variable is null and throws InvalidConfigException if it is null
  23. * @param mixed $variable variable to check
  24. * @param string $message message to print if variable is null
  25. * @throws InvalidConfigException
  26. */
  27. public static function required(&$variable, $message = null)
  28. {
  29. if ($variable === null) {
  30. throw new InvalidConfigException($message ?? 'Required param not found.');
  31. }
  32. }
  33. public static function cast($object, $class)
  34. {
  35. $objectClass = get_class($object);
  36. if ($objectClass === $class) {
  37. return $object;
  38. }
  39. if (!is_subclass_of($class, $objectClass) && !is_subclass_of($objectClass, $class)) {
  40. throw new \InvalidArgumentException(sprintf('Object of class %s is incompatible with class %s',
  41. $objectClass, $class));
  42. }
  43. $result = unserialize(
  44. preg_replace(
  45. '/^O:\d+:"[^"]++"/',
  46. 'O:' . strlen($class) . ':"' . $class . '"',
  47. serialize($object)
  48. )
  49. );
  50. return $result;
  51. }
  52. }