/** * Get all backup files * * @return array */ public function get_files() { $backups = array(); try { $iterator = new RegexIterator( new DirectoryIterator( AI1WM_BACKUPS_PATH ), '/^(.+)-(\d+)-(\d+)-(\d+)\.wpress$/', RegexIterator::GET_MATCH ); foreach ( $iterator as $item ) { try { $backup = new Ai1wm_File; $backup->setFile( $item[0] ); $backup->setName( $item[1] ); $backup->setSize( $iterator->getSize() ); $backup->setCreatedAt( strtotime( "{$item[2]} {$item[3]}" ) ); // Add backup file $backups[] = $backup; } catch ( Exception $e ) { // Log the error Ai1wm_Log::error( 'Exception while listing backup file: ' . $e->getMessage() ); } } } catch ( Exception $e ) { $backups = array(); } // Sort backups by most recent first usort( $backups, array( $this, 'compare' ) ); return $backups; }
/** * */ public function prepare() { $this->fetched = $this->fetch(); $this->fetched->rewind(); $this->filtered = $this->filter($this->fetched); $this->filtered->rewind(); $this->sorted = $this->sort($this->filtered); $this->sorted->rewind(); }
public function testAll($testDir) { // Iterate across this dir for files matching *_test.php $directory = new RecursiveDirectoryIterator($testDir); $iterator = new RecursiveIteratorIterator($directory); $regex = new RegexIterator($iterator, '/^.+_test\\.php$/i', RecursiveRegexIterator::GET_MATCH); $regex->next(); while ($regex->valid()) { $item = $regex->current(); require_once $item[0]; $regex->next(); } }
protected static function readCommands($incHidden = false) { static $commands = array(); static $hidden = array(); if (!$commands) { $projectRoot = Meshing_Utils::getProjectRoot(); $consoleRoot = $projectRoot . Meshing_Utils::getPaths()->getPathMeshingCommands(); $directory = new RecursiveDirectoryIterator($consoleRoot); $iterator = new RecursiveIteratorIterator($directory); $regex = new RegexIterator($iterator, '/^.+\\.php$/i', RecursiveRegexIterator::GET_MATCH); $regex->next(); $i++; while ($regex->valid()) { // For safety! if ($i > 50) { break; } // Get the full pathname of the class $item = $regex->current(); $item = $item[0]; // Strip out the full path bit, and generally tidy $item = str_replace($consoleRoot . DIRECTORY_SEPARATOR, '', $item); $item = str_replace('.php', '', $item); $className = 'Meshing_Console_Command_' . str_replace(DIRECTORY_SEPARATOR, '_', $item); $item = strtolower(str_replace(DIRECTORY_SEPARATOR, ':', $item)); // Classes without this method are not commands at all $realCommand = method_exists($className, 'getDescription'); // We consult a special method to determine whether to show the command if ($realCommand) { $cmdClass = new $className(); $commands[$className] = $item; if ($cmdClass->isHiddenCommand()) { $hidden[] = $className; } } $regex->next(); } // Preserve the keys when sorting asort($commands); } // Strip out hidden commands if (!$incHidden) { foreach ($hidden as $removeClass) { unset($commands[$removeClass]); } } return $commands; }
function accept() { @preg_match_all($this->re, (string) ($this->uk ? $this->key() : $this->current()), $sub); $ret = parent::accept(); var_dump($sub == $this->current()); return $ret; }
/** * @test * @group QA * @dataProvider dirs_to_parse */ function some_files_are_missing_the_copyright_statement($dir) { $Directory = new RecursiveDirectoryIterator($dir); $Iterator = new RecursiveIteratorIterator($Directory); $Regex = new RegexIterator($Iterator, '/\\.php$/i', RecursiveRegexIterator::GET_MATCH); $result = array(); $Regex->next(); while ($Regex->valid()) { $path = $Regex->getPathname(); $copy = 'Copyright (c) 2015 Gregory Vinčić, The MIT License (MIT)'; if (!$this->file_contains($path, $copy)) { $result[] = $path; } $Regex->next(); } $this->assertEquals('', implode("\n", $result)); }
/** * Returns a regex iterator instance, starting from $dir applying the given * $pattern. * * @param string $directory * @param regex $pattern * @return \RegexIterator */ public function __construct($directory, $pattern) { $iterator = new \RecursiveIteratorIterator( new \RecursiveDirectoryIterator($directory) ); parent::__construct($iterator, $pattern); }
function __construct($file = ".*", $path = ".", $recursive = false) { $path = !$path || $path === '' ? '.' : $path; $dirIt = new RecursiveDirectoryIterator($path); if ($recursive) { $theIt = new RecursiveIteratorIterator($dirIt); } else { $theIt = new IteratorIterator($dirIt); } // $iterator = new RegexIterator($theIt, '/\\\\'.$file.'/' ,RecursiveRegexIterator::GET_MATCH); parent::__construct($theIt, '/\\\\' . $file . '/', RecursiveRegexIterator::GET_MATCH); }
public function getFileList($directory, $recursive = false) { $recursiveIteratorIterator = new \RegexIterator(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(rtrim($this->rootPath . '/' . $directory, '/')), \RecursiveIteratorIterator::SELF_FIRST), '/^((?!thumb(_[a-z]+)?).)*$/'); $jsonFileArray = array(); $thumbnailList = UploaderConfiguration::getInstance()->getThumbnails(); foreach ($recursiveIteratorIterator as $file) { /** * @var $file \SplFileInfo */ $extension = 'Dir'; if (!$file->isDir()) { $extension = ucfirst(pathinfo($file->getFilename(), PATHINFO_EXTENSION)); } // filters if ($file->getFilename() == '.' || $file->getFilename() == 'index.php' || 0 === strpos($file->getFilename(), '.')) { continue; } // set preview if image $preview = 'none'; $thumbnails = array(); if ($this->isImage($extension)) { $thumbnails = $this->getThumbnails($thumbnailList, $extension, $file, $thumbnails); $preview = current($thumbnails); if (!file_exists($this->cx->getWebsitePath() . $preview)) { $preview = ''; } } $fileInfos = array('filepath' => mb_strcut($file->getPath() . '/' . $file->getFilename(), mb_strlen($this->cx->getWebsitePath())), 'name' => $file->getFilename(), 'size' => $this->formatBytes($file->getSize()), 'cleansize' => $file->getSize(), 'extension' => ucfirst(mb_strtolower($extension)), 'preview' => $preview, 'active' => false, 'type' => $file->getType(), 'thumbnail' => $thumbnails); // filters if ($fileInfos['name'] == '.' || preg_match('/\\.thumb/', $fileInfos['name']) || $fileInfos['name'] == 'index.php' || 0 === strpos($fileInfos['name'], '.')) { continue; } $path = array($file->getFilename() => array('datainfo' => $fileInfos)); for ($depth = $recursiveIteratorIterator->getDepth() - 1; $depth >= 0; $depth--) { $path = array($recursiveIteratorIterator->getSubIterator($depth)->current()->getFilename() => $path); } $jsonFileArray = array_merge_recursive($jsonFileArray, $path); } return $jsonFileArray; }
public function getFileList($directory, $recursive = false, $readonly = false) { if (isset($this->fileListCache[$directory][$recursive][$readonly])) { return $this->fileListCache[$directory][$recursive][$readonly]; } $recursiveIteratorIterator = new \RegexIterator(new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator(rtrim($this->rootPath . '/' . $directory, '/')), \RecursiveIteratorIterator::SELF_FIRST), '/^((?!thumb(_[a-z]+)?).)*$/'); $jsonFileArray = array(); $thumbnailList = $this->cx->getMediaSourceManager()->getThumbnailGenerator()->getThumbnails(); foreach ($recursiveIteratorIterator as $file) { /** * @var $file \SplFileInfo */ $extension = 'Dir'; if (!$file->isDir()) { $extension = ucfirst(pathinfo($file->getFilename(), PATHINFO_EXTENSION)); } // filters if ($file->getFilename() == '.' || $file->getFilename() == 'index.php' || 0 === strpos($file->getFilename(), '.')) { continue; } // set preview if image $preview = 'none'; $hasPreview = false; $thumbnails = array(); if ($this->isImage($extension)) { $hasPreview = true; $thumbnails = $this->getThumbnails($thumbnailList, $extension, $file, $thumbnails); $preview = current($thumbnails); if (!file_exists($this->cx->getWebsitePath() . $preview)) { $hasPreview = false; } } $size = \FWSystem::getLiteralSizeFormat($file->getSize()); $fileInfos = array('filepath' => mb_strcut($file->getPath() . '/' . $file->getFilename(), mb_strlen($this->cx->getWebsitePath())), 'name' => $file->getFilename(), 'size' => $size ? $size : '0 B', 'cleansize' => $file->getSize(), 'extension' => ucfirst(mb_strtolower($extension)), 'preview' => $preview, 'hasPreview' => $hasPreview, 'active' => false, 'type' => $file->getType(), 'thumbnail' => $thumbnails); if ($readonly) { $fileInfos['readonly'] = true; } // filters if ($fileInfos['name'] == '.' || preg_match('/\\.thumb/', $fileInfos['name']) || $fileInfos['name'] == 'index.php' || 0 === strpos($fileInfos['name'], '.')) { continue; } $path = array($file->getFilename() => array('datainfo' => $fileInfos)); for ($depth = $recursiveIteratorIterator->getDepth() - 1; $depth >= 0; $depth--) { $path = array($recursiveIteratorIterator->getSubIterator($depth)->current()->getFilename() => $path); } $jsonFileArray = $this->array_merge_recursive($jsonFileArray, $path); } $jsonFileArray = $this->utf8EncodeArray($jsonFileArray); $this->fileListCache[$directory][$recursive][$readonly] = $jsonFileArray; return $jsonFileArray; }
/** * WpMenuPages constructor. * * @param string $pluginBaseFile Absolute path to plugin main file * @param array|Options $options An instance of {@link Options} or an array with default options * @param string $optionsBaseName In case the $options param is an array this should be a string * defining the name of the options array as stored in DB * * @throws \InvalidArgumentException If $pluginBaseFile is empty or pointing to non readable file * @throws \InvalidArgumentException If $options isn't an instance of {@link Options} and is not an array * and $optionsBaseName is empty * @throws \Exception If symlinks are used and couldn't resolve $pluginBaseFile path * @since 1.0.0 * @author Panagiotis Vagenas <*****@*****.**> */ public function __construct($pluginBaseFile, $options, $optionsBaseName = '') { if (empty($pluginBaseFile) || !file_exists($pluginBaseFile) || !is_readable($pluginBaseFile)) { throw new \InvalidArgumentException('Invalid argument $pluginBaseFile in ' . __METHOD__); } $pluginBaseFile = wp_normalize_path($pluginBaseFile); $pluginIsSymlink = strpos($pluginBaseFile, ABSPATH) !== 0; $pagesIsSymlink = strpos(__FILE__, ABSPATH) !== 0; if ($pluginIsSymlink) { $pluginFolderName = dirname(plugin_basename($pluginBaseFile)); $this->pluginBasePath = trailingslashit(WP_PLUGIN_DIR) . $pluginFolderName; $this->pluginBaseFile = trailingslashit($this->pluginBasePath) . basename($pluginBaseFile); } else { $this->pluginBasePath = dirname($pluginBaseFile); $this->pluginBaseFile = realpath($pluginBaseFile); } if ($pagesIsSymlink) { $this->basePath = dirname(dirname(dirname(__FILE__))); $this->basePathRelToPlugin = str_replace($this->pluginBasePath, '', $this->basePath); $dirItr = new \RecursiveDirectoryIterator($this->pluginBasePath, \RecursiveDirectoryIterator::FOLLOW_SYMLINKS | \RecursiveDirectoryIterator::SKIP_DOTS); $itr = new \RecursiveIteratorIterator($dirItr); $res = new \RegexIterator($itr, '/WpMenuPages\\.php/', \RecursiveIteratorIterator::LEAVES_ONLY); $res->next(); /** @var \SplFileInfo $wpMenuPagesFile */ $wpMenuPagesFile = $res->current(); if (!$wpMenuPagesFile instanceof \SplFileInfo) { // TODO Message throw new \Exception('Something went awfully wrong!'); } $this->basePath = dirname(dirname($wpMenuPagesFile->getPath())); } else { $this->basePath = dirname(dirname(dirname(__FILE__))); } $this->basePathRelToPlugin = str_replace($this->pluginBasePath, '', $this->basePath); if ($options instanceof Options) { $this->options = $options; } elseif (is_array($options) && !empty($optionsBaseName)) { $this->options = Options::getInstance($optionsBaseName, $options); } else { throw new \InvalidArgumentException('Invalid argument $options in ' . __METHOD__); } add_action('admin_init', function () { $this->pluginMetaData = get_plugin_data($this->pluginBaseFile); }); }
/** * Return all template files of a particular group as array * * @param string * @param integer * * @return array * @throws Exception */ public static function getTemplateGroupInFolders($prefix, $folders) { $templates = array(); // Find all matching templates foreach ($folders as $sourceName => $folder) { $iterator = new RecursiveDirectoryIterator($folder, RecursiveDirectoryIterator::SKIP_DOTS | RecursiveDirectoryIterator::UNIX_PATHS); $iterator = new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::LEAVES_ONLY); $iterator = new RegexIterator($iterator, '~(^|/)' . preg_quote($prefix, '~') . '.*\\.twig$~i'); /** @var RecursiveDirectoryIterator|RecursiveIteratorIterator|RegexIterator $iterator */ $iterator->next(); while ($iterator->accept()) { $templateName = $iterator->getSubPathname(); $templateName = preg_replace('#\\.[^\\.]+\\.twig$#', '', $templateName); $templates[$sourceName][$templateName] = $templateName; uksort($templates[$sourceName], 'strnatcasecmp'); $iterator->next(); } } uksort($templates, 'strnatcasecmp'); return $templates; }
/** * Returns if a given directory has tests (recursively) * * @param string $dir full path to the directory to look for phpunit tests * @param string $testtype phpunit|behat * @return bool if a given directory has tests (true) or no (false) */ private static function directory_has_tests($dir, $testtype) { if (!is_dir($dir)) { return false; } $dirite = new RecursiveDirectoryIterator($dir); $iteite = new RecursiveIteratorIterator($dirite); $regexp = self::get_regexp($testtype); $regite = new RegexIterator($iteite, $regexp); $regite->rewind(); if ($regite->valid()) { return true; } return false; }
/** * Returns if a given directory has tests (recursively) * * @param $dir string full path to the directory to look for phpunit tests * @return bool if a given directory has tests (true) or no (false) */ private static function directory_has_tests($dir) { if (!is_dir($dir)) { return false; } $dirite = new RecursiveDirectoryIterator($dir); $iteite = new RecursiveIteratorIterator($dirite); $sep = preg_quote(DIRECTORY_SEPARATOR, '|'); $regite = new RegexIterator($iteite, '|' . $sep . 'tests' . $sep . '.*_test\\.php$|'); $regite->rewind(); if ($regite->valid()) { return true; } return false; }
<div class="tabbertab" id="tabset_layout_edit_files_tab" data-icon-class="icon-signup" > <h3 class="tabberheading"> <?php echo JText::_('FLEXI_EDIT_LAYOUT_FILES'); ?> </h3> <div id="layout-filelist-container" class="span4" style="margin:0.5%;"> <span class="fcsep_level0" style="margin:0 0 12px 0; background-color:#333; "> <span class="badge"><?php echo JText::_('FLEXI_LAYOUT_FILES'); ?> </span> </span> <?php $tmpldir = JPATH_ROOT . DS . 'components' . DS . 'com_flexicontent' . DS . 'templates' . DS . $this->layout->name; $it = new RegexIterator(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($tmpldir)), '#' . $this->layout->view . '(_.*\\.|\\.)(php|xml|css|js)#i'); //$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($tmpldir)); $it->rewind(); $ext_badge = array('php' => 'success', 'xml' => 'info', 'css' => 'warning', 'js' => 'important', 'ini' => 'info'); $file_tip = array('item.css' => 'Contains CSS specific to this item layout', 'category.css' => 'Contains CSS specific to this category layout', 'item.xml' => 'Layout\'s structure: including display parameters, field positions, file list, etc', 'category.xml' => 'Layout\'s structure: including display parameters, field positions, file list, etc', 'item.php' => 'PHP/HTML to display item\'s fields', 'category_items.php' => 'Item list filtering form, and Item loop (displaying every item)', 'category.php' => 'Top-level container of the layout', 'category_category.php' => 'Displays category information: title, description, image, etc', 'category_category_html5.php' => 'Displays category information: title, description, image, etc', 'category_alpha.php' => 'Displays the alphanumerical index of the item list', 'category_peercategories.php' => 'Displays the peer categories list', 'category_subcategories.php' => 'Display the sub-categories list'); $file_tip['item_html5.php'] = $file_tip['item.php'] . ' (HTML5 version)'; $file_tip['category_items_html5.php'] = $file_tip['category_items.php'] . ' (HTML5 version)'; $file_tip['category_html5.php'] = $file_tip['category.php'] . ' (HTML5 version)'; $file_tip['category_category_html5.php'] = $file_tip['category_category.php'] . ' (HTML5 version)'; $file_tip['category_alpha_html5.php'] = $file_tip['category_alpha.php'] . ' (HTML5 version)'; $file_tip['category_peercategories_html5.php'] = $file_tip['category_peercategories.php'] . ' (HTML5 version)'; $file_tip['category_subcategories_html5.php'] = $file_tip['category_subcategories.php'] . ' (HTML5 version)'; $file_tip_extra = array('item.xml' => 'This file contains layout\' s structure: including <br/> - <b>display parameters, field positions, file list, etc</b>, <br/> - you can add extra parameters/positions, <br/>-- if you add a new position, you will need to also add the dispay -LOOP- of the new position inside files: <br/><b>item.php</b> <br/><b>item_html5.php</b> <br/><br/>(click to edit file and then use the code button)', 'category.xml' => 'This file contains layout\' s structure: including <br/> - <b>display parameters, field positions, file list, etc</b>, <br/> - you can add extra parameters/positions, <br/>-- if you add a new position, you will need to also add the dispay -LOOP- of the new position inside files: <br/><b>category_items.php</b> <br/><b>category_items_html5.php</b> <br/><br/>(click to edit file and then use the code button)', 'item.php' => 'This file display the item, thus has display LOOPs of for every position to show fields of every position, if you add new position in the XML file, then make sure that you ADD the display loop here <br/><br/>(click to edit file and then use the code button)', 'category_items.php' => 'This file includes: <br/><br/>- Item list filtering form, <br/>- Item loop (that displays every item\'s fields), <br/><br/>if you add new field position in the XML file, then make sure that you ADD here, the display loop that displays the fields of the position <br/><br/>(click to edit file and then use the code button)'); $file_tip_extra['item_html5.php'] = $file_tip_extra['item.php']; $file_tip_extra['category_items_html5.php'] = $file_tip_extra['category_items.php']; $file_code_btns = array('item.xml' => array('fieldPosXML' => 1, 'paramTextXML' => 1, 'paramRadioXML' => 1, 'paramSelectXML' => 1), 'category.xml' => array('fieldPosXML' => 1, 'paramTextXML' => 1, 'paramRadioXML' => 1, 'paramSelectXML' => 1), 'item.php' => array('itemPosHTML' => 1, 'itemFieldDisplay' => 1), 'category_items.php' => array('catPosHTML' => 1, 'catFieldDisplay' => 1));
/** * Method to get files having the given extensions from a given folder * * @access private * @return integer * @since 1.0 */ function getFilesFromPath($itemid, $fieldid, $append_item = 1, $append_field = 0, $folder_param_name = 'dir', $exts = 'bmp,csv,doc,docx,gif,ico,jpg,jpeg,odg,odp,ods,odt,pdf,png,ppt,pptx,swf,txt,xcf,xls,xlsx,zip,ics') { $app = JFactory::getApplication(); $option = JRequest::getVar('option'); $imageexts = array('jpg', 'gif', 'png', 'bmp', 'jpeg'); // Common image extensions $gallery_folder = $this->getFieldFolderPath($itemid, $fieldid, $append_item, $append_field, $folder_param_name); //echo $gallery_folder ."<br />"; // Create folder for current language if (!is_dir($gallery_folder)) { mkdir($gallery_folder, $mode = 0755, $recursive = true); } // Get file list according to filtering $exts = preg_replace("/[\\s]*,[\\s]*/", '|', $exts); $it = new RegexIterator(new RecursiveIteratorIterator(new RecursiveDirectoryIterator($gallery_folder)), '#(.*\\.)(' . $exts . ')#i'); $it->rewind(); // Get file information $rows = array(); $i = 1; while ($it->valid()) { if ($it->isDot()) { $it->next(); continue; } $filesubpath = $it->getSubPathName(); // filename including the folder subpath $filepath = $it->key(); $pinfo = pathinfo($filepath); $row = new stdClass(); $row->ext = $pinfo['extension']; $row->filename = $filesubpath; //$pinfo['filename'].".".$pinfo['extension']; $row->size = sprintf("%.0f KB", filesize($filepath) / 1024); $row->altname = $pinfo['filename']; $row->uploader = '-'; $row->uploaded = date("F d Y H:i:s.", filectime($filepath)); $row->id = $i; if (in_array(strtolower($row->ext), $imageexts)) { $row->icon = JURI::root() . "components/com_flexicontent/assets/images/mime-icon-16/image.png"; } elseif (file_exists(JPATH_SITE . "/components/com_flexicontent/assets/images/mime-icon-16/" . $row->ext . ".png")) { $row->icon = JURI::root() . "components/com_flexicontent/assets/images/mime-icon-16/" . $row->ext . ".png"; } else { $row->icon = JURI::root() . "components/com_flexicontent/assets/images/mime-icon-16/unknown.png"; } $rows[] = $row; $i++; $it->next(); } return $rows; }
public function accept() { return !parent::accept(); }
<?php $array = array('foo', 'bar', 'baz'); $iterator = new ArrayIterator($array); $regexIterator = new RegexIterator($iterator, "/f/"); var_dump($regexIterator->getMode() === RegexIterator::MATCH); $regexIterator->setMode(RegexIterator::MATCH); var_dump($regexIterator->getMode() === RegexIterator::MATCH); $regexIterator->setMode(RegexIterator::GET_MATCH); var_dump($regexIterator->getMode() === RegexIterator::GET_MATCH); $regexIterator->setMode(RegexIterator::ALL_MATCHES); var_dump($regexIterator->getMode() === RegexIterator::ALL_MATCHES); $regexIterator->setMode(RegexIterator::SPLIT); var_dump($regexIterator->getMode() === RegexIterator::SPLIT);
private function folderContains($folderPath, $filePattern) { if (!is_dir($folderPath)) { return false; } $directoryIterator = new \RecursiveDirectoryIterator($folderPath); $flatIterator = new \RecursiveIteratorIterator($directoryIterator); $fileIterator = new \RegexIterator($flatIterator, $filePattern, \RegexIterator::GET_MATCH); $fileIterator->rewind(); return $fileIterator->valid(); }
<?php $array = array('foo', 'bar', 'baz'); $iterator = new ArrayIterator($array); $regexIterator = new RegexIterator($iterator, "/f/", null, RegexIterator::USE_KEY); var_dump($regexIterator->getFlags() === RegexIterator::USE_KEY); // Test a change in flags, there's only one class constant so it has to be another int value $regexIterator->setFlags(3); var_dump($regexIterator->getFlags() === RegexIterator::USE_KEY); $regexIterator->setFlags(RegexIterator::USE_KEY); var_dump($regexIterator->getFlags() === RegexIterator::USE_KEY);
<?php $x = new RegexIterator(new ArrayIterator(range(1, 10)), '/\\d/'); var_dump($x->accept());
<?php $data = array('Frutto: Mela', 'Frutto: Pera', 'Frutto: Banana', 'Verdura: Insalata'); $iterator = new RegexIterator(new ArrayIterator($data), '/^Frutto: /'); print_r(iterator_to_array($iterator)); $iterator->setMode(RegexIterator::REPLACE); print_r(iterator_to_array($iterator)); $iterator = new RegexIterator(new ArrayIterator($data), '/(^Frutto): (.*)/'); $iterator->setMode(RegexIterator::REPLACE); $iterator->replacement = '$2: $1'; print_r(iterator_to_array($iterator));
echo '>' . $this->_valeur . '</div>' . PHP_EOL; } } ?> <style> .vert{ color: green; margin-left: 25px; } .bleu{color: blue; } </style> <h2>Mon Filtre avec while</h2> <?php $DirectoryIterator = new MonDI('./'); //print_r($DirectoryIterator); $Iterator_iterator = new MonFilter($DirectoryIterator); $Iterator_iterator->rewind(); while ($Iterator_iterator->valid()) { $Iterator_iterator->afficher_valeur(); $Iterator_iterator->next(); } echo '<h2>RegexIterator avec while</h2>'; $RegexIterator = new RegexIterator($DirectoryIterator, '#rep#'); $RegexIterator->rewind(); while ($RegexIterator->valid()) { echo $RegexIterator->current()->getFilename() . '<br />'; $RegexIterator->next(); } echo '<h2>RegexIterator avec foreach</h2>'; foreach ($RegexIterator as $Resultat) { echo $Resultat . '<br />'; }
<?php $array = array('cat', 'hat', 'sat'); $iterator = new ArrayIterator($array); # Simple regex $regexIterator = new RegexIterator($iterator, '/.at/'); var_dump($regexIterator->getRegex()); # Empty regular expression $regexIterator = new RegexIterator($iterator, '//'); var_dump($regexIterator->getRegex()); # "Complex" email regular expression $regexIterator = new RegexIterator($iterator, '|\\b[A-Z0-9._%-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b|'); var_dump($regexIterator->getRegex());
private function findFile(string $fileName, string $extension) { $iterator = new \RegexIterator(new \DirectoryIterator($this->downloadPath), sprintf('/%s\\.%s$/ui', preg_quote(pathinfo($fileName, PATHINFO_FILENAME), '/'), '(' . $extension . ')'), \RegexIterator::GET_MATCH); $iterator->rewind(); return $iterator->current()[0]; }
<?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);
/** * ( excerpt from * http://php.net/manual/en/recursiveregexiterator.construct.php ) * * Creates a new regular expression iterator. * * @iterator mixed The recursive iterator to apply this regex filter * to. * @regex mixed The regular expression to match. * @mode mixed Operation mode, see RegexIterator::setMode() for a * list of modes. * @flags mixed Special flags, see RegexIterator::setFlags() for a * list of available flags. * @preg_flags mixed The regular expression flags. These flags depend on * the operation mode parameter: * - RecursiveRegexIterator::ALL_MATCHES: See preg_match_all(). * - RecursiveRegexIterator::GET_MATCH: See preg_match(). * - RecursiveRegexIterator::MATCH: See preg_match(). * - RecursiveRegexIterator::REPLACE: none. * - RecursiveRegexIterator::SPLIT: See preg_split(). */ public function __construct(RecursiveIterator $iterator, $regex, $mode = self::MATCH, $flags = 0, $preg_flags = 0) { parent::__construct($iterator, $regex, $mode, $flags, $preg_flags); }
<?php $Directory = new RecursiveDirectoryIterator('../'); $Iterator = new RecursiveIteratorIterator($Directory); $Regex = new RegexIterator($Iterator, '/^.+\\.php$/i', RecursiveRegexIterator::GET_MATCH); $inner = $Regex->getInnerIterator(); $files = array_keys(iterator_to_array($inner)); foreach ($files as $file) { if (pathinfo($file, PATHINFO_EXTENSION) == "php" and in_array("model", explode("/", $file)) === true) { include_once $file; } // if (pathinfo($file, PATHINFO_EXTENSION) == "php" // and in_array("model", explode("/", $file)) === true) { // echo $file; // } }
public function accept() { return $this->hasChildren() || parent::accept(); }
/** * Find templates/resources for the given path. * * <p><strong>Example:</strong></p> * * <p>Find all styles in a particular folder (<em>style</em>).</p> * <code><pre> * $styles = $this->find('style', '/css/'); * foreach ($styles as $name => $url) { * echo '<link rel="stylesheet" type="text/css" href="'.$url.'"/>'; * } * </pre></code> * * <p>Alternatively, using the build in $resource manager, it would look like this:</p> * <code><pre> * $styles = $this->find('style', '/css/'); * foreach ($styles as $name => $url) { * $resourceManager->cssFile($name); * } * </pre></code> * * @param string path The base path, relative to the template/resource path. * @param string regexp Optional filter expression; default is <code>null</code> for none. * @param string type The resource type; default is <code>View::RESOURCE</code>. * @return array A map of matching filenames. */ public function find($path, $regexp = null, $type = View::RESOURCE) { list($path, $type) = $this->resolveType($path, $type); $locations = $this->getLocationsFor($type); // iterate in ascending priority, so the more important come first $files = array(); foreach ($locations as $location) { $base = $location . '/' . $path; if (file_exists($base) && is_dir($base)) { $it = new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($base)); if (null != $regexp) { $it = new \RegexIterator($it, $regexp, \RegexIterator::MATCH); } for ($it->rewind(); $it->valid(); $it->next()) { $name = str_replace(array($base, '\\'), array('', '/'), $it->current()->getPathname()); $files[] = $name; } } } return $files; }