FileFinder.php 12.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
<?php
/*
 *  $Id$
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * This software consists of voluntary contributions made by many individuals
 * and is licensed under the LGPL. For more information, see
19
 * <http://www.phpdoctrine.org>.
20 21 22 23 24 25 26 27 28 29 30
 */

/**
 *
 * This is a port of sfFinder from the symfony-project.
 * http://www.symfony-project.com
 *
 * Allow to build rules to find files and directories.
 *
 * All rules may be invoked several times, except for ->in() method.
 * Some rules are cumulative (->name() for example) whereas others are destructive
Jonathan.Wage's avatar
Jonathan.Wage committed
31
 * (most recent value is used, ->maxDepth() method for example).
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
 *
 * All methods return the current Doctrine_FileFinder object to allow easy chaining:
 *
 * $files = Doctrine_FileFinder::type('file')->name('*.php')->in(.);
 *
 * Interface loosely based on perl File::Find::Rule module.
 *
 * Doctrine_FileFinder
 *
 * @package     Doctrine
 * @subpackage  FileFinder
 * @author      Symfony Project/Fabien Potencier <fabien.potencier@symfony-project.com>
 * @license     http://www.opensource.org/licenses/lgpl-license.php LGPL
 * @version     $Revision$
 * @link        www.symfony-project.com
 * @since       1.0
 */
class Doctrine_FileFinder
{
  protected $type        = 'file';
  protected $names       = array();
  protected $prunes      = array();
  protected $discards    = array();
  protected $execs       = array();
Jonathan.Wage's avatar
Jonathan.Wage committed
56
  protected $minDepth    = 0;
57
  protected $sizes       = array();
Jonathan.Wage's avatar
Jonathan.Wage committed
58
  protected $maxDepth    = 1000000;
59
  protected $relative    = false;
Jonathan.Wage's avatar
Jonathan.Wage committed
60
  protected $followLink = false;
61 62 63 64 65 66 67 68 69

  /**
   * Sets maximum directory depth.
   *
   * Finder will descend at most $level levels of directories below the starting point.
   *
   * @param  integer level
   * @return object current Doctrine_FileFinder object
   */
Jonathan.Wage's avatar
Jonathan.Wage committed
70
  public function maxDepth($level)
71
  {
Jonathan.Wage's avatar
Jonathan.Wage committed
72
    $this->maxDepth = $level;
73 74 75 76 77 78 79 80 81 82 83 84

    return $this;
  }

  /**
   * Sets minimum directory depth.
   *
   * Finder will start applying tests at level $level.
   *
   * @param  integer level
   * @return object current Doctrine_FileFinder object
   */
Jonathan.Wage's avatar
Jonathan.Wage committed
85
  public function minDepth($level)
86
  {
Jonathan.Wage's avatar
Jonathan.Wage committed
87
    $this->minDepth = $level;
88 89 90 91

    return $this;
  }

Jonathan.Wage's avatar
Jonathan.Wage committed
92
  public function getType()
93 94 95 96 97 98 99 100 101 102 103 104 105
  {
    return $this->type;
  }

  /**
   * Sets the type of elements to returns.
   *
   * @param  string directory or file or any (for both file and directory)
   * @return object new Doctrine_FileFinder object
   */
  public static function type($name)
  {
    $finder = new Doctrine_FileFinder();
Jonathan.Wage's avatar
Jonathan.Wage committed
106

107 108 109 110 111
    return $finder->setType($name);
  }

  public function setType($name)
  {
Jonathan.Wage's avatar
Jonathan.Wage committed
112
    if (strtolower(substr($name, 0, 3)) == 'dir') {
113
      $this->type = 'directory';
Jonathan.Wage's avatar
Jonathan.Wage committed
114
    } else if (strtolower($name) == 'any') {
115
      $this->type = 'any';
Jonathan.Wage's avatar
Jonathan.Wage committed
116
    } else {
117 118 119 120 121 122 123 124 125
      $this->type = 'file';
    }

    return $this;
  }

  /*
   * glob, patterns (must be //) or strings
   */
Jonathan.Wage's avatar
Jonathan.Wage committed
126
  protected function toRegex($str)
127
  {
Jonathan.Wage's avatar
Jonathan.Wage committed
128
    if ($str{0} == '/' && $str{strlen($str) - 1} == '/') {
129
      return $str;
Jonathan.Wage's avatar
Jonathan.Wage committed
130 131
    } else {
      return Doctrine_FileFinder_GlobToRegex::globToRegex($str);
132 133 134
    }
  }

Jonathan.Wage's avatar
Jonathan.Wage committed
135
  protected function argsToArray($argList, $not = false)
136 137 138
  {
    $list = array();

Jonathan.Wage's avatar
Jonathan.Wage committed
139 140 141 142
    for ($i = 0; $i < count($argList); $i++) {
      if (is_array($argList[$i])) {
        foreach ($argList[$i] as $arg) {
          $list[] = array($not, $this->toRegex($arg));
143
        }
Jonathan.Wage's avatar
Jonathan.Wage committed
144 145
      } else {
        $list[] = array($not, $this->toRegex($argList[$i]));
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
      }
    }

    return $list;
  }

  /**
   * Adds rules that files must match.
   *
   * You can use patterns (delimited with / sign), globs or simple strings.
   *
   * $finder->name('*.php')
   * $finder->name('/\.php$/') // same as above
   * $finder->name('test.php')
   *
   * @param  list   a list of patterns, globs or strings
   * @return object current Doctrine_FileFinder object
   */
  public function name()
  {
    $args = func_get_args();
Jonathan.Wage's avatar
Jonathan.Wage committed
167
    $this->names = array_merge($this->names, $this->argsToArray($args));
168 169 170 171 172 173 174 175 176 177 178

    return $this;
  }

  /**
   * Adds rules that files must not match.
   *
   * @see    ->name()
   * @param  list   a list of patterns, globs or strings
   * @return object current Doctrine_FileFinder object
   */
Jonathan.Wage's avatar
Jonathan.Wage committed
179
  public function notName()
180 181
  {
    $args = func_get_args();
Jonathan.Wage's avatar
Jonathan.Wage committed
182
    $this->names = array_merge($this->names, $this->argsToArray($args, true));
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199

    return $this;
  }

  /**
   * Adds tests for file sizes.
   *
   * $finder->size('> 10K');
   * $finder->size('<= 1Ki');
   * $finder->size(4);
   *
   * @param  list   a list of comparison strings
   * @return object current Doctrine_FileFinder object
   */
  public function size()
  {
    $args = func_get_args();
Jonathan.Wage's avatar
Jonathan.Wage committed
200 201
    for ($i = 0; $i < count($args); $i++) {
      $this->sizes[] = new Doctrine_FileFinder_NumberCompare($args[$i]);
202 203 204 205 206 207 208 209 210 211 212 213 214 215
    }

    return $this;
  }

  /**
   * Traverses no further.
   *
   * @param  list   a list of patterns, globs to match
   * @return object current Doctrine_FileFinder object
   */
  public function prune()
  {
    $args = func_get_args();
Jonathan.Wage's avatar
Jonathan.Wage committed
216
    $this->prunes = array_merge($this->prunes, $this->argsToArray($args));
217 218 219 220 221 222 223 224 225 226 227 228 229

    return $this;
  }

  /**
   * Discards elements that matches.
   *
   * @param  list   a list of patterns, globs to match
   * @return object current Doctrine_FileFinder object
   */
  public function discard()
  {
    $args = func_get_args();
Jonathan.Wage's avatar
Jonathan.Wage committed
230
    $this->discards = array_merge($this->discards, $this->argsToArray($args));
231 232 233 234 235 236 237 238 239 240 241

    return $this;
  }

  /**
   * Ignores version control directories.
   *
   * Currently supports subversion, CVS, DARCS, Gnu Arch, Monotone, Bazaar-NG
   *
   * @return object current Doctrine_FileFinder object
   */
Jonathan.Wage's avatar
Jonathan.Wage committed
242
  public function ignoreVersionControl()
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
  {
    $ignores = array('.svn', 'CVS', '_darcs', '.arch-params', '.monotone', '.bzr');

    return $this->discard($ignores)->prune($ignores);
  }

  /**
   * Executes function or method for each element.
   *
   * Element match if functino or method returns true.
   *
   * $finder->exec('myfunction');
   * $finder->exec(array($object, 'mymethod'));
   *
   * @param  mixed  function or method to call
   * @return object current Doctrine_FileFinder object
   */
  public function exec()
  {
    $args = func_get_args();
Jonathan.Wage's avatar
Jonathan.Wage committed
263 264
    for ($i = 0; $i < count($args); $i++) {
      if (is_array($args[$i]) && !method_exists($args[$i][0], $args[$i][1])) {
265
        throw new Doctrine_Exception(sprintf('method "%s" does not exist for object "%s".', $args[$i][1], $args[$i][0]));
Jonathan.Wage's avatar
Jonathan.Wage committed
266
      } else if ( ! is_array($args[$i]) && !function_exists($args[$i])) {
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
        throw new Doctrine_Exception(sprintf('function "%s" does not exist.', $args[$i]));
      }

      $this->execs[] = $args[$i];
    }

    return $this;
  }

  /**
   * Returns relative paths for all files and directories.
   *
   * @return object current Doctrine_FileFinder object
   */
  public function relative()
  {
    $this->relative = true;

    return $this;
  }

  /**
   * Symlink following.
   *
   * @return object current Doctrine_FileFinder object
   */
Jonathan.Wage's avatar
Jonathan.Wage committed
293
  public function followLink()
294
  {
Jonathan.Wage's avatar
Jonathan.Wage committed
295
    $this->followLink = true;
296 297 298 299 300 301 302 303 304 305 306 307 308 309

    return $this;
  }

  /**
   * Searches files and directories which match defined rules.
   *
   * @return array list of files and directories
   */
  public function in()
  {
    $files    = array();
    $here_dir = getcwd();
    $numargs  = func_num_args();
Jonathan.Wage's avatar
Jonathan.Wage committed
310
    $argList = func_get_args(); 
311 312

    // first argument is an array?
Jonathan.Wage's avatar
Jonathan.Wage committed
313 314 315
    if ($numargs == 1 && is_array($argList[0])) {
      $argList = $argList[0];
      $numargs  = count($argList);
316 317
    }

Jonathan.Wage's avatar
Jonathan.Wage committed
318 319
    for ($i = 0; $i < $numargs; $i++) {
      $realDir = realpath($argList[$i]);
320 321

      // absolute path?
Jonathan.Wage's avatar
Jonathan.Wage committed
322 323 324 325
      if ( ! self::isPathAbsolute($realDir)) {
        $dir = $here_dir . DIRECTORY_SEPARATOR . $realDir;
      } else {
        $dir = $realDir;
326 327
      }

Jonathan.Wage's avatar
Jonathan.Wage committed
328
      if ( ! is_dir($realDir)) {
329 330 331
        continue;
      }

Jonathan.Wage's avatar
Jonathan.Wage committed
332 333 334 335
      if ($this->relative) {
        $files = array_merge($files, str_replace($dir . DIRECTORY_SEPARATOR, '', $this->_searchIn($dir)));
      } else {
        $files = array_merge($files, $this->_searchIn($dir));
336 337 338 339 340 341
      }
    }

    return array_unique($files);
  }

Jonathan.Wage's avatar
Jonathan.Wage committed
342
  protected function _searchIn($dir, $depth = 0)
343
  {
Jonathan.Wage's avatar
Jonathan.Wage committed
344
    if ($depth > $this->maxDepth) {
345 346 347
      return array();
    }

Jonathan.Wage's avatar
Jonathan.Wage committed
348
    if (is_link($dir) && !$this->followLink) {
349 350 351 352 353
      return array();
    }

    $files = array();

Jonathan.Wage's avatar
Jonathan.Wage committed
354 355 356 357 358 359 360 361 362
    if (is_dir($dir)) {
      $currentDir = opendir($dir);
      while (false !== $entryName = readdir($currentDir)) {
        if ($entryName == '.' || $entryName == '..') {
            continue;
        }
        
        $currentEntry = $dir . DIRECTORY_SEPARATOR . $entryName;
        if (is_link($currentEntry) && !$this->followLink) {
363 364 365
          continue;
        }

Jonathan.Wage's avatar
Jonathan.Wage committed
366 367 368
        if (is_dir($currentEntry)) {
          if (($this->type == 'directory' || $this->type == 'any') && ($depth >= $this->minDepth) && !$this->_isDiscarded($dir, $entryName) && $this->_matchNames($dir, $entryName) && $this->_execOk($dir, $entryName)) {
            $files[] = realpath($currentEntry);
369 370
          }

Jonathan.Wage's avatar
Jonathan.Wage committed
371 372
          if ( ! $this->_isPruned($dir, $entryName)) {
            $files = array_merge($files, $this->_searchIn($currentEntry, $depth + 1));
373
          }
Jonathan.Wage's avatar
Jonathan.Wage committed
374 375 376
        } else {
          if (($this->type != 'directory' || $this->type == 'any') && ($depth >= $this->minDepth) && !$this->_isDiscarded($dir, $entryName) && $this->_matchNames($dir, $entryName) && $this->_sizeOk($dir, $entryName) && $this->_execOk($dir, $entryName)) {
            $files[] = realpath($currentEntry);
377 378 379
          }
        }
      }
Jonathan.Wage's avatar
Jonathan.Wage committed
380 381

      closedir($currentDir);
382 383 384 385 386
    }

    return $files;
  }

Jonathan.Wage's avatar
Jonathan.Wage committed
387
  protected function _matchNames($dir, $entry)
388
  {
Jonathan.Wage's avatar
Jonathan.Wage committed
389 390 391 392
    if ( ! count($this->names)) {
        return true;
    }
    
393
    // we must match one "not_name" rules to be ko
Jonathan.Wage's avatar
Jonathan.Wage committed
394 395
    $oneNotNameRule = false;
    foreach ($this->names as $args) {
396
      list($not, $regex) = $args;
Jonathan.Wage's avatar
Jonathan.Wage committed
397 398 399
      if ($not) {
        $oneNotNameRule = true;
        if (preg_match($regex, $entry)) {
400 401 402 403 404
          return false;
        }
      }
    }

Jonathan.Wage's avatar
Jonathan.Wage committed
405
    $oneNameRule = false;
406
    // we must match one "name" rules to be ok
Jonathan.Wage's avatar
Jonathan.Wage committed
407
    foreach ($this->names as $args) {
408
      list($not, $regex) = $args;
Jonathan.Wage's avatar
Jonathan.Wage committed
409 410 411
      if ( ! $not) {
        $oneNameRule = true;
        if (preg_match($regex, $entry)) {
412 413 414 415 416
          return true;
        }
      }
    }

Jonathan.Wage's avatar
Jonathan.Wage committed
417
    if ($oneNotNameRule && $oneNameRule) {
418
      return false;
Jonathan.Wage's avatar
Jonathan.Wage committed
419
    } else if ($oneNotNameRule) {
420
      return true;
Jonathan.Wage's avatar
Jonathan.Wage committed
421
    } else if ($oneNameRule) {
422
      return false;
Jonathan.Wage's avatar
Jonathan.Wage committed
423
    } else {
424 425 426 427
      return true;
    }
  }

Jonathan.Wage's avatar
Jonathan.Wage committed
428
  protected function _sizeOk($dir, $entry)
429
  {
Jonathan.Wage's avatar
Jonathan.Wage committed
430 431 432 433 434 435 436 437 438 439 440 441 442
    if ( ! count($this->sizes)) {
        return true;
    }
    
    if ( ! is_file($dir . DIRECTORY_SEPARATOR . $entry)) {
        return true;
    }
    
    $filesize = filesize($dir . DIRECTORY_SEPARATOR . $entry);
    foreach ($this->sizes as $number_compare) {
      if ( ! $number_compare->test($filesize)) {
        return false;
      }
443 444 445 446 447
    }

    return true;
  }

Jonathan.Wage's avatar
Jonathan.Wage committed
448
  protected function _isPruned($dir, $entry)
449
  {
Jonathan.Wage's avatar
Jonathan.Wage committed
450 451 452 453 454
    if ( ! count($this->prunes)) {
        return false;
    }
    
    foreach ($this->prunes as $args) {
455
      $regex = $args[1];
Jonathan.Wage's avatar
Jonathan.Wage committed
456 457 458
      if (preg_match($regex, $entry)) {
          return true;
      }
459 460 461 462 463
    }

    return false;
  }

Jonathan.Wage's avatar
Jonathan.Wage committed
464
  protected function _isDiscarded($dir, $entry)
465
  {
Jonathan.Wage's avatar
Jonathan.Wage committed
466 467 468 469 470
    if ( ! count($this->discards)) {
        return false;
    }
    
    foreach ($this->discards as $args) {
471
      $regex = $args[1];
Jonathan.Wage's avatar
Jonathan.Wage committed
472 473 474
      if (preg_match($regex, $entry)) {
          return true;
      }
475 476 477 478 479
    }

    return false;
  }

Jonathan.Wage's avatar
Jonathan.Wage committed
480
  protected function _execOk($dir, $entry)
481
  {
Jonathan.Wage's avatar
Jonathan.Wage committed
482 483 484 485 486 487 488 489
    if ( ! count($this->execs)) {
        return true;
    }
    
    foreach ($this->execs as $exec) {
      if ( ! call_user_func_array($exec, array($dir, $entry))) {
          return false;
      }
490 491 492 493 494 495 496 497 498 499 500 501
    }

    return true;
  }

  public static function isPathAbsolute($path)
  {
    if ($path{0} == '/' || $path{0} == '\\' ||
        (strlen($path) > 3 && ctype_alpha($path{0}) &&
         $path{1} == ':' &&
         ($path{2} == '\\' || $path{2} == '/')
        )
Jonathan.Wage's avatar
Jonathan.Wage committed
502
       ) {
503 504 505 506 507 508
      return true;
    }

    return false;
  }
}