55The Finder Component
66====================
77
8- The Finder component finds files and directories via an intuitive fluent
9- interface.
8+ The Finder component finds files and directories based on different criteria
9+ (name, file size, modification time, etc.) via an intuitive fluent interface.
1010
1111Installation
1212------------
@@ -28,57 +28,36 @@ directories::
2828 use Symfony\Component\Finder\Finder;
2929
3030 $finder = new Finder();
31+ // find all files in the current directory
3132 $finder->files()->in(__DIR__);
3233
33- foreach ($finder as $file) {
34- // dumps the absolute path
35- var_dump($file->getRealPath());
36-
37- // dumps the relative path to the file, omitting the filename
38- var_dump($file->getRelativePath());
39-
40- // dumps the relative path to the file
41- var_dump($file->getRelativePathname());
34+ // check if there are any search results
35+ if ($finder->hasResults()) {
36+ // ...
4237 }
4338
44- The ``$file `` is an instance of :class: `Symfony\\ Component\\ Finder\\ SplFileInfo `
45- which extends PHP's own :phpclass: `SplFileInfo ` to provide methods to work with relative
46- paths.
47-
48- The above code prints the names of all the files in the current directory
49- recursively. The Finder class uses a fluent interface, so all methods return
50- the Finder instance.
39+ foreach ($finder as $file) {
40+ $absoluteFilePath = $file->getRealPath();
41+ $fileNameWithExtension = $file->getRelativePathname();
5142
52- .. tip ::
43+ // ...
44+ }
5345
54- A Finder instance is a PHP :phpclass: `IteratorAggregate `. So, in addition to iterating over the
55- Finder with ``foreach ``, you can also convert it to an array with the
56- :phpfunction: `iterator_to_array ` function, or get the number of items with
57- :phpfunction: `iterator_count `.
46+ The ``$file `` variable is an instance of
47+ :class: `Symfony\\ Component\\ Finder\\ SplFileInfo ` which extends PHP's own
48+ :phpclass: `SplFileInfo ` to provide methods to work with relative paths.
5849
5950.. caution ::
6051
6152 The ``Finder `` object doesn't reset its internal state automatically.
6253 This means that you need to create a new instance if you do not want
6354 get mixed results.
6455
65- .. caution ::
66-
67- When searching through multiple locations passed to the
68- :method: `Symfony\\ Component\\ Finder\\ Finder::in ` method, a separate iterator
69- is created internally for every location. This means we have multiple result
70- sets aggregated into one.
71- Since :phpfunction: `iterator_to_array ` uses keys of result sets by default,
72- when converting to an array, some keys might be duplicated and their values
73- overwritten. This can be avoided by passing ``false `` as a second parameter
74- to :phpfunction: `iterator_to_array `.
75-
76- Criteria
77- --------
56+ Searching for Files and Directories
57+ -----------------------------------
7858
79- There are lots of ways to filter and sort your results. You can also use the
80- :method: `Symfony\\ Component\\ Finder\\ Finder::hasResults ` method to check if
81- there's any file or directory matching the search criteria.
59+ The component provides lots of methods to define the search criteria. They all
60+ can be chained because they implement a `fluent interface `_.
8261
8362Location
8463~~~~~~~~
@@ -97,12 +76,11 @@ Search in several locations by chaining calls to
9776 // same as above
9877 $finder->in(__DIR__)->in('/elsewhere');
9978
100- Use wildcard characters to search in the directories matching a pattern::
79+ Use ``* `` as a wildcard character to search in the directories matching a
80+ pattern (each pattern has to resolve to at least one directory path)::
10181
10282 $finder->in('src/Symfony/*/*/Resources');
10383
104- Each pattern has to resolve to at least one directory path.
105-
10684Exclude directories from matching with the
10785:method: `Symfony\\ Component\\ Finder\\ Finder::exclude ` method::
10886
@@ -114,7 +92,7 @@ It's also possible to ignore directories that you don't have permission to read:
11492 $finder->ignoreUnreadableDirs()->in(__DIR__);
11593
11694As the Finder uses PHP iterators, you can pass any URL with a supported
117- `protocol `_ ::
95+ `PHP wrapper for URL-style protocols `_ (`` ftp:// ``, `` zlib:// ``, etc.) ::
11896
11997 // always add a trailing slash when looking for in the FTP root dir
12098 $finder->in('ftp://example.com/');
@@ -126,18 +104,19 @@ And it also works with user-defined streams::
126104
127105 use Symfony\Component\Finder\Finder;
128106
129- $s3 = new \Zend_Service_Amazon_S3($key, $secret);
130- $s3->registerStreamWrapper('s3');
107+ // register a 's3://' wrapper with the official AWS SDK
108+ $s3Client = new Aws\S3\S3Client([/* config options */]);
109+ $s3Client->registerStreamWrapper();
131110
132111 $finder = new Finder();
133112 $finder->name('photos*')->size('< 100K')->date('since 1 hour ago');
134113 foreach ($finder->in('s3://bucket-name') as $file) {
135114 // ... do something with the file
136115 }
137116
138- .. note ::
117+ .. seealso ::
139118
140- Read the `Streams `_ documentation to learn how to create your own streams.
119+ Read the `PHP streams `_ documentation to learn how to create your own streams.
141120
142121Files or Directories
143122~~~~~~~~~~~~~~~~~~~~
@@ -146,63 +125,30 @@ By default, the Finder returns files and directories; but the
146125:method: `Symfony\\ Component\\ Finder\\ Finder::files ` and
147126:method: `Symfony\\ Component\\ Finder\\ Finder::directories ` methods control that::
148127
128+ // look for files only; ignore directories
149129 $finder->files();
150130
131+ // look for directories only; ignore files
151132 $finder->directories();
152133
153- If you want to follow links, use the ``followLinks() `` method::
134+ If you want to follow ` symbolic links`_ , use the ``followLinks() `` method::
154135
155136 $finder->files()->followLinks();
156137
157- By default, the iterator ignores popular VCS files. This can be changed with
158- the ``ignoreVCS() `` method::
159-
160- $finder->ignoreVCS(false);
161-
162- Sorting
163- ~~~~~~~
164-
165- Sort the result by name or by type (directories first, then files)::
166-
167- $finder->sortByName();
168-
169- $finder->sortByType();
170-
171- .. tip ::
172-
173- By default, the ``sortByName() `` method uses the :phpfunction: `strcmp ` PHP
174- function (e.g. ``file1.txt ``, ``file10.txt ``, ``file2.txt ``). Pass ``true ``
175- as its argument to use PHP's `natural sort order `_ algorithm instead (e.g.
176- ``file1.txt ``, ``file2.txt ``, ``file10.txt ``).
177-
178- Sort the files and directories by the last accessed, changed or modified time::
179-
180- $finder->sortByAccessedTime();
181-
182- $finder->sortByChangedTime();
138+ Version Control Files
139+ ~~~~~~~~~~~~~~~~~~~~~
183140
184- $finder->sortByModifiedTime();
185-
186- You can also define your own sorting algorithm with ``sort() `` method::
187-
188- $finder->sort(function (\SplFileInfo $a, \SplFileInfo $b) {
189- return strcmp($a->getRealPath(), $b->getRealPath());
190- });
191-
192- You can reverse any sorting by using the ``reverseSorting() `` method::
193-
194- // results will be sorted "Z to A" instead of the default "A to Z"
195- $finder->sortByName()->reverseSorting();
141+ `Version Control Systems `_ (or "VCS" for short), such as Git and Mercurial,
142+ create some special files to store their metadata. Those files are ignored by
143+ default when looking for files and directories, but you can change this with the
144+ ``ignoreVCS() `` method::
196145
197- .. note ::
198-
199- Notice that the ``sort* `` methods need to get all matching elements to do
200- their jobs. For large iterators, it is slow.
146+ $finder->ignoreVCS(false);
201147
202148File Name
203149~~~~~~~~~
204150
205- Restrict files by name with the
151+ Find files by name with the
206152:method: `Symfony\\ Component\\ Finder\\ Finder::name ` method::
207153
208154 $finder->files()->name('*.php');
@@ -233,7 +179,7 @@ Multiple filenames can be excluded by chaining calls or passing an array::
233179File Contents
234180~~~~~~~~~~~~~
235181
236- Restrict files by contents with the
182+ Find files by content with the
237183:method: `Symfony\\ Component\\ Finder\\ Finder::contains ` method::
238184
239185 $finder->files()->contains('lorem ipsum');
@@ -249,15 +195,16 @@ The ``notContains()`` method excludes files containing given pattern::
249195Path
250196~~~~
251197
252- Restrict files and directories by path with the
198+ Find files and directories by path with the
253199:method: `Symfony\\ Component\\ Finder\\ Finder::path ` method::
254200
255201 // matches files that contain "data" anywhere in their paths (files or directories)
256202 $finder->path('data');
257203 // for example this will match data/*.xml and data.xml if they exist
258204 $finder->path('data')->name('*.xml');
259205
260- On all platforms slash (i.e. ``/ ``) should be used as the directory separator.
206+ Use the forward slash (i.e. ``/ ``) as the directory separator on all platforms,
207+ including Windows. The component makes the necessary conversion internally.
261208
262209The ``path() `` method accepts a string, a regular expression or an array of
263210strings or regulars expressions::
@@ -275,12 +222,15 @@ Multiple paths can be defined by chaining calls or passing an array::
275222Internally, strings are converted into regular expressions by escaping slashes
276223and adding delimiters:
277224
278- .. code-block :: text
279-
280- dirname ===> /dirname/
281- a/b/c ===> /a\/b\/c/
225+ ===================== =======================
226+ Original Given String Regular Expression Used
227+ ===================== =======================
228+ ``dirname `` ``/dirname/ ``
229+ ``a/b/c `` ``/a\/b\/c/ ``
230+ ===================== =======================
282231
283- The :method: `Symfony\\ Component\\ Finder\\ Finder::notPath ` method excludes files by path::
232+ The :method: `Symfony\\ Component\\ Finder\\ Finder::notPath ` method excludes files
233+ by path::
284234
285235 $finder->notPath('other/dir');
286236
@@ -299,7 +249,7 @@ Multiple paths can be excluded by chaining calls or passing an array::
299249File Size
300250~~~~~~~~~
301251
302- Restrict files by size with the
252+ Find files by size with the
303253:method: `Symfony\\ Component\\ Finder\\ Finder::size ` method::
304254
305255 $finder->files()->size('< 1.5K');
@@ -311,8 +261,8 @@ Restrict by a size range by chaining calls or passing an array::
311261 // same as above
312262 $finder->files()->size(['>= 1K', '<= 2K']);
313263
314- The comparison operator can be any of the following: ``> ``, ``>= ``, ``< ``, `` <= ``,
315- ``== ``, ``!= ``.
264+ The comparison operator can be any of the following: ``> ``, ``>= ``, ``< ``,
265+ ``<= ``, `` == ``, ``!= ``.
316266
317267The target value may use magnitudes of kilobytes (``k ``, ``ki ``), megabytes
318268(``m ``, ``mi ``), or gigabytes (``g ``, ``gi ``). Those suffixed with an ``i `` use
@@ -321,7 +271,7 @@ the appropriate ``2**n`` version in accordance with the `IEC standard`_.
321271File Date
322272~~~~~~~~~
323273
324- Restrict files by last modified dates with the
274+ Find files by last modified dates with the
325275:method: `Symfony\\ Component\\ Finder\\ Finder::date ` method::
326276
327277 $finder->date('since yesterday');
@@ -333,16 +283,16 @@ Restrict by a date range by chaining calls or passing an array::
333283 // same as above
334284 $finder->date(['>= 2018-01-01', '<= 2018-12-31']);
335285
336- The comparison operator can be any of the following: ``> ``, ``>= ``, ``< ``, `` <= ``,
337- ``== ``. You can also use ``since `` or ``after `` as an alias for ``> ``, and
338- ``until `` or ``before `` as an alias for ``< ``.
286+ The comparison operator can be any of the following: ``> ``, ``>= ``, ``< ``,
287+ ``<= ``, `` == ``. You can also use ``since `` or ``after `` as an alias for ``> ``,
288+ and ``until `` or ``before `` as an alias for ``< ``.
339289
340- The target value can be any date supported by the `strtotime `_ function .
290+ The target value can be any date supported by :phpfunction: `strtotime `.
341291
342292Directory Depth
343293~~~~~~~~~~~~~~~
344294
345- By default, the Finder recursively traverse directories. Restrict the depth of
295+ By default, the Finder recursively traverses directories. Restrict the depth of
346296traversing with :method: `Symfony\\ Component\\ Finder\\ Finder::depth `::
347297
348298 $finder->depth('== 0');
@@ -358,7 +308,7 @@ Restrict by a depth range by chaining calls or passing an array::
358308Custom Filtering
359309~~~~~~~~~~~~~~~~
360310
361- To restrict the matching file with your own strategy, use
311+ To filter results with your own strategy, use
362312:method: `Symfony\\ Component\\ Finder\\ Finder::filter `::
363313
364314 $filter = function (\SplFileInfo $file)
@@ -375,8 +325,63 @@ it is called with the file as a :class:`Symfony\\Component\\Finder\\SplFileInfo`
375325instance. The file is excluded from the result set if the Closure returns
376326``false ``.
377327
328+ Sorting Results
329+ ---------------
330+
331+ Sort the results by name or by type (directories first, then files)::
332+
333+ $finder->sortByName();
334+
335+ $finder->sortByType();
336+
337+ .. tip ::
338+
339+ By default, the ``sortByName() `` method uses the :phpfunction: `strcmp ` PHP
340+ function (e.g. ``file1.txt ``, ``file10.txt ``, ``file2.txt ``). Pass ``true ``
341+ as its argument to use PHP's `natural sort order `_ algorithm instead (e.g.
342+ ``file1.txt ``, ``file2.txt ``, ``file10.txt ``).
343+
344+ Sort the files and directories by the last accessed, changed or modified time::
345+
346+ $finder->sortByAccessedTime();
347+
348+ $finder->sortByChangedTime();
349+
350+ $finder->sortByModifiedTime();
351+
352+ You can also define your own sorting algorithm with the ``sort() `` method::
353+
354+ $finder->sort(function (\SplFileInfo $a, \SplFileInfo $b) {
355+ return strcmp($a->getRealPath(), $b->getRealPath());
356+ });
357+
358+ You can reverse any sorting by using the ``reverseSorting() `` method::
359+
360+ // results will be sorted "Z to A" instead of the default "A to Z"
361+ $finder->sortByName()->reverseSorting();
362+
363+ .. note ::
364+
365+ Notice that the ``sort* `` methods need to get all matching elements to do
366+ their jobs. For large iterators, it is slow.
367+
368+ Transforming Results into Arrays
369+ --------------------------------
370+
371+ A Finder instance is an :phpclass: `IteratorAggregate ` PHP class. So, in addition
372+ to iterating over the Finder results with ``foreach ``, you can also convert it
373+ to an array with the :phpfunction: `iterator_to_array ` function, or get the
374+ number of items with :phpfunction: `iterator_count `.
375+
376+ If you call to the :method: `Symfony\\ Component\\ Finder\\ Finder::in ` method more
377+ than once to search through multiple locations, pass ``false `` as a second
378+ parameter to :phpfunction: `iterator_to_array ` to avoid issues (a separate
379+ iterator is created for each location and, if you don't pass ``false `` to
380+ :phpfunction: `iterator_to_array `, keys of result sets are used and some of them
381+ might be duplicated and their values overwritten).
382+
378383Reading Contents of Returned Files
379- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
384+ ----------------------------------
380385
381386The contents of returned files can be read with
382387:method: `Symfony\\ Component\\ Finder\\ SplFileInfo::getContents `::
@@ -392,9 +397,11 @@ The contents of returned files can be read with
392397 // ...
393398 }
394399
395- .. _strtotime : https://php.net/manual/en/datetime.formats.php
396- .. _protocol : https://php.net/manual/en/wrappers.php
397- .. _Streams : https://php.net/streams
398- .. _IEC standard : https://physics.nist.gov/cuu/Units/binary.html
399- .. _Packagist : https://packagist.org/packages/symfony/finder
400+ .. _`fluent interface` : https://en.wikipedia.org/wiki/Fluent_interface
401+ .. _`symbolic links` : https://en.wikipedia.org/wiki/Symbolic_link
402+ .. _`Version Control Systems` : https://en.wikipedia.org/wiki/Version_control
403+ .. _`PHP wrapper for URL-style protocols` : https://php.net/manual/en/wrappers.php
404+ .. _`PHP streams` : https://php.net/streams
405+ .. _`IEC standard` : https://physics.nist.gov/cuu/Units/binary.html
406+ .. _`Packagist` : https://packagist.org/packages/symfony/finder
400407.. _`natural sort order` : https://en.wikipedia.org/wiki/Natural_sort_order
0 commit comments