webmozart/glob
Ant-like globbing for PHP with support for , ?, [], {}, and // to match directories. Glob filesystem paths (including stream wrappers), match globs against strings, and filter path arrays. Uses native glob() when possible; throws on invalid patterns.
Install via composer require webmozart/glob. The package’s core is Webmozart\Glob\Glob, with Glob::glob($glob, $flags = 0) as the primary method—ideal when you need Ant-style patterns like /**/ or {a,b} that PHP’s native glob() lacks. Start by using absolute globs (e.g., __DIR__ . '/config/**/*.yaml') since relative globs are unsupported. For memory efficiency with large file trees, use new GlobIterator($glob) instead of loading all results at once.
First use case: Collect all Twig templates used in admin UIs, excluding vendor:
use Webmozart\Glob\Glob;
$adminTemplates = Glob::glob(
__DIR__ . '/templates/{admin,shared}/*.twig',
Glob::FILTER_VALUE
);
Glob::filter($paths, $glob, $mode)—with FILTER_VALUE (default) to match against path strings, or FILTER_KEY to match array keys (e.g., ['config/app.yaml' => '...']).$iterator = new GlobIterator(__DIR__ . '/logs/{*.log,*.log.gz}'); // GlobIterator
$filtered = new CallbackFilterIterator($iterator, fn($file) => $file->getSize() > 1024 * 1024);
Glob::glob('vfs://app/logs/**/*.txt'); // Works with vfsStream, php://memory, etc.
Path::canonicalize() (from webmozart/path-util) or sys_get_temp_dir() → then prepend the base as an absolute glob segment. Avoid assuming CWD-relative behavior.Glob::match($path, $glob) for deterministic validation logic (e.g., in configuration validation or security checks).Example: Validate uploads against a strict allowlist
foreach ($_FILES as $upload) {
$path = $upload['tmp_name'];
if (!Glob::match($path, __DIR__ . '/uploads/images/*.{jpg,jpeg,png,gif}')) {
throw new InvalidUploadException('File type not allowed');
}
}
/) internally—even on Windows—and returned paths always normalize to /. Escape literal backslashes as \\\\ (e.g., 'C:\\\\backup\\*\\\\').*, ?, [, {, ], } require \ prefix. In PHP strings, remember double escaping: '\\*' → literal \*.InvalidArgumentException; directory read errors may return false. Wrap in if ($results === false) checks (not exceptions) for robustness.glob() when patterns avoid advanced features (e.g., /**/, {a,b}), but complex patterns force regex-based scanning. Profile hot paths!GLOB_BRACE isn’t always available; the package handles fallback automatically, but verify phpinfo() if you see inconsistent brace expansion.GlobIterator doesn’t guarantee order—use IteratorIterator + usort() if sorted results matter.Glob::glob() indirectly via a service class to avoid filesystem dependencies—unit tests rarely need real paths.How can I help you explore Laravel packages today?