GuardUtils.php 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /**
  3. * Zend Framework (http://framework.zend.com/)
  4. *
  5. * @link http://github.com/zendframework/zf2 for the canonical source repository
  6. * @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
  7. * @license http://framework.zend.com/license/new-bsd New BSD License
  8. */
  9. namespace Zend\Stdlib\Guard;
  10. use Traversable;
  11. /**
  12. * Static guard helper class
  13. *
  14. * Bridges the gap for allowing refactoring until traits can be used by default.
  15. *
  16. * @deprecated
  17. */
  18. abstract class GuardUtils
  19. {
  20. const DEFAULT_EXCEPTION_CLASS = 'Zend\Stdlib\Exception\InvalidArgumentException';
  21. /**
  22. * Verifies that the data is an array or Traversable
  23. *
  24. * @param mixed $data the data to verify
  25. * @param string $dataName the data name
  26. * @param string $exceptionClass FQCN for the exception
  27. * @throws \Exception
  28. */
  29. public static function guardForArrayOrTraversable(
  30. $data,
  31. $dataName = 'Argument',
  32. $exceptionClass = self::DEFAULT_EXCEPTION_CLASS
  33. ) {
  34. if (!is_array($data) && !($data instanceof Traversable)) {
  35. $message = sprintf(
  36. '%s must be an array or Traversable, [%s] given',
  37. $dataName,
  38. is_object($data) ? get_class($data) : gettype($data)
  39. );
  40. throw new $exceptionClass($message);
  41. }
  42. }
  43. /**
  44. * Verify that the data is not empty
  45. *
  46. * @param mixed $data the data to verify
  47. * @param string $dataName the data name
  48. * @param string $exceptionClass FQCN for the exception
  49. * @throws \Exception
  50. */
  51. public static function guardAgainstEmpty(
  52. $data,
  53. $dataName = 'Argument',
  54. $exceptionClass = self::DEFAULT_EXCEPTION_CLASS
  55. ) {
  56. if (empty($data)) {
  57. $message = sprintf('%s cannot be empty', $dataName);
  58. throw new $exceptionClass($message);
  59. }
  60. }
  61. /**
  62. * Verify that the data is not null
  63. *
  64. * @param mixed $data the data to verify
  65. * @param string $dataName the data name
  66. * @param string $exceptionClass FQCN for the exception
  67. * @throws \Exception
  68. */
  69. public static function guardAgainstNull(
  70. $data,
  71. $dataName = 'Argument',
  72. $exceptionClass = self::DEFAULT_EXCEPTION_CLASS
  73. ) {
  74. if (null === $data) {
  75. $message = sprintf('%s cannot be null', $dataName);
  76. throw new $exceptionClass($message);
  77. }
  78. }
  79. }