Namespaces

  • Nette
    • Application
      • Diagnostics
      • Responses
      • Routers
      • UI
    • Caching
      • Storages
    • ComponentModel
    • Database
      • Diagnostics
      • Drivers
      • Reflection
      • Table
    • DI
      • Config
        • Adapters
      • Diagnostics
      • Extensions
    • Diagnostics
    • Forms
      • Controls
      • Rendering
    • Http
      • Diagnostics
    • Iterators
    • Latte
      • Macros
    • Loaders
    • Localization
    • Mail
    • PhpGenerator
    • Reflection
    • Security
      • Diagnostics
    • Templating
    • Utils
  • NetteModule
  • none

Classes

  • Arrays
  • Callback
  • FileSystem
  • Finder
  • Html
  • Json
  • LimitedScope
  • MimeTypeDetector
  • Neon
  • NeonEntity
  • Paginator
  • Strings
  • Validators

Exceptions

  • AssertionException
  • JsonException
  • NeonException
  • RegexpException
  • TokenizerException
  • Overview
  • Namespace
  • Class
  • Tree
  • Deprecated
  • Other releases
  • Nette homepage
  1: <?php
  2: 
  3: /**
  4:  * This file is part of the Nette Framework (https://nette.org)
  5:  * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
  6:  */
  7: 
  8: namespace Nette\Utils;
  9: 
 10: use Nette;
 11: use RecursiveIteratorIterator;
 12: 
 13: 
 14: /**
 15:  * Finder allows searching through directory trees using iterator.
 16:  *
 17:  * <code>
 18:  * Finder::findFiles('*.php')
 19:  *     ->size('> 10kB')
 20:  *     ->from('.')
 21:  *     ->exclude('temp');
 22:  * </code>
 23:  *
 24:  * @author     David Grudl
 25:  */
 26: class Finder extends Nette\Object implements \IteratorAggregate
 27: {
 28:     /** @var array */
 29:     private $paths = array();
 30: 
 31:     /** @var array of filters */
 32:     private $groups;
 33: 
 34:     /** @var filter for recursive traversing */
 35:     private $exclude = array();
 36: 
 37:     /** @var int */
 38:     private $order = RecursiveIteratorIterator::SELF_FIRST;
 39: 
 40:     /** @var int */
 41:     private $maxDepth = -1;
 42: 
 43:     /** @var array */
 44:     private $cursor;
 45: 
 46: 
 47:     /**
 48:      * Begins search for files matching mask and all directories.
 49:      * @param  mixed
 50:      * @return Finder
 51:      */
 52:     public static function find($mask)
 53:     {
 54:         if (!is_array($mask)) {
 55:             $mask = func_get_args();
 56:         }
 57:         $finder = new static;
 58:         return $finder->select($mask, 'isDir')->select($mask, 'isFile');
 59:     }
 60: 
 61: 
 62:     /**
 63:      * Begins search for files matching mask.
 64:      * @param  mixed
 65:      * @return Finder
 66:      */
 67:     public static function findFiles($mask)
 68:     {
 69:         if (!is_array($mask)) {
 70:             $mask = func_get_args();
 71:         }
 72:         $finder = new static;
 73:         return $finder->select($mask, 'isFile');
 74:     }
 75: 
 76: 
 77:     /**
 78:      * Begins search for directories matching mask.
 79:      * @param  mixed
 80:      * @return Finder
 81:      */
 82:     public static function findDirectories($mask)
 83:     {
 84:         if (!is_array($mask)) {
 85:             $mask = func_get_args();
 86:         }
 87:         $finder = new static;
 88:         return $finder->select($mask, 'isDir');
 89:     }
 90: 
 91: 
 92:     /**
 93:      * Creates filtering group by mask & type selector.
 94:      * @param  array
 95:      * @param  string
 96:      * @return self
 97:      */
 98:     private function select($masks, $type)
 99:     {
100:         $this->cursor = & $this->groups[];
101:         $pattern = self::buildPattern($masks);
102:         if ($type || $pattern) {
103:             $this->filter(function ($file) use ($type, $pattern) {
104:                 return !$file->isDot()
105:                     && (!$type || $file->$type())
106:                     && (!$pattern || preg_match($pattern, '/' . strtr($file->getSubPathName(), '\\', '/')));
107:             });
108:         }
109:         return $this;
110:     }
111: 
112: 
113:     /**
114:      * Searchs in the given folder(s).
115:      * @param  string|array
116:      * @return self
117:      */
118:     public function in($path)
119:     {
120:         if (!is_array($path)) {
121:             $path = func_get_args();
122:         }
123:         $this->maxDepth = 0;
124:         return $this->from($path);
125:     }
126: 
127: 
128:     /**
129:      * Searchs recursively from the given folder(s).
130:      * @param  string|array
131:      * @return self
132:      */
133:     public function from($path)
134:     {
135:         if ($this->paths) {
136:             throw new Nette\InvalidStateException('Directory to search has already been specified.');
137:         }
138:         if (!is_array($path)) {
139:             $path = func_get_args();
140:         }
141:         $this->paths = $path;
142:         $this->cursor = & $this->exclude;
143:         return $this;
144:     }
145: 
146: 
147:     /**
148:      * Shows folder content prior to the folder.
149:      * @return self
150:      */
151:     public function childFirst()
152:     {
153:         $this->order = RecursiveIteratorIterator::CHILD_FIRST;
154:         return $this;
155:     }
156: 
157: 
158:     /**
159:      * Converts Finder pattern to regular expression.
160:      * @param  array
161:      * @return string
162:      */
163:     private static function buildPattern($masks)
164:     {
165:         $pattern = array();
166:         foreach ($masks as $mask) {
167:             $mask = rtrim(strtr($mask, '\\', '/'), '/');
168:             $prefix = '';
169:             if ($mask === '') {
170:                 continue;
171: 
172:             } elseif ($mask === '*') {
173:                 return NULL;
174: 
175:             } elseif ($mask[0] === '/') { // absolute fixing
176:                 $mask = ltrim($mask, '/');
177:                 $prefix = '(?<=^/)';
178:             }
179:             $pattern[] = $prefix . strtr(preg_quote($mask, '#'),
180:                 array('\*\*' => '.*', '\*' => '[^/]*', '\?' => '[^/]', '\[\!' => '[^', '\[' => '[', '\]' => ']', '\-' => '-'));
181:         }
182:         return $pattern ? '#/(' . implode('|', $pattern) . ')\z#i' : NULL;
183:     }
184: 
185: 
186:     /********************* iterator generator ****************d*g**/
187: 
188: 
189:     /**
190:      * Returns iterator.
191:      * @return \Iterator
192:      */
193:     public function getIterator()
194:     {
195:         if (!$this->paths) {
196:             throw new Nette\InvalidStateException('Call in() or from() to specify directory to search.');
197: 
198:         } elseif (count($this->paths) === 1) {
199:             return $this->buildIterator($this->paths[0]);
200: 
201:         } else {
202:             $iterator = new \AppendIterator();
203:             $iterator->append($workaround = new \ArrayIterator(array('workaround PHP bugs #49104, #63077')));
204:             foreach ($this->paths as $path) {
205:                 $iterator->append($this->buildIterator($path));
206:             }
207:             unset($workaround[0]);
208:             return $iterator;
209:         }
210:     }
211: 
212: 
213:     /**
214:      * Returns per-path iterator.
215:      * @param  string
216:      * @return \Iterator
217:      */
218:     private function buildIterator($path)
219:     {
220:         $iterator = new \RecursiveDirectoryIterator($path, \RecursiveDirectoryIterator::FOLLOW_SYMLINKS);
221: 
222:         if ($this->exclude) {
223:             $filters = $this->exclude;
224:             $iterator = new Nette\Iterators\RecursiveFilter($iterator, function ($foo, $bar, $file) use ($filters) {
225:                 if (!$file->isDot() && !$file->isFile()) {
226:                     foreach ($filters as $filter) {
227:                         if (!call_user_func($filter, $file)) {
228:                             return FALSE;
229:                         }
230:                     }
231:                 }
232:                 return TRUE;
233:             });
234:         }
235: 
236:         if ($this->maxDepth !== 0) {
237:             $iterator = new RecursiveIteratorIterator($iterator, $this->order);
238:             $iterator->setMaxDepth($this->maxDepth);
239:         }
240: 
241:         if ($this->groups) {
242:             $groups = $this->groups;
243:             $iterator = new Nette\Iterators\Filter($iterator, function ($foo, $bar, $file) use ($groups) {
244:                 foreach ($groups as $filters) {
245:                     foreach ($filters as $filter) {
246:                         if (!call_user_func($filter, $file)) {
247:                             continue 2;
248:                         }
249:                     }
250:                     return TRUE;
251:                 }
252:                 return FALSE;
253:             });
254:         }
255: 
256:         return $iterator;
257:     }
258: 
259: 
260:     /********************* filtering ****************d*g**/
261: 
262: 
263:     /**
264:      * Restricts the search using mask.
265:      * Excludes directories from recursive traversing.
266:      * @param  mixed
267:      * @return self
268:      */
269:     public function exclude($masks)
270:     {
271:         if (!is_array($masks)) {
272:             $masks = func_get_args();
273:         }
274:         $pattern = self::buildPattern($masks);
275:         if ($pattern) {
276:             $this->filter(function ($file) use ($pattern) {
277:                 return !preg_match($pattern, '/' . strtr($file->getSubPathName(), '\\', '/'));
278:             });
279:         }
280:         return $this;
281:     }
282: 
283: 
284:     /**
285:      * Restricts the search using callback.
286:      * @param  callable
287:      * @return self
288:      */
289:     public function filter($callback)
290:     {
291:         $this->cursor[] = $callback;
292:         return $this;
293:     }
294: 
295: 
296:     /**
297:      * Limits recursion level.
298:      * @param  int
299:      * @return self
300:      */
301:     public function limitDepth($depth)
302:     {
303:         $this->maxDepth = $depth;
304:         return $this;
305:     }
306: 
307: 
308:     /**
309:      * Restricts the search by size.
310:      * @param  string  "[operator] [size] [unit]" example: >=10kB
311:      * @param  int
312:      * @return self
313:      */
314:     public function size($operator, $size = NULL)
315:     {
316:         if (func_num_args() === 1) { // in $operator is predicate
317:             if (!preg_match('#^(?:([=<>!]=?|<>)\s*)?((?:\d*\.)?\d+)\s*(K|M|G|)B?\z#i', $operator, $matches)) {
318:                 throw new Nette\InvalidArgumentException('Invalid size predicate format.');
319:             }
320:             list(, $operator, $size, $unit) = $matches;
321:             static $units = array('' => 1, 'k' => 1e3, 'm' => 1e6, 'g' => 1e9);
322:             $size *= $units[strtolower($unit)];
323:             $operator = $operator ? $operator : '=';
324:         }
325:         return $this->filter(function ($file) use ($operator, $size) {
326:             return Finder::compare($file->getSize(), $operator, $size);
327:         });
328:     }
329: 
330: 
331:     /**
332:      * Restricts the search by modified time.
333:      * @param  string  "[operator] [date]" example: >1978-01-23
334:      * @param  mixed
335:      * @return self
336:      */
337:     public function date($operator, $date = NULL)
338:     {
339:         if (func_num_args() === 1) { // in $operator is predicate
340:             if (!preg_match('#^(?:([=<>!]=?|<>)\s*)?(.+)\z#i', $operator, $matches)) {
341:                 throw new Nette\InvalidArgumentException('Invalid date predicate format.');
342:             }
343:             list(, $operator, $date) = $matches;
344:             $operator = $operator ? $operator : '=';
345:         }
346:         $date = Nette\DateTime::from($date)->format('U');
347:         return $this->filter(function ($file) use ($operator, $date) {
348:             return Finder::compare($file->getMTime(), $operator, $date);
349:         });
350:     }
351: 
352: 
353:     /**
354:      * Compares two values.
355:      * @param  mixed
356:      * @param  mixed
357:      * @return bool
358:      */
359:     public static function compare($l, $operator, $r)
360:     {
361:         switch ($operator) {
362:             case '>':
363:                 return $l > $r;
364:             case '>=':
365:                 return $l >= $r;
366:             case '<':
367:                 return $l < $r;
368:             case '<=':
369:                 return $l <= $r;
370:             case '=':
371:             case '==':
372:                 return $l == $r;
373:             case '!':
374:             case '!=':
375:             case '<>':
376:                 return $l != $r;
377:             default:
378:                 throw new Nette\InvalidArgumentException("Unknown operator $operator.");
379:         }
380:     }
381: 
382: }
383: 
Nette 2.1 API documentation generated by ApiGen 2.8.0