/** * @param $path * @return mixed|string */ private function getFile($path) { $returnView = $this->viewFolder . $path . '.php'; if (!file_exists($returnView)) { $dir = $path; $dir = explode('/', $dir); unset($dir[count($dir) - 1]); $dir = implode('/', $dir); $it = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->viewFolder . $dir)); while ($it->valid()) { if (!$it->isDot()) { $cache['SelectView'] = strrev($path); $cache['SelectView'] = explode("/", $cache['SelectView'])[0]; $cache['SelectView'] = strrev($cache['SelectView']); $cache['ReturnView'] = explode(".", $it->key()); unset($cache['ReturnView'][count($cache['ReturnView']) - 1]); $cache['ReturnView'] = implode('.', $cache['ReturnView']); $cache['ReturnView'] = explode("\\", $cache['ReturnView']); $cache['ReturnView'] = $cache['ReturnView'][count($cache['ReturnView']) - 1]; if ($cache['ReturnView'] == $cache['SelectView']) { $returnView = $it->key(); } } $it->next(); } if (!isset($returnView)) { die('Can not find a file matching these arguments: getView("' . $this->getPath($path, TRUE) . '")'); } return $returnView; } }
/** * Function to start a scan in a directory. * @return Array * @throws DirectoryNotFoundException */ public static function scanDir($parentDirectory) { $occurences = array(array()); //if the directory/file does not exists, then throw and error. if (!file_exists($parentDirectory)) { throw new DirectoryORFileNotFoundException("ERROR: Directory not found!"); } //get the list of all the files inside this directory. $allFiles = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($parentDirectory)); $fileList = array(); //remove (.), (..) and directories from the list of all files so that only files are left. while ($allFiles->valid()) { if (!$allFiles->isDot()) { if (!is_dir($allFiles->key())) { array_push($fileList, $allFiles->key()); } } $allFiles->next(); } $i = 0; foreach ($fileList as $file) { if (pathinfo($file, PATHINFO_EXTENSION) != "php") { continue; } $occurences[$i]['file'] = realpath($file); $occurences[$i]['result'] = Scanner::scanFile($file); $i++; } return $occurences; }
/** * @throws \Seitenbau\FileSystem\FileSystemException */ public static function copyDir($source, $destination) { if (!is_dir($source)) { throw new FileSystemException('Sourcedir "' . $source . '" does not exists'); } $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($source), \RecursiveIteratorIterator::SELF_FIRST); if (!self::createDirIfNotExists($destination)) { return false; } // Verzeichnis rekursiv durchlaufen while ($iterator->valid()) { if (!$iterator->isDot()) { if ($iterator->current()->isDir()) { // relativen Teil des Pfad auslesen $relDir = str_replace($source, '', $iterator->key()); // Ziel-Verzeichnis erstellen if (!self::createDirIfNotExists($destination . $relDir)) { return false; } } elseif ($iterator->current()->isFile()) { $destinationFile = $destination . str_replace($source, '', $iterator->key()); if (!copy($iterator->key(), $destinationFile)) { return false; } } } $iterator->next(); } return true; }
public static function DirectoryContent($Directory, $UserLanguage) { $ReadDirectory = $Directory . str_replace('.language', '', $UserLanguage); $Iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($ReadDirectory)); $FilesArray = array(); while ($Iterator->valid()) { if (!$Iterator->isDot()) { $FilesArray[] = array('FileLink' => $Iterator->key(), 'FileName' => $Iterator->getSubPathName(), 'SmallFileName' => strtolower(str_replace('.language', '', $Iterator->getSubPathName())), 'LinesCount' => File::CountLines($Iterator->key())); } $Iterator->next(); } return $FilesArray; }
/** * Get Test Files * * @param null $directory * @param null $excludes * @return array */ public static function getTestFiles($directory = null, $excludes = null) { if (is_array($directory)) { $files = array(); foreach ($directory as $d) { $files = array_merge($files, self::getTestFiles($d, $excludes)); } return array_unique($files); } if ($excludes !== null) { $excludes = self::getTestFiles((array) $excludes); } if ($directory === null || $directory !== realpath($directory)) { $basePath = App::pluginPath('DebugKit') . 'Test' . DS . 'Case' . DS; $directory = str_replace(DS . DS, DS, $basePath . $directory); } $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)); $files = array(); while ($it->valid()) { if (!$it->isDot()) { $file = $it->key(); if (preg_match('|Test\\.php$|', $file) && $file !== __FILE__ && !preg_match('|^All.+?\\.php$|', basename($file)) && ($excludes === null || !in_array($file, $excludes))) { $files[] = $file; } } $it->next(); } return $files; }
function array_flatten(array $array, $key_separator = '/') { $result = array(); // a stack of strings $keys = array(); $prev_depth = -1; $iter = new RecursiveIteratorIterator(new RecursiveArrayIterator($array), RecursiveIteratorIterator::SELF_FIRST); // rewind() is necessary for ($iter->rewind(); $iter->valid(); $iter->next()) { $curr_depth = $iter->getDepth(); $diff_depth = $prev_depth - $curr_depth + 1; //##### TODO: It would be nice to do this with a single function. while ($diff_depth > 0) { array_pop($keys); --$diff_depth; } /* Note: http://bugs.php.net/bug.php?id=52425 array_shift/array_pop: add parameter that tells how many to elements to pop */ array_push($keys, $iter->key()); if (is_scalar($iter->current())) { $result[implode($key_separator, $keys)] = $iter->current(); } $prev_depth = $curr_depth; } return $result; }
private static function searchByContent(\RecursiveIteratorIterator $file, $query) { if (!$file->isDot() && is_readable($file->key())) { try { $handle = fopen($file->key(), 'r'); if ($handle) { while (!feof($handle)) { if (strpos(fgets($handle), $query) !== false) { return true; } } } } catch (ContextErrorException $e) { } } return false; }
function key() { if ($this->rit_flags & self::BYPASS_KEY) { return parent::key(); } else { return $this->getPrefix() . parent::key() . $this->getPostfix(); } }
public function addDirectory($path, $localpath = null, $exclude_hidden = true) { if ($localpath === null) { $localpath = $path; } $localpath = rtrim($localpath, '/\\'); $path = rtrim($path, '/\\'); $iter = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST); while ($iter->valid()) { if (!$iter->isDot() && !$iter->isDir()) { if (!$exclude_hidden || !$this->is_path_hidden($iter->key())) { $this->addFile($iter->key(), $localpath . DIRECTORY_SEPARATOR . $iter->getSubPathName()); } } $iter->next(); } }
public function buildTree($last_created = '') { $dir = new RecursiveDirectoryIterator($this->root_dir, FilesystemIterator::SKIP_DOTS); $this->filter($dir); $it = new RecursiveIteratorIterator($this->filter, RecursiveIteratorIterator::SELF_FIRST, RecursiveIteratorIterator::CATCH_GET_CHILD); $tree = array(); foreach ($it as $fileinfo) { $name = $fileinfo->getFilename(); $sub_path_name = $it->getSubPathName(); $parts = explode(DIRECTORY_SEPARATOR, $sub_path_name); array_pop($parts); $parentArr =& $tree; //go deep in the file|dir path foreach ($parts as $part) { $parentArr =& $parentArr['dirs'][$part]; } if ($fileinfo->isDir()) { //statistics $statistics = $this->countChildren($it->key()); $total_files = round($statistics['files'] / $this->count_suffix); // Add the final part to the structure if (!empty($last_created) && $it->key() == $last_created) { $parentArr['dirs'][$name] = array('f' => $name, 'c-folders' => $statistics['folders'], 'c-files' => $total_files, 'last' => true); } else { $parentArr['dirs'][$name] = array('f' => $name, 'c-folders' => $statistics['folders'], 'c-files' => $total_files, 'ffff' => $statistics['files'] . '..' . $this->count_suffix); } } else { // Add some file info to the structure if ($fileinfo->isLink()) { $realpath = $fileinfo->getRealPath(); $filesize = filesize($realpath); $filemtime = filemtime($realpath); } else { $filesize = $fileinfo->getSize(); $filemtime = $fileinfo->getMTime(); } $file_path = $it->getSubPath() == '' ? '/' : '/' . $it->getSubPath() . '/'; $parentArr['files'][] = array('filename' => $name, 'filesize' => $this->fileSizeConvert($filesize), 'date' => date("d-m-Y H:i", $filemtime), 'relative_path' => $file_path); } } unset($parentArr); $this->sortArray($tree); return $tree; }
public static function GetDirectoryContent($Directory, $SearchForFormat = null) { $Iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($Directory)); $FilesArray = array(); while ($Iterator->valid()) { if (!$Iterator->isDot()) { if ($SearchForFormat != null) { $Exploded = explode('.', $Iterator->getSubPathName()); if ($Exploded[1] == $SearchForFormat) { $FilesArray[] = array('FileLink' => $Iterator->key(), 'FileName' => $Iterator->getSubPathName()); } } else { $FilesArray[] = array('FileLink' => $Iterator->key(), 'FileName' => $Iterator->getSubPathName()); } } $Iterator->next(); } return $FilesArray; }
function current() { $current = parent::current(); $key = parent::key(); $retValue = "<td style='width:150px;border:1px solid black;'>\n\t\t\t \t\t \t<input "; if ($key == 'Id') { $retValue .= "readonly "; } $retValue .= "type='text' name='" . htmlspecialchars($key) . "' value='" . htmlspecialchars($current) . "'>\n\t\t\t \t\t</td>"; return $retValue; }
public static function GetDirectoryContent($Directory) { $Iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($Directory)); $FilesArray = array(); while ($Iterator->valid()) { if (!$Iterator->isDot()) { $FilesArray[] = array('FileLink' => $Iterator->key(), 'FileName' => $Iterator->getSubPathName()); } $Iterator->next(); } return $FilesArray; }
private function get_all_files() { $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($this->input_dir)); $result = array(); while ($iterator->valid()) { if (!$iterator->isDot()) { $result[$iterator->getSubPath()][] = $iterator->key(); } $iterator->next(); } return $result; }
public static function addTestDirectoryRecursive(PHPUnit_Framework_TestSuite $suite, $directory) { $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory)); while ($it->valid()) { if (!$it->isDot()) { $file = $it->key(); if (preg_match('|Test\\.php$|', $file) && $file !== __FILE__) { $suite->addTestFile($file); } } $it->next(); } }
/** * @param $path * @return mixed|string */ private function getFile($path) { $returnView = $this->viewFolder . $path . '.php'; if (!file_exists($returnView)) { $returnView = null; $dir = $path; $dir = explode('/', $dir); unset($dir[count($dir) - 1]); $dir = implode('/', $dir); $it = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($this->viewFolder . $dir)); while ($it->valid()) { if (!$it->isDot()) { //Reverse requested file $cache['SelectView'] = strrev($path); // Get the last entry $cache['SelectView'] = explode("/", $cache['SelectView'])[0]; //Reverse againg for getting it the right way round $cache['SelectView'] = strrev($cache['SelectView']); //Get current position and remove file ending $cache['ReturnView'] = explode(".", $it->key()); unset($cache['ReturnView'][count($cache['ReturnView']) - 1]); $cache['ReturnView'] = implode('.', $cache['ReturnView']); //Workaround: Windows file paths to unix file paths $cache['ReturnView'] = str_replace("\\", "/", $cache['ReturnView']); //Gets the last element of the file path $cache['ReturnView'] = explode("/", $cache['ReturnView']); $cache['ReturnView'] = $cache['ReturnView'][count($cache['ReturnView']) - 1]; if ($cache['ReturnView'] == $cache['SelectView']) { $returnView = $it->key(); } } $it->next(); } if (!isset($returnView)) { die('Can not find a file matching these arguments: getView("' . $this->getPath($path, TRUE) . '")'); } return $returnView; } }
public static function flatArray( $needle = null, $haystack = array( ) ) { $iterator = new RecursiveIteratorIterator( new RecursiveArrayIterator( $haystack ) ); $elements = array( ); foreach( $iterator as $element ) { if( is_null( $needle ) || $iterator->key() == $needle ) { $elements[] = $element; } } return $elements; }
/** * Searches value inside a multidimensional array, returning its index * * Original function by "giulio provasi" (link below) * * @param mixed|array $haystack * The haystack to search * * @param mixed $needle * The needle we are looking for * * @param mixed|optional $index * Allow to define a specific index where the data will be searched * * @return integer|string * If given needle can be found in given haystack, its index will * be returned. Otherwise, -1 will * * @see http://www.php.net/manual/en/function.array-search.php#97645 */ public static function search($haystack, $needle, $index = NULL) { if (is_null($haystack)) { return -1; } $arrayIterator = new \RecursiveArrayIterator($haystack); $iterator = new \RecursiveIteratorIterator($arrayIterator); while ($iterator->valid()) { if ((isset($index) and $iterator->key() == $index or !isset($index)) and $iterator->current() == $needle) { return $arrayIterator->key(); } $iterator->next(); } return -1; }
protected function trackPattern($pattern) { $directory = pathinfo($pattern, PATHINFO_DIRNAME); $extension = pathinfo($pattern, PATHINFO_EXTENSION); $iterator = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($directory)); while ($iterator->valid()) { $file = $iterator->key(); $iterator->next(); if ($iterator->isDot()) { continue; } if ($extension == pathinfo($file, PATHINFO_EXTENSION)) { $this->trackFile($file); } } }
/** * Execute the command. * * @return void * * @since 1.0 */ public function execute() { $this->getApplication()->outputTitle('Make Documentation'); $this->usePBar = $this->getApplication()->get('cli-application.progress-bar'); if ($this->getApplication()->input->get('noprogress')) { $this->usePBar = false; } $this->github = $this->getContainer()->get('gitHub'); $this->getApplication()->displayGitHubRateLimit(); /* @type \Joomla\Database\DatabaseDriver $db */ $db = $this->getContainer()->get('db'); $docuBase = JPATH_ROOT . '/Documentation'; /* @type \RecursiveDirectoryIterator $it */ $it = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($docuBase, \FilesystemIterator::SKIP_DOTS)); $this->out('Compiling documentation in: ' . $docuBase)->out(); $table = new ArticlesTable($db); // @todo compile the md text here. $table->setGitHub($this->github); while ($it->valid()) { if ($it->isDir()) { $it->next(); continue; } $file = new \stdClass(); $file->filename = $it->getFilename(); $path = $it->getSubPath(); $page = substr($it->getFilename(), 0, strrpos($it->getFilename(), '.')); $this->debugOut('Compiling: ' . $page); $table->reset(); $table->{$table->getKeyName()} = null; try { $table->load(array('alias' => $page, 'path' => $path)); } catch (\RuntimeException $e) { // New item } $table->is_file = '1'; $table->path = $it->getSubPath(); $table->alias = $page; $table->text_md = file_get_contents($it->key()); $table->store(); $this->out('.', false); $it->next(); } $this->out()->out('Finished =;)'); }
public function getHelpers($module) { try { $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($module . '/Helper')); } catch (UnexpectedValueException $e) { Mage::Log($e->getMessage()); return ''; } $options = array(); while ($it->valid()) { if (!$it->isDot()) { $label = strtolower(str_replace('.php', '', str_replace('/', '_', $it->getSubPathName()))); $options[$it->key() . '=>' . $label] = $label; } $it->next(); } return $this->_toOptionsFromHash($options); }
private function findControllers() { $path = constant('APPLICATION_PATH') . '/modules'; $found = []; $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)); $it->rewind(); while ($it->valid()) { if (!$it->isDot()) { if (false !== strpos($it->getSubPathName(), 'Controller') && false == strpos($it->getSubPathName(), 'Abstract')) { //echo 'SubPathName: ' . $it->getSubPathName() . "\n"; //echo 'SubPath: ' . $it->getSubPath() . "\n"; //echo 'Key: ' . $it->key() . "\n\n"; $found[] = $it->key(); } } $it->next(); } return $found; }
/** * Generate source-file tags to copy all resources from given dir. * * @param type $dir Dir path relative to $this->basePath. * @param array $options * <li>ident - ident chanracters. */ public function sourceFiles($dir, $options = array()) { //ob_end_clean(); if (!isset($options['indent'])) { $options['indent'] = ""; } $path = $this->basePath . $dir; $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)); while ($it->valid()) { if (!$it->isDot()) { $filename = strtr($it->key(), '\\', '/'); if (isset($options['ignorePattern']) && preg_match($options['ignorePattern'], $filename)) { $this->perror("\nignored {$filename}"); $it->next(); continue; } $targetDir = preg_replace('#.+LibraryProject/(.+?)/[^/]+$#', '$1', $filename); echo "\n{$options['indent']}<source-file src=\"{$filename}\" target-dir=\"{$targetDir}\"/>"; } $it->next(); } echo "\n"; //exit; }
/** * Executes the command * @param InputInterface $input The Input Interface * @param OutputInterface $output The Output Interface * @return void */ protected function execute(InputInterface $input, OutputInterface $output) { $output->writeln(''); $output->writeln('<info>---------------</info>'); $output->writeln('ICS File Merger'); $output->writeln('<info>---------------</info>'); $output->writeln(''); // -------------------------------------------------------------------------- // Get variables $srcDir = $input->getOption('src'); $destDir = $input->getOption('dest'); $fileName = $input->getOption('file'); // -------------------------------------------------------------------------- // Test source directory if (!is_dir($destDir)) { $output->writeln('<error>Source directory does not exist</error>'); $output->writeln($srcDir); $output->writeln(''); return; } // Test output destination if (!is_writable($destDir)) { $output->writeln('<error>Destination is not writeable</error>'); $output->writeln($destDir); $output->writeln(''); return; } // -------------------------------------------------------------------------- // Look for .ics files $output->writeln('<info>Searching for .ics in:</info> ' . $srcDir); $it = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($srcDir)); $numFiles = 0; $it->rewind(); while ($it->valid()) { if (!$it->isDot() && strtolower(substr($it->key(), -4)) === '.ics') { $numFiles++; } $it->next(); } if ($numFiles === 0) { $output->writeln('<info>Did not find any .ics files</info>'); $output->writeln(''); return; } $output->writeln('<info>Found ' . $numFiles . ' .ics files</info>'); // -------------------------------------------------------------------------- // Begin merging files $output->writeln(''); $output->writeln('<info>Merging .ics files</info>'); $output->writeln(''); // Create the merge file and write the initial lines to it if (!$this->makeFile($destDir, $fileName)) { $output->writeln('<error>Failed to create merge file</error>'); $output->writeln(''); return; } // write file header $this->writeFileLine('BEGIN:VCALENDAR'); $this->writeFileLine('VERSION:2.0'); $this->writeFileLine('PRODID:XXX'); $this->writeFileLine('CALSCALE:GREGORIAN'); // Set up the progress helper $progress = $this->getHelper('progress'); $progress->start($output, $numFiles); $it->rewind(); while ($it->valid()) { if (!$it->isDot() && strtolower(substr($it->key(), -4)) === '.ics') { // Open the file and extract the event data $fileContents = file_get_contents($it->key()); if (!empty($fileContents)) { preg_match_all('/BEGIN\\:VEVENT(.*?)END\\:VEVENT/s', $fileContents, $matches); if (!empty($matches[1])) { foreach ($matches[1] as $event) { $this->writeFileLine('BEGIN:VEVENT'); $lines = explode("\r\n", $event); $lines = array_map('trim', $lines); $lines = array_filter($lines); foreach ($lines as $line) { $this->writeFileLine($line); } $this->writeFileLine('END:VEVENT'); } } } $progress->advance(); } $it->next(); } $progress->finish(); // Write file footer $this->writeFileLine('END:VCALENDAR'); $output->writeln(''); $output->writeln('<info>Completed merging .ics files</info>'); $output->writeln('<info>Output available at:</info> ' . $destDir); $output->writeln(''); }
function get_script_file_array($folder) { $files = array(); $it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($folder)); //TODO: make this configurable / test with a lot of websites $it->setMaxDepth(2); // this will save a LOT of time //bad coding if image used in file other than css $ext = array('.css', '.js', '.html', '.htm', '.php', '.php4', '.php5'); while ($it->valid()) { if (!$it->isDot()) { if ($this->strposa($it->key(), $ext) !== false) { //FB::log($it->key()); //$filename = $it->getFilename(); //array_push($files, $filename); array_push($files, $basedir = $it->key()); //str_replace('\\', '/', $it->key())); //$it->getSubPathName(), $it->getSubPath() } } $it->next(); } return $files; }
/** * performs a search in a nested array * @param array $haystack the array to be searched * @param string $needle the search string * @param string $index optional, only search this key name * @return mixed the key of the matching field, otherwise false * * performs a search in a nested array * * taken from http://www.php.net/manual/en/function.array-search.php#97645 */ public static function recursiveArraySearch($haystack, $needle, $index = null) { $aIt = new RecursiveArrayIterator($haystack); $it = new RecursiveIteratorIterator($aIt); while ($it->valid()) { if ((isset($index) and $it->key() == $index or !isset($index)) and $it->current() == $needle) { return $aIt->key(); } $it->next(); } return false; }
/** * {@inheritdoc} */ public function key() { $keys = $this->stack; $keys[] = parent::key(); return implode($this->keySeparator, $keys); }
<?php $data = array(1 => 'val1', array(2 => 'val2', array(3 => 'val3')), 4 => 'val4'); $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($data)); foreach ($iterator as $foo) { $key = $iterator->key(); echo "update {$key}\n"; var_dump($iterator->getInnerIterator()); $iterator->offsetSet($key, 'alter'); var_dump($iterator->getInnerIterator()); } $copy = $iterator->getArrayCopy(); var_dump($copy);
function array_get($array, $searched, $index) { $aIt = new RecursiveArrayIterator($array); $it = new RecursiveIteratorIterator($aIt); while ($it->valid()) { if ((isset($index) and $it->key() == $index or !isset($index)) and $it->current() == $searched) { $c = $aIt->current(); return $c; // return $c[$key]; } $it->next(); } return FALSE; }
/** * * Search for needle in a recursive array * @author http://www.php.net/manual/en/function.array-search.php#97645 * * @param $haystack * @param $needle * @param $index */ function rarray_search($needle, $haystack, $index = null) { $aIt = new RecursiveArrayIterator($haystack); $it = new RecursiveIteratorIterator($aIt); // Tar bort ".www" om det finns för bättre jämföring $needle = preg_replace('/\bwww./', '', $needle); while($it->valid()) { // Tar bort ".www" om det finns för bättre jämföring $current = preg_replace('/\bwww./', '', $it->current()); if (((isset($index) AND ($it->key() == $index)) OR (!isset($index))) AND ($current == $needle)) { return $aIt->key(); } $it->next(); } return FALSE; }