ArrayOrTraversableGuardTrait.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  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. * Provide a guard method for array or Traversable data
  13. */
  14. trait ArrayOrTraversableGuardTrait
  15. {
  16. /**
  17. * Verifies that the data is an array or Traversable
  18. *
  19. * @param mixed $data the data to verify
  20. * @param string $dataName the data name
  21. * @param string $exceptionClass FQCN for the exception
  22. * @throws \Exception
  23. */
  24. protected function guardForArrayOrTraversable(
  25. $data,
  26. $dataName = 'Argument',
  27. $exceptionClass = 'Zend\Stdlib\Exception\InvalidArgumentException'
  28. ) {
  29. if (!is_array($data) && !($data instanceof Traversable)) {
  30. $message = sprintf(
  31. "%s must be an array or Traversable, [%s] given",
  32. $dataName,
  33. is_object($data) ? get_class($data) : gettype($data)
  34. );
  35. throw new $exceptionClass($message);
  36. }
  37. }
  38. }