function createFileStruct($arguments) { $cur_path = getcwd(); $iterator = new RecursiveArrayIterator($arguments); iterator_apply($iterator, 'traverseStructure', array($iterator)); echo 'File structure complete.'; }
private function inspectDir($path) { $rdi = new RecursiveDirectoryIterator($path); $rii = new RecursiveIteratorIterator($rdi); $filtered = new HausDesign_Controller_Plugin_Reflection_Filter($rii); iterator_apply($filtered, array($this, 'process'), array($filtered)); }
/** * get formatted data * @return array */ public function getData() { // format functions self::$map['effect'] = function ($iterator) { $effect = $iterator['effect']; switch ($iterator['effect']) { case 'magnetar': $effect = 'magnetar'; break; case 'red giant': $effect = 'redGiant'; break; case 'pulsar': $effect = 'pulsar'; break; case 'wolf-rayet star': $effect = 'wolfRayet'; break; case 'cataclysmic variable': $effect = 'cataclysmic'; break; case 'black hole': $effect = 'blackHole'; break; } return $effect; }; // format functions self::$map['security'] = function ($iterator) { if ($iterator['security'] == 7 || $iterator['security'] == 8 || $iterator['security'] == 9) { $trueSec = round($iterator['trueSec'], 3); if ($trueSec <= 0) { $security = '0.0'; } elseif ($trueSec < 0.5) { $security = 'L'; } else { $security = 'H'; } } else { $security = 'C' . $iterator['security']; } return $security; }; // format functions self::$map['type'] = function ($iterator) { // TODO refactor $type = 'w-space'; $typeId = 1; if ($iterator['security'] == 7 || $iterator['security'] == 8 || $iterator['security'] == 9) { $type = 'k-space'; $typeId = 2; } return ['id' => $typeId, 'name' => $type]; }; iterator_apply($this, 'self::recursiveIterator', [$this]); return iterator_to_array($this, false); }
/** * * * @param array $index * @param $storeId * @param $productIds * @return array */ protected function _addAdvancedIndexData(array $index, $storeId, $productIds) { $prefix = $this->_engine->getFieldsPrefix(); $prefixedCategoryData = $this->_getCatalogCategoryData($storeId, $productIds); $prefixedPriceData = $this->_getCatalogProductPriceData($productIds); $indexCollector = new ArrayObject(); $indexIterator = new ArrayIterator($index); iterator_apply($indexIterator, array($this, '_advancedIndexCallback'), array($indexIterator, $indexCollector, $prefix, $prefixedCategoryData, $prefixedPriceData)); return $indexCollector->getArrayCopy(); }
/** * Set Data Source from different sources * * @param ArrayIterator $source * Source Data * * @return ArrayIterator * Input ArrayIterator with its values modified to be instance of * Next\DB\Table\Row */ protected function setSource($source) { parent::setSource($source); $manager =& $this->manager; iterator_apply($this->source, function (\Iterator $iterator) use($manager) { $iterator->offsetSet($iterator->key(), new Row($manager, $iterator->current())); return TRUE; }, array($this->source)); return $this->source; }
function apply() { $arr = array('chen', 'wang', 'liu'); try { $it = new ArrayIterator($arr); iterator_apply($it, 'addCaps', array($it)); } catch (Exception $e) { // echo the error message echo $e->getMessage(); } }
/** * Retrieve rules for a given UA * @param string $userAgent * @return null|Rule */ public function get($userAgent) { $item = null; $iterator = new \ArrayIterator($this->collection); iterator_apply($iterator, function (\ArrayIterator $iterator, $userAgent) use(&$item) { if ($iterator->key() != Rules::DEFAULT_UA && preg_match($iterator->key(), $userAgent) === 1) { $item = $iterator->current(); return false; } return true; }, [$iterator, $userAgent]); return $item !== null ? $item : (isset($this->collection[self::DEFAULT_UA]) ? $this->collection[self::DEFAULT_UA] : null); }
/** * Get Annotations Found * * @return array * Found Annotations */ public function getAnnotations() { $data = new \ArrayIterator(); $domains = $this->matchDomainAnnotations($this->application); if (count($domains) > 0) { $data->offsetSet('Domains', $domains); } $data->offsetSet('Path', $this->matchPathAnnotation($this->application)); // Listing Controllers Methods and reducing (or amplifying) the list to its Action Methods $actions = $this->application->getControllers()->getIterator(); iterator_apply($actions, function (\Iterator $iterator) { $action = new Actions(new \ArrayIterator($iterator->current()->getClass()->getMethods())); $iterator->offsetSet($iterator->key(), $action->getAnnotations()); return TRUE; }, array($actions)); if ($actions->count() > 0) { $data->offsetSet('Routes', $actions->getArrayCopy()); } return $data; }
<?php function someFunc($iterator) { print $iterator->current(); return true; } $array = array(1, 2, 3); $iterator = new ArrayIterator($array); iterator_apply($iterator, 'someFunc', array($iterator));
/** * @return array * @throws Zend_Exception */ public function getArrayGroupProducts() { // $cache = Zend_Registry::get('cache'); // // $cache->remove('fullCatalogProducts'); //Массив по группам $arrayGroupProducts = array(); $categoryMapper = new Catalog_Model_Mapper_Categories(); $treeCategories = $categoryMapper->fetchTreeSubCategoriesInArray(); foreach ($treeCategories as $item) { $this->setCategoryWithProducts(array()); $children = $item['subCategories']; $it = new RecursiveArrayIterator($children); iterator_apply($it, array('Utils_CsvCatalogGeneratorController', 'fetchCategoriesWithProducts'), array($it)); $categoryProducts = $this->getCategoryWithProducts(); if (!empty($categoryProducts)) { foreach ($categoryProducts as $key => $categoryProduct) { $products = $this->getProductsCategory($key); $categoryProducts[$key]['products'] = $products; } } $arrayGroupProducts[$item['id']] = $categoryProducts; } return $arrayGroupProducts; }
/** * Partitions this collection in two collections according to a predicate. * Keys are preserved in the resulting collections. * * @param Closure $p The predicate on which to partition. * * @return array An array with two elements. The first element contains the collection * of elements where the predicate returned TRUE, the second element * contains the collection of elements where the predicate returned FALSE. */ public function partition(Closure $p) { $trueColl = new static(); $falseColl = new static(); iterator_apply($this, function () use($p, $trueColl, $falseColl) { $key = $this->key(); $current = $this->current(); if ($p($current, $key)) { $trueColl->set($key, $current); } else { $falseColl->set($key, $current); } return true; }); return array($trueColl, $falseColl); }
/** * Returns an iterator of the current position * @param \RecursiveArrayIterator $node * @param array $tree * @return mixed|null */ protected function findValue(\RecursiveArrayIterator $node, $tree = []) { # Find the node we are looking for, and return the iterator and value list($node, $node_value) = $this->findNode($node, $tree); if ($node_value === null) { return null; } # This node has no children, it's just a string value, replace and return if ($node->hasChildren() === false) { $node->offsetSet($node->key(), $this->parseTokens($node->current())); return $node->current(); } # The node we want has children, parse through the # leafs and parse any tokens that are present in them $rec_ii = new \RecursiveIteratorIterator($node->getChildren(), \RecursiveIteratorIterator::LEAVES_ONLY); iterator_apply($rec_ii, function (\Iterator &$iter, &$node_value) { $curr_key = $iter->key(); $curr_val = $this->parseTokens($iter->current()); $iter->offsetSet($curr_key, $curr_val); # This is a bug in PHP or something - if $nodeValue is an array, then the # offsetSet() doesn't "stick" the new values, since they're not passed # into the iterator by reference. So this is a work-around if (is_array($node_value) && isset($node_value[$curr_key])) { $node_value[$curr_key] = $curr_val; } return true; }, [&$rec_ii, &$node_value]); return $node_value; }
/** * Get registered Cookies * * @param boolean $asString * If TRUE, instead a Collection, a string of all the cookies will be returned * * @return Next\Components\Iterator\Lists|Next\HTTP\Headers\Fields\Request\Cookie * * <p> * If <strong>$asString</strong> is set to FALSE, the Cookies * Lists Collection will be returned * </p> * * <p> * If <strong>$asString</strong> is TRUE, a well formed Request * Cookie Header will be returned * </p> */ public function getCookies($asString = FALSE) { if ($asString === FALSE) { return $this->cookies->getCollection(); } // Is there something to return? if ($this->cookies->count() == 0) { return NULL; } // Let's return as string $cookieString = NULL; $iterator = $this->cookies->getIterator(); iterator_apply($iterator, function (\Iterator $iterator) use(&$cookieString) { $cookieString .= sprintf("%s;", $iterator->current()->getValue()); return TRUE; }, array($iterator)); return new Cookie(rtrim($cookieString, ";")); }
/** * Register many plugins at once * * If $map is a string, assumes that the map is the class name of a * Traversable object (likely a ShortNameLocator); it will then instantiate * this class and use it to register plugins. * * If $map is an array or Traversable object, it will iterate it to * register plugin names/classes. * * For all other arguments, or if the string $map is not a class or not a * Traversable class, an exception will be raised. * * @param string|array|Traversable $map * @return PluginClassLoader * @throws Exception\InvalidArgumentException */ public function registerPlugins($map) { if (is_string($map)) { if (!class_exists($map)) { throw new Exception\InvalidArgumentException('Map class provided is invalid'); } $map = new $map; } if (is_array($map)) { $map = new ArrayIterator($map); } if (!$map instanceof Traversable) { throw new Exception\InvalidArgumentException('Map provided is invalid; must be traversable'); } // iterator_apply doesn't work as expected with IteratorAggregate if ($map instanceof IteratorAggregate) { $map = $map->getIterator(); } // iterator_apply is faster than foreach $loader = $this; iterator_apply($map, function() use ($loader, $map) { $loader->registerPlugin($map->key(), $map->current()); return true; }); return $this; }
/** * addRoutes(): defined by RouteStack interface. * * @see Route::addRoutes() * @param mixed $routes * @return RouteStack */ public function addRoutes($routes) { if (is_array($routes)) { $routes = new ArrayIterator($routes); } elseif (!$routes instanceof Traversable) { throw new Exception\InvalidArgumentException('Routes provided are invalid; must be traversable'); } $routeStack = $this; iterator_apply($routes, function() use ($routeStack, $routes) { $routeStack->addRoute($routes->key(), $routes->current()); return true; }); return $this; }
echo "Appending to plugin class map '$output' for classes in '$path'..." . PHP_EOL; } else { echo "Creating plugin class map for classes in '$path'..." . PHP_EOL; } } // Get the ClassFileLocator, and pass it the library path $l = new \Zend\File\ClassFileLocator($path); // Iterate over each element in the path, and create a map of pluginname => classname $map = new \stdClass; iterator_apply($l, function() use ($l, $map){ $file = $l->current(); $namespace = empty($file->namespace) ? '' : $file->namespace . '\\'; $plugin = strtolower($file->classname); $class = $namespace . $file->classname; $map->{$plugin} = $class; return true; }); if ($appending) { $content = var_export((array) $map, true) . ';'; // Fix \' strings from injected DIRECTORY_SEPARATOR usage in iterator_apply op $content = str_replace("\\'", "'", $content); // Convert to an array and remove the first "array (" $content = explode(PHP_EOL, $content); array_shift($content);
} else { echo "Creating class file map for library in '{$path}'..." . PHP_EOL; } } // Get the ClassFileLocator, and pass it the library path $l = new \Zend\File\ClassFileLocator($path); // Iterate over each element in the path, and create a map of // classname => filename, where the filename is relative to the library path $map = new \stdClass(); $strip .= DIRECTORY_SEPARATOR; iterator_apply($l, function () use($l, $map, $strip, $relativePathForClassmap) { $file = $l->current(); $namespace = empty($file->namespace) ? '' : $file->namespace . '\\'; $filename = str_replace($strip, '', $file->getPath() . DIRECTORY_SEPARATOR . $file->getFilename()); // Add in relative path to library $filename = $relativePathForClassmap . $filename; // Replace directory separators with constant $filename = str_replace(array('/', '\\'), "' . DIRECTORY_SEPARATOR . '", $filename); $map->{$namespace . $file->classname} = $filename; return true; }); if ($appending) { $content = var_export((array) $map, true) . ';'; // Prefix with __DIR__; modify the generated content $content = preg_replace('#(=> )#', '$1__DIR__ . DIRECTORY_SEPARATOR . ', $content); // Fix \' strings from injected DIRECTORY_SEPARATOR usage in iterator_apply op $content = str_replace("\\'", "'", $content); // Convert to an array and remove the first "array (" $content = explode(PHP_EOL, $content); array_shift($content); // Load existing class map file and remove the closing "bracket ");" from it
<?php function test() { throw new Exception('Broken callback'); } $it = new RecursiveArrayIterator(array(1, 21, 22)); try { iterator_apply($it, 'test'); } catch (Exception $e) { echo $e->getMessage(); }
echo "Creating class file map for library in '{$path}'..." . PHP_EOL; } // Get the ClassFileLocator, and pass it the library path $l = new Zend_File_ClassFileLocator($path); // Iterate over each element in the path, and create a map of // classname => filename, where the filename is relative to the library path $map = new stdClass(); $strip .= DIRECTORY_SEPARATOR; function createMap(Iterator $i, $map, $strip) { $file = $i->current(); $namespace = empty($file->namespace) ? '' : $file->namespace . '\\'; $filename = str_replace($strip, '', $file->getRealpath()); // Windows portability $filename = str_replace(array('/', '\\'), "' . DIRECTORY_SEPARATOR . '", $filename); $map->{$namespace . $file->classname} = $filename; return true; } iterator_apply($l, 'createMap', array($l, $map, $strip)); // Create a file with the class/file map. // Stupid syntax highlighters make separating < from PHP declaration necessary $dirStore = 'dirname_' . uniqid(); $content = '<' . "?php\n" . '$' . $dirStore . " = dirname(__FILE__);\n" . 'return ' . var_export((array) $map, true) . ';'; // Prefix with dirname(__FILE__); modify the generated content $content = preg_replace('#(=> )#', '$1$' . $dirStore . ' . DIRECTORY_SEPARATOR . ', $content); $content = str_replace("\\'", "'", $content); // Write the contents to disk file_put_contents($output, $content); if (!$usingStdout) { echo "Wrote classmap file to '" . realpath($output) . "'" . PHP_EOL; }
/** * map iterator * @return array */ public function getData() { // "system trueSec" mapping ------------------------------------------- self::$map['trueSec'] = function ($iterator) { $trueSec = self::formatTrueSec($iterator['system_security']); return $trueSec; }; // "system effect" mapping -------------------------------------------- self::$map['effect'] = function ($iterator) { $effect = $iterator['effect']; switch ($iterator['effect']) { case 'magnetar': $effect = 'magnetar'; break; case 'red giant': $effect = 'redGiant'; break; case 'pulsar': $effect = 'pulsar'; break; case 'wolf-rayet star': $effect = 'wolfRayet'; break; case 'cataclysmic variable': $effect = 'cataclysmic'; break; case 'black hole': $effect = 'blackHole'; break; } return $effect; }; // "system security" mapping ------------------------------------------ self::$map['security'] = function ($iterator) { $security = ''; if ($iterator['security'] == 7 || $iterator['security'] == 8 || $iterator['security'] == 9) { // k-space system $trueSec = self::formatTrueSec($iterator['system_security']); if ($trueSec <= 0) { $security = '0.0'; } elseif ($trueSec < 0.5) { $security = 'L'; } else { $security = 'H'; } } elseif ($iterator['security'] == 1 || $iterator['security'] == 2 || $iterator['security'] == 3 || $iterator['security'] == 4 || $iterator['security'] == 5 || $iterator['security'] == 6) { // standard wormhole system $security = 'C' . $iterator['security']; } elseif ($iterator['security'] == 13) { // shattered wormhole system $security = 'SH'; } return $security; }; // "system type" mapping ---------------------------------------------- self::$map['type'] = function ($iterator) { // TODO refactor $type = 'w-space'; $typeId = 1; if ($iterator['security'] == 7 || $iterator['security'] == 8 || $iterator['security'] == 9) { $type = 'k-space'; $typeId = 2; } return ['id' => $typeId, 'name' => $type]; }; iterator_apply($this, 'self::recursiveIterator', [$this]); return iterator_to_array($this, false); }
echo '<hr>'; echo '<h3>array_map()</h3>'; $uppercaseNumbers = array_map(function ($number) { return strtoupper($number); }, $numbersCollection); printf('Collection used in array_map(): %s<br>', json_encode($uppercaseNumbers)); echo '<hr>'; $collectionAsArray = iterator_to_array($numbersCollection); printf('Collection as array: %s<br>', json_encode($collectionAsArray)); echo '<hr>'; $uppercaseNumbers = array_map(function ($number) { return strtoupper($number); }, $collectionAsArray); printf('Collection (as array) used in array_map(): %s<br>', json_encode($uppercaseNumbers)); echo '<hr>'; echo '<h3>array_chunk()</h3>'; $chunked = array_chunk($collectionAsArray, 2); printf('Collection (as array) used in chunked(): %s<br>', json_encode($chunked)); echo '<hr>'; echo '<h3>iterator_apply()</h3>'; iterator_apply($numbersCollection, function ($numbersCollection) { printf('%s ', $numbersCollection->current()); return true; }, [$numbersCollection]); echo '<hr>'; echo '<h3>unset()</h3>'; unset($numbersCollection[2]); printf('Collection after unset(): %s<br>', json_encode($numbersCollection->getCollection())); unset($numbers[2]); printf('Array after unset(): %s<br>', json_encode($numbers)); echo '<hr>';
<?php /** * Adds `class="img-responsive"` to images in generated HTML files. * * @license http://opensource.org/licenses/BSD-3-Clause BSD-3-Clause * @copyright Copyright (c) 2016 Zend Technologies USA Inc. (http://www.zend.com) */ $docPath = realpath(getcwd() . '/doc'); $rdi = new RecursiveDirectoryIterator($docPath . '/html'); $rii = new RecursiveIteratorIterator($rdi, RecursiveIteratorIterator::SELF_FIRST); $files = new RegexIterator($rii, '/\\.html$/', RecursiveRegexIterator::GET_MATCH); $process = function () use($files) { $fileInfo = $files->getInnerIterator()->current(); if (!$fileInfo->isFile()) { return true; } if ($fileInfo->getBasename('.html') === $fileInfo->getBasename()) { return true; } $file = $fileInfo->getRealPath(); $html = file_get_contents($file); if (!preg_match('#<p><img alt="[^"]*" src="[^"]+" \\/><\\/p>#s', $html)) { return true; } $html = preg_replace('#(<p><img alt="[^"]*" src="[^"]+" )(\\/><\\/p>)#s', '$1class="img-responsive"$2', $html); file_put_contents($file, $html); return true; }; iterator_apply($files, $process);
<?php function print_caps(Iterator $iterator) { echo strtoupper($iterator->current()) . "\n"; return TRUE; } $it = new ArrayIterator(array("Apples", "Bananas", "Cherries")); iterator_apply($it, "print_caps", array($it));
var_dump($arg->key()); var_dump($arg->current()); } else { var_dump($arg); } return true; } function test() { static $arg = 0; var_dump($arg++); return true; } $it = new RecursiveArrayIterator(array(1, array(21, 22), 3)); var_dump(iterator_apply($it, 'test', NULL)); echo "===ARGS===\n"; var_dump(iterator_apply($it, 'test_arg', array($it))); echo "===RECURSIVE===\n"; $it = new RecursiveIteratorIterator($it); var_dump(iterator_apply($it, 'test')); echo "===ERRORS===\n"; try { var_dump(iterator_apply($it, 'test', 1)); } catch (Error $e) { my_error_handler($e->getCode(), $e->getMessage(), $e->getFile(), $e->getLine()); } var_dump(iterator_apply($it, 'non_existing_function')); var_dump(iterator_apply($it, 'non_existing_function', NULL, 2)); ?> ===DONE===
/** * @param array $raw * * @return $this[]|self[] */ public static function create(array $raw) : array { $return = []; foreach ($raw as $postName => $fileValue) { if (!is_array($fileValue['error'])) { if ($fileValue['error'] != 4) { $return[$postName] = new File($postName, $fileValue); } } else { $keys = [$postName]; $browse = function (\RecursiveArrayIterator $iterator) use(&$browse, &$keys, &$return, $postName, $fileValue) { while ($iterator->valid()) { $arrayKeys = array_keys($iterator->getArrayCopy()); $currentKey = $arrayKeys[sizeof($arrayKeys) - 1]; $currentValue = $iterator->getArrayCopy()[$iterator->key()]; if ($iterator->hasChildren()) { $keys[] = $iterator->key(); $browse($iterator->getChildren()); } else { $names =& $fileValue['name']; $types =& $fileValue['type']; $sizes =& $fileValue['size']; $tmps =& $fileValue['tmp_name']; $errors =& $fileValue['error']; $clone = array_merge($keys, [$iterator->key()]); array_shift($clone); $returnRef =& $return[$postName]; while (!is_null($key = array_shift($clone))) { $names =& $names[$key]; $types =& $types[$key]; $sizes =& $sizes[$key]; $tmps =& $tmps[$key]; $errors =& $errors[$key]; $returnRef =& $returnRef[$key]; } if (!is_null($names) && $errors != 4) { $returnRef = new File(implode('/', $keys), ['name' => $names, 'type' => $types, 'size' => $sizes, 'tmp_name' => $tmps, 'error' => $errors]); } } // reset, iterator change tree if (!is_array($currentValue) && $currentKey == $iterator->key()) { $keys = [$postName]; } $iterator->next(); } }; $iterator = new \RecursiveArrayIterator($fileValue['name']); iterator_apply($iterator, $browse, [$iterator]); } } return $return; }
private function searchIblocks() { $i = new \RecursiveArrayIterator(array($this->filter)); iterator_apply($i, array($this, 'recursiveScan'), array($i)); return !empty($this->iblockPrimary); }
/** * @param ArrayIterator $iterator */ protected function _prepareIndexesCallback(ArrayIterator $iterator) { while ($iterator->valid()) { $index = $iterator->current(); $indexIterator = new ArrayIterator($index); iterator_apply($indexIterator, array($this, '_prepareIndexDocumentCallback'), array($indexIterator)); $indexedEntity = $this->_addAdditonalIndexParameters($index['sku']); $this->getClusterManager()->indexDocument($this->getIndexerEntityType(), $this->getIndexerEntityProvider()->getStore(), $indexedEntity->getId(), $this->_currentIndexedDocument); $iterator->next(); } }
<?php class Foo { public function __call($name, $params) { echo "Called {$name}.\n"; return true; } } $it = new ArrayIterator(array(1, 2, 3)); iterator_apply($it, array(new Foo(), "foobar")); ?> ===DONE=== <?php exit(0);
<?php $data = array('banana', 'mela', 'pera'); $iterator = new ArrayIterator($data); function upper(Iterator $iterator) { echo strtoupper($iterator->current()), PHP_EOL; return true; } iterator_apply($iterator, 'upper', array($iterator));
$strip = implode(DIRECTORY_SEPARATOR, $segments); } $prefixWithDir = $opts->getOption('d'); if (!$usingStdout) { echo "Creating class file map for library in '{$path}'..." . PHP_EOL; } // Get the ClassFileLocator, and pass it the library path $l = new \Zend\File\ClassFileLocator($path); // Iterate over each element in the path, and create a map of // classname => filename, where the filename is relative to the library path $map = new \stdClass(); $strip .= DIRECTORY_SEPARATOR; iterator_apply($l, function () use($l, $map, $strip) { $file = $l->current(); $namespace = empty($file->namespace) ? '' : $file->namespace . '\\'; $filename = str_replace($strip, '', $file->getRealpath()); $map->{$namespace . $file->classname} = $filename; return true; }); // Create a file with the class/file map. // Stupid syntax highlighters make separating < from PHP declaration necessary $map = var_export((array) $map, true); $content = <<<EOT <?php namespace {$namespace}; \$_map = {$map}; spl_autoload_register(function(\$class) use (\$_map) { if (array_key_exists(\$class, \$_map)) { require_once \$_map[\$class]; } });