Adds rules that files must match.

You can use patterns (delimited with / sign), globs or simple strings.

$collection->names(['*.php'])
$collection->names(['/\.php$/']) // same as above
$collection->names(['test.php'])
502523
public function names(array $patterns): self
    {
        $filter = new Iterator\FilenameFilterIterator($this->getIterator(), $patterns, []);

        return new self(iterator_to_array($filter));
    }
1124555
def match_files(files, pattern: Pattern):
    """"""

    for name in files:
        if re.match(pattern, name):
            yield name
912124
function _ruleCheckFileName($elementValue, $regex)
    {
        if (!HTML_QuickForm_file::_ruleIsUploadedFile($elementValue)) {
            return true;
        }
        return preg_match($regex, $elementValue['name']);
    }
1115155
private function ensureFileIndexes()
    {
        $indexKey = ['filename' => 1, 'uploadDate' => 1];
        foreach ($this->listIndexes() as $index) {
            if ($index['key'] === $indexKey) {
                return;
            }
        }

        $this->createIndex($indexKey);
    }
377521
protected function _rules() {
		$rules = new Rules();

		$files = array(
			$this->config,
			Libraries::get('li3_quality', 'path') . '/config/syntax.json'
		);
		foreach ($files as $file) {
			if (file_exists($file)) {
				$this->out("Loading configuration file `{$file}`...");
				$config = json_decode(file_get_contents($file), true) + array(
					'name' => null,
					'rules' => array(),
					'options' => array()
				);
				break;
			}
		}

		foreach ($config['rules'] as $ruleName) {
			$class = Libraries::locate('rules.syntax', $ruleName);
			$rules->add(new $class());
		}
		if ($config['options']) {
			$rules->options($config['options']);
		}
		return $rules;
	}
714421
public function setupRules()
    {
        $namespace = '(?:(?P<namespace>\w+):)?';
        $namespaceGroup = [
            1           => Token::NAME,
            'namespace' => '$.scope',
        ];
        $variableRules = new Validator(['!string.single', '!comment', '!variable.special']);

        $this->rules->addMany([
            'string' => CommonFeatures::strings(['single' => '\'', 'double' => '"'], [
                'context' => ['!operator.escape', '!comment', '!string'],
            ]),

            'variable' => [
                new Rule(new RegexMatcher('/(?<!`)(\$'.$namespace.'[a-z_]\w*)/i', $namespaceGroup), [
                    'context'  => $variableRules,
                    'priority' => 0,
                ]),
                new Rule(new RegexMatcher('/[^`](\$\{'.$namespace.'.*?\})/i', $namespaceGroup), [
                    'context'  => $variableRules,
                    'priority' => 0,
                ]),
            ],

            'variable.splat' => new Rule(new RegexMatcher('/[^`](\@'.$namespace.'[a-z_]\w*)/i', $namespaceGroup), [
                'context'  => $variableRules,
                'priority' => 0,
            ]),

            'variable.special' => new Rule(new RegexMatcher('/(\$(?:\$|\^|\?|_|true|false|null))/i'), [
                'priority' => 5,
                'context'  => $variableRules,
            ]),


            'comment'             => new Rule(new CommentMatcher(['#'], [['<#', '#>']])),
            'keyword.doc-section' => new Rule(new RegexMatcher('/[\s\R](\.\w+)/i'), [
                'context' => ['comment'],
            ]),

            'symbol.dotnet' => new Rule(new RegexMatcher('/(\[[a-z][\w\.]*(?:\[\])?\])/si')),

            'symbol.annotation' => new Rule(
                new RegexMatcher('/\[([\w\.]+)\s*(?P<arguments>\((?>[^()]+|(?&arguments))*\))\s*\]/si', [
                    1           => Token::NAME,
                    'arguments' => '$.arguments',
                ])
            ),

            'keyword' => new Rule(new WordMatcher([
                'Begin', 'Break', 'Catch', 'Continue', 'Data', 'Do', 'DynamicParam',
                'Else', 'Elseif', 'End', 'Exit', 'Filter', 'Finally', 'For', 'ForEach',
                'From', 'Function', 'If', 'In', 'InlineScript', 'Hidden', 'Parallel', 'Param',
                'Process', 'Return', 'Sequence', 'Switch', 'Throw', 'Trap', 'Try', 'Until', 'While', 'Workflow',
            ]), ['priority' => 3]),

            'operator' => new Rule(new RegexMatcher('/(&|\-eq|\-ne|\-gt|\-ge|\-lt|\-le|\-ieq|\-ine|\-igt|\-ige|\-ilt|\-ile|\-ceq|\-cne|\-cgt|\-cge|\-clt|\-cle|\-like|\-notlike|\-match|\-notmatch|\-ilike|\-inotlike|\-imatch|\-inotmatch|\-clike|\-cnotlike|\-cmatch|\-cnotmatch|\-contains|\-notcontains|\-icontains|\-inotcontains|\-ccontains|\-cnotcontains|\-isnot|\-is|\-as|\-replace|\-ireplace|\-creplace|\-and|\-or|\-band|\-bor|\-not|\-bnot|\-f|\-casesensitive|\-exact|\-file|\-regex|\-wildcard)\b/i'),
                [
                    'context' => ['!string', '!comment'],
                ]),

            'symbol.parameter' => new Rule(new RegexMatcher('/\s(-\w+:?)\b/i'), [
                'priority' => 0,
                'context'  => ['!string', '!comment', '!call'],
            ]),

            'operator.punctuation' => new Rule(new WordMatcher([',', ';', '.', '::', '%'], ['separated' => false]), [
                'priority' => 0,
                'context'  => ['!string', '!comment', '!call'],
            ]),

            'number' => [
                new Rule(new RegexMatcher('/\b(-?(?:0x[0-9a-f]+|\d+)l?(?:kb|mb|gb|tb|pb)?)\b/i'), [
                    'priority' => 0,
                    'context'  => ['!string', '!comment', '!variable', '!call'],
                ]),
                new Rule(new RegexMatcher('/\b(-?(?>\d+)?\.\d+(?>d|l)(?>e(?:\+|-)?\d+)?(?:kb|mb|gb|tb|pb)?)\b/i'), [
                    'priority' => 0,
                    'context'  => ['!string', '!comment', '!variable', '!call'],
                ]),
            ],

            'call' => new Rule(new RegexMatcher(
                '/(?<![^`]`)(?<=\n|\{|\(|\}|\||=|;|^|function|filter|^PS>)\s*((?:\w+\\\)?\w[\w-\.]+)/im'
            ), ['priority' => 2]),

            'delimiter.prompt' => new Rule(new RegexMatcher('/^(PS>)/im'), ['priority' => 4]),
        ]);
    }
1199798
private static function buildPatterns() {
		if (!is_null(self::$patterns['escape'])) {
			// Patterns have already been built
			return;
		}

		// @codingStandardsIgnoreStart Generic.Files.LineLength.TooLong
		$patterns =& self::$patterns;
		$patterns['escape'] = "(?:{$patterns['unicode']}|\\[^\r\n\f0-9a-f])";
		$patterns['nmstart'] = "(?:[_a-z]|{$patterns['nonAscii']}|{$patterns['escape']})";
		$patterns['nmchar'] = "(?:[_a-z0-9-]|{$patterns['nonAscii']}|{$patterns['escape']})";
		$patterns['ident'] = "-?{$patterns['nmstart']}{$patterns['nmchar']}*";
		$patterns['quantity'] = "{$patterns['num']}(?:\s*{$patterns['unit']}|{$patterns['ident']})?";
		$patterns['possibly_negative_quantity'] = "((?:-?{$patterns['quantity']})|(?:inherit|auto))";
		$patterns['color'] = "(#?{$patterns['nmchar']}+|(?:rgba?|hsla?)\([ \d.,%-]+\))";
		$patterns['url_chars'] = "(?:{$patterns['url_special_chars']}|{$patterns['nonAscii']}|{$patterns['escape']})*";
		$patterns['lookahead_not_open_brace'] = "(?!({$patterns['nmchar']}|\r?\n|\s|#|\:|\.|\,|\+|>|\(|\)|\[|\]|=|\*=|~=|\^=|'[^']*'])*?{)";
		$patterns['lookahead_not_closing_paren'] = "(?!{$patterns['url_chars']}?{$patterns['valid_after_uri_chars']}\))";
		$patterns['lookahead_for_closing_paren'] = "(?={$patterns['url_chars']}?{$patterns['valid_after_uri_chars']}\))";
		$patterns['noflip_single'] = "/({$patterns['noflip_annotation']}{$patterns['lookahead_not_open_brace']}[^;}]+;?)/i";
		$patterns['noflip_class'] = "/({$patterns['noflip_annotation']}{$patterns['chars_within_selector']}})/i";
		$patterns['direction_ltr'] = "/({$patterns['direction']})ltr/i";
		$patterns['direction_rtl'] = "/({$patterns['direction']})rtl/i";
		$patterns['left'] = "/{$patterns['lookbehind_not_letter']}(left){$patterns['lookahead_not_letter']}{$patterns['lookahead_not_closing_paren']}{$patterns['lookahead_not_open_brace']}/i";
		$patterns['right'] = "/{$patterns['lookbehind_not_letter']}(right){$patterns['lookahead_not_letter']}{$patterns['lookahead_not_closing_paren']}{$patterns['lookahead_not_open_brace']}/i";
		$patterns['left_in_url'] = "/{$patterns['lookbehind_not_letter']}(left){$patterns['lookahead_for_closing_paren']}/i";
		$patterns['right_in_url'] = "/{$patterns['lookbehind_not_letter']}(right){$patterns['lookahead_for_closing_paren']}/i";
		$patterns['ltr_in_url'] = "/{$patterns['lookbehind_not_letter']}(ltr){$patterns['lookahead_for_closing_paren']}/i";
		$patterns['rtl_in_url'] = "/{$patterns['lookbehind_not_letter']}(rtl){$patterns['lookahead_for_closing_paren']}/i";
		$patterns['cursor_east'] = "/{$patterns['lookbehind_not_letter']}([ns]?)e-resize/";
		$patterns['cursor_west'] = "/{$patterns['lookbehind_not_letter']}([ns]?)w-resize/";
		$patterns['four_notation_quantity_props'] = "((?:margin|padding|border-width)\s*:\s*)";
		$patterns['four_notation_quantity'] = "/{$patterns['four_notation_quantity_props']}{$patterns['possibly_negative_quantity']}(\s+){$patterns['possibly_negative_quantity']}(\s+){$patterns['possibly_negative_quantity']}(\s+){$patterns['possibly_negative_quantity']}{$patterns['suffix']}/i";
		$patterns['four_notation_color'] = "/((?:-color|border-style)\s*:\s*){$patterns['color']}(\s+){$patterns['color']}(\s+){$patterns['color']}(\s+){$patterns['color']}{$patterns['suffix']}/i";
		// border-radius: <length or percentage>{1,4} [optional: / <length or percentage>{1,4} ]
		$patterns['border_radius'] = '/(border-radius\s*:\s*)' . $patterns['possibly_negative_quantity']
			. '(?:(?:\s+' . $patterns['possibly_negative_quantity'] . ')(?:\s+' . $patterns['possibly_negative_quantity'] . ')?(?:\s+' . $patterns['possibly_negative_quantity'] . ')?)?'
			. '(?:(?:(?:\s*\/\s*)' . $patterns['possibly_negative_quantity'] . ')(?:\s+' . $patterns['possibly_negative_quantity'] . ')?(?:\s+' . $patterns['possibly_negative_quantity'] . ')?(?:\s+' . $patterns['possibly_negative_quantity'] . ')?)?' . $patterns['suffix']
			. '/i';
		$patterns['box_shadow'] = "/(box-shadow\s*:\s*(?:inset\s*)?){$patterns['possibly_negative_quantity']}/i";
		$patterns['text_shadow1'] = "/(text-shadow\s*:\s*){$patterns['possibly_negative_quantity']}(\s*){$patterns['color']}/i";
		$patterns['text_shadow2'] = "/(text-shadow\s*:\s*){$patterns['color']}(\s*){$patterns['possibly_negative_quantity']}/i";
		$patterns['text_shadow3'] = "/(text-shadow\s*:\s*){$patterns['possibly_negative_quantity']}/i";
		$patterns['bg_horizontal_percentage'] = "/(background(?:-position)?\s*:\s*(?:[^:;}\s]+\s+)*?)({$patterns['quantity']})/i";
		$patterns['bg_horizontal_percentage_x'] = "/(background-position-x\s*:\s*)(-?{$patterns['num']}%)/i";
		$patterns['translate_x'] = "/(transform\s*:[^;]*)(translateX\s*\(\s*){$patterns['possibly_negative_quantity']}(\s*\))/i";
		$patterns['translate'] = "/(transform\s*:[^;]*)(translate\s*\(\s*){$patterns['possibly_negative_quantity']}((?:\s*,\s*{$patterns['possibly_negative_quantity']}){0,2}\s*\))/i";
		// @codingStandardsIgnoreEnd
	}
1215903
private function patternHasMatch($globPattern)
    {
        if (substr(trim($globPattern), 0, 1) === '/') {
            $globPattern = trim(substr($globPattern, 1));
        } elseif (substr(trim($globPattern), -1) === '/') {
            $globPattern = trim(substr($globPattern, 0, -1));
        } else {
            $globPattern = '{' . trim($globPattern) . '}*';
        }

        $initialWorkingDirectory = (string) getcwd();
        chdir($this->directory);

        $matches = glob($globPattern, GLOB_BRACE);

        chdir($initialWorkingDirectory);

        return is_array($matches) && count($matches) > 0;
    }
1315721
public function doAddPattern($pattern)
    {
        if (0 === strpos($pattern, '!')) {
            $searchPattern = substr($pattern, 1);
            $this->finder->notPath(Glob::toRegex($searchPattern, true, true));

            $pathComponents = explode('/', $searchPattern);

            if (1 < \count($pathComponents)) {
                $parentDirectories = \array_slice($pathComponents, 0, -1);
                $basePath = '';

                foreach ($parentDirectories as $dir) {
                    $this->finder->notPath('/\b('.preg_quote($basePath.$dir, '/').')(?!\/)\b/');
                    $basePath .= $dir.'/';
                }
            }
        } else {
            $this->finder->path(Glob::toRegex($pattern, true, true));
        }
    }
617556
private function doAddMatchers()
    {
        if (!empty($this->newMatchers)) {
            $this->shell->addMatchers($this->newMatchers);
            $this->newMatchers = [];
        }
    }
406075
public function createRegex()
    {
        $parts = explode('/', ltrim($this->path, '/'));
        $regex = '/^'; // Matches the start of the string
        foreach ($parts as $part) {
            $regex .= '\/'; // Matches starting slash
            // Handle non-variable parts
            if (stripos($part, '{') === false &&
                stripos($part, '}') === false) {
                $regex .= $part; // Exactly match this part
                continue;
            }
            // Handle variable parts
            $name = str_ireplace(['{', '}'], '', $part);
            $this->parameterNames[] = $name;
            $this->parameters[$name] = null;
            // Check if a rule exists for this part
            if (isset($this->rules[$name])) {
                $regex .= $this->rules[$name];
                continue;
            }
            // No rule exists, match all except slashes
            $regex .= '([^\/]+)';
        }
        $regex .= '$/'; // Matches end of string
        $this->regex = $regex;
    }
886732
def process_pattern(fn):
    
    directory, pattern = validate_pattern(fn)
    if directory is not None:
        filenames = fnmatch.filter(auto(listdir, directory), pattern)
        if filenames:
            return [directory + '/' + sfn for sfn in filenames]
        else:
            print_err("cannot access '{}': No such file or directory".format(fn))
427492
private function addFileMap()
    {
        $code = '';
        $definitions = $this->container->getDefinitions();
        ksort($definitions);
        foreach ($definitions as $id => $definition) {
            if (!$definition->isSynthetic() && $definition->isShared() && !$this->isHotPath($definition)) {
                $code .= sprintf("            %s => '%s.php',\n", $this->doExport($id), $this->generateMethodName($id));
            }
        }

        return $code ? "        \$this->fileMap = array(\n{$code}        );\n" : '';
    }
1283337
def add_matching(pattern)
      FileList.glob(pattern).each do |fn|
        self << fn unless excluded_from_list?(fn)
      end
    end
56159
function lintAllFiles (src, options)
{
    glob(src,
        function (err, files)
        {
            if (err) throw err;

            for (var i = 0, l = files.length; i < l; i++)
            {
                jsHintHelper.lintFile(files[i], options.rules);
            }
        }
    );
}
489251
public function setupRules()
    {
        $identifier = '-?[_a-zA-Z]+[_a-zA-Z0-9-]*';
        $at = [
            'charset', 'import', 'namespace',
            'media', 'supports', 'document', 'page', 'font-face', 'keyframes', 'viewport', 'counter-style',
            'font-feature-values', 'swash', 'ornaments', 'annotation', 'stylistic', 'styleset', 'character-variant'
        ];
        
        $this->rules->addMany([
            'string' => CommonFeatures::strings(['single' => '\'', 'double' => '"'], [
                'context' => $this->everywhere()
            ]),

            'meta.declaration' => [
                new OpenRule(new SubStringMatcher('{'), [
                    'context' => ['!meta.declaration.media', '!comment'],
                    'factory' => new TokenFactory(MetaToken::class)
                ]),
                new CloseRule(new SubStringMatcher('}')),
            ],

            'meta.declaration.media' => [
                new Rule(new RegexMatcher('/@media(.*?\{)/'), [
                    'context' => Validator::everywhere(),
                    'factory' => new TokenFactory(MetaToken::class)
                ]),
            ],

            'meta.declaration.rule' => [
                new OpenRule(new RegexMatcher('/@media.*(\()/'), [
                    'context' => ['meta.declaration.media'],
                    'factory' => new TokenFactory(MetaToken::class)
                ]),
                new CloseRule(new SubStringMatcher(')')),
            ],

            'keyword.at-rule' => new Rule(new RegexMatcher('/(@(?:-[a-z]+-)?(?:'.implode('|', $at).'))/'), [
                'priority' => 2
            ]),

            'symbol.selector.id'    => new Rule(new RegexMatcher("/(#$identifier)/i")),
            'symbol.selector.tag'   => new Rule(new RegexMatcher('/(?>[\s}]|^)(?=(\w+)[^;]*\{)/ms')),
            'symbol.selector.class' => new Rule(new RegexMatcher("/(\\.$identifier)/i")),

            'symbol.selector.class.pseudo' => new Rule(new RegexMatcher("/(:{1,2}$identifier)/")),

            'number' => new Rule(new RegexMatcher("/([-+]?[0-9]*\\.?[0-9]+([\\w%]+)?)/"), [
                'context'  => ['meta.declaration', '!constant.color', '!comment', '!symbol', '!comment', '!string'],
                'priority' => 0
            ]),
            
            'symbol.property' => new Rule(new RegexMatcher("/($identifier:)/"), [
                'context' => ['meta.declaration', '!symbol', '!comment'],
                'priority' => 2
            ]),

            'call' => new Rule(new RegexMatcher("/($identifier)\\s*\\((?:(?P<string>[a-z].*?)|.*?)\\)/", [
                1 => Token::NAME,
                'string' => 'string.argument'
            ]), [
                'context' => ['meta.declaration', '!comment', '!string', '!keyword']
            ]),

            'constant.color' => [
                new Rule(new RegexMatcher("/(#[0-9a-f]{3,6})/i"), [
                    'priority' => 2,
                    'context'  => ['meta.declaration', '!comment']
                ]),
                new Rule(new WordMatcher([
                    'white', 'silver', 'gray', 'black', 'red', 'maroon', 'yellow', 'olive',
                    'lime', 'green', 'aqua', 'teal', 'blue', 'navy', 'fuchsia', 'purple'
                ]), [
                    'context'  => ['meta.declaration', '!comment', '!symbol', '!variable']
                ]),
            ],

            'operator' => new Rule(new WordMatcher(['>', '+', '*', '!important'], ['separated' => false]), [
                'context' => $this->everywhere()
            ]),

            'operator.punctuation' => new Rule(new SubStringMatcher(';'), [
                'context' => $this->everywhere()
            ]),

            'comment' => new Rule(new CommentMatcher([], [['/*', '*/']]), ['context' => $this->everywhere()])
        ]);
    }
1297607
protected function _searchFiles()
    {
        $pattern = false;
        if (!empty($this->_exclude)) {
            $exclude = [];
            foreach ($this->_exclude as $e) {
                if (DIRECTORY_SEPARATOR !== '\\' && $e[0] !== DIRECTORY_SEPARATOR) {
                    $e = DIRECTORY_SEPARATOR . $e;
                }
                $exclude[] = preg_quote($e, '/');
            }
            $pattern = '/' . implode('|', $exclude) . '/';
        }
        foreach ($this->_paths as $path) {
            $path = realpath($path) . DIRECTORY_SEPARATOR;
            $Folder = new Folder($path);
            $files = $Folder->findRecursive('.*\.(php|ctp|thtml|inc|tpl)', true);
            if (!empty($pattern)) {
                $files = preg_grep($pattern, $files, PREG_GREP_INVERT);
                $files = array_values($files);
            }
            $this->_files = array_merge($this->_files, $files);
        }
        $this->_files = array_unique($this->_files);
    }