/** * traverse a list held in an array or a traversable object * * @param array|object $list * the list to walk * @param string $listName * what is the name of $list in the calling code? * @param callable $callable * what are we calling * @return void */ public static function using($list, $listName, callable $callable) { // genuine PHP array? if (is_array($list)) { return TraverseArray::using($list, $listName, $callable); } // iterator of some kind? if ($list instanceof Traversable) { return TraverseArray::using($list, $listName, $callable); } // all objects can be traversed, although it doesn't // always make sense if (is_object($list)) { return TraverseObject::using($list, $listName, $callable); } // if we get here, we can't help throw new InvalidArgumentException('$list is not traversable'); }
/** * traverse a list held in an array * * @param array $list * the list to walk * @param string $listName * what is the name of $list in the calling code? * @param callable $callable * what are we calling * @return void */ function traverse_array($list, $listName, callable $callable) { return TraverseArray::using($list, $listName, $callable); }
/** * @covers ::using * @dataProvider provideNonLists * @expectedException InvalidArgumentException */ public function test_throws_InvalidArgumentException_when_list_is_not_an_array_or_Traversable($list) { // ---------------------------------------------------------------- // setup your test // this will hold the list built by our callable $actualList = []; // the test uses a valid callable just to make sure this // is not triggering any exceptions of any kind $callable = function ($value, $key, $name) use(&$actualList) { $actualList[$name] = $value; }; // ---------------------------------------------------------------- // perform the change TraverseArray::using($list, '$list', $callable); // ---------------------------------------------------------------- // test the results }