. */ /** * Doctrine_FileFinder_GlobToRegex * * Match globbing patterns against text. * * if match_glob("foo.*", "foo.bar") echo "matched\n"; * * // prints foo.bar and foo.baz * $regex = globToRegex("foo.*"); * for (array('foo.bar', 'foo.baz', 'foo', 'bar') as $t) * { * if (/$regex/) echo "matched: $car\n"; * } * * Doctrine_FileFinder_GlobToRegex implements glob(3) style matching that can be used to match * against text, rather than fetching names from a filesystem. * * based on perl Text::Glob module. * * @package Doctrine * @subpackage FileFinder * @author Fabien Potencier php port * @author Richard Clamp perl version * @copyright 2004-2005 Fabien Potencier * @copyright 2002 Richard Clamp * @version SVN: $Id: Doctrine_FileFinder.class.php 5110 2007-09-15 12:07:18Z fabien $ */ class Doctrine_FileFinder_GlobToRegex { protected static $strictLeadingDot = true; protected static $strictWildcardSlash = true; public static function setStrictLeadingDot($boolean) { self::$strictLeadingDot = $boolean; } public static function setStrictWildcardSlash($boolean) { self::$strictWildcardSlash = $boolean; } /** * Returns a compiled regex which is the equiavlent of the globbing pattern. * * @param string glob pattern * @return string regex */ public static function globToRegex($glob) { $firstByte = true; $escaping = false; $inCurlies = 0; $regex = ''; for ($i = 0; $i < strlen($glob); $i++) { $car = $glob[$i]; if ($firstByte) { if (self::$strictLeadingDot && $car != '.') { $regex .= '(?=[^\.])'; } $firstByte = false; } if ($car == '/') { $firstByte = true; } if ($car == '.' || $car == '(' || $car == ')' || $car == '|' || $car == '+' || $car == '^' || $car == '$') { $regex .= "\\$car"; } else if ($car == '*') { $regex .= ($escaping ? "\\*" : (self::$strictWildcardSlash ? "[^/]*" : ".*")); } else if ($car == '?') { $regex .= ($escaping ? "\\?" : (self::$strictWildcardSlash ? "[^/]" : ".")); } else if ($car == '{') { $regex .= ($escaping ? "\\{" : "("); if ( ! $escaping) { ++$inCurlies; } } else if ($car == '}' && $inCurlies) { $regex .= ($escaping ? "}" : ")"); if ( ! $escaping) { --$inCurlies; } } else if ($car == ',' && $inCurlies) { $regex .= ($escaping ? "," : "|"); } else if ($car == "\\") { if ($escaping) { $regex .= "\\\\"; $escaping = false; } else { $escaping = true; } continue; } else { $regex .= $car; $escaping = false; } $escaping = false; } return "#^$regex$#"; } }