pquery.array.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. <?php
  2. /**
  3. * pQuery plugin for executing common array functions.
  4. *
  5. * @package pQuery
  6. */
  7. /**
  8. * @todo Documentation
  9. */
  10. class pQueryArray extends pQuery implements pQueryExtension {
  11. static $accepts = array('array');
  12. /**
  13. * Get the value of an array alement at the given index.
  14. *
  15. * @param int|string $index The index to get the element of.
  16. * @returns mixed The array value at the given index if it exists, or NULL otherwise.
  17. */
  18. function get($index) {
  19. return isset($this->variable[$index]) ? $this->variable[$index] : null;
  20. }
  21. /**
  22. * Check if the array is empty.
  23. *
  24. * @returns bool Whether the array is empty.
  25. */
  26. function is_empty() {
  27. return !$this->count();
  28. }
  29. /**
  30. * Reverse the array.
  31. *
  32. * @returns pQueryArray The current object.
  33. */
  34. function reverse() {
  35. $this->variable = array_reverse($this->variable);
  36. return $this;
  37. }
  38. /**
  39. * Execute an existing array function on the array.
  40. *
  41. * @var $method string A (part of the) function name to execute.
  42. * @var method $args Additional arguments to pass to the called function.
  43. * @returns mixed Either the current object, or the return value
  44. * of the called array function.
  45. */
  46. function __call($method, $args) {
  47. $function = 'array_'.$method;
  48. if( function_exists($function) ) {
  49. array_unshift($args, &$this->variable);
  50. return call_user_func_array($function, $args);
  51. }
  52. if( in_array($method, array('count')) )
  53. return $method($this->variable);
  54. if( in_array($method, array('shuffle')) ) {
  55. $method($this->variable);
  56. return $this;
  57. }
  58. return self::error('Plugin "%s" has no method "%s".', __CLASS__, $method);
  59. }
  60. }
  61. /**
  62. * Shortcut constructor for {@link pQueryArray}.
  63. *
  64. * @returns pQueryArray A new pQueryArray instance.
  65. */
  66. function _arr($array) {
  67. return pQuery::create('array', $array);
  68. }
  69. pQuery::extend('pQueryArray', 'array');
  70. ?>