5
5
The Finder Component
6
6
====================
7
7
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.
10
10
11
11
Installation
12
12
------------
@@ -28,57 +28,36 @@ directories::
28
28
use Symfony\Component\Finder\Finder;
29
29
30
30
$finder = new Finder();
31
+ // find all files in the current directory
31
32
$finder->files()->in(__DIR__);
32
33
33
10000
code>
- 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
+ // ...
42
37
}
43
38
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();
51
42
52
- .. tip ::
43
+ // ...
44
+ }
53
45
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.
58
49
59
50
.. caution ::
60
51
61
52
The ``Finder `` object doesn't reset its internal state automatically.
62
53
This means that you need to create a new instance if you do not want
63
54
get mixed results.
64
55
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
+ -----------------------------------
78
58
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 `_.
82
61
83
62
Location
84
63
~~~~~~~~
@@ -97,12 +76,11 @@ Search in several locations by chaining calls to
97
76
// same as above
98
77
$finder->in(__DIR__)->in('/elsewhere');
99
78
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)::
101
81
102
82
$finder->in('src/Symfony/*/*/Resources');
103
83
104
- Each pattern has to resolve to at least one directory path.
105
-
106
84
Exclude directories from matching with the
107
85
:method: `Symfony\\ Component\\ Finder\\ Finder::exclude ` method::
108
86
@@ -114,7 +92,7 @@ It's also possible to ignore directories that you don't have permission to read:
114
92
$finder->ignoreUnreadableDirs()->in(__DIR__);
115
93
116
94
As 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.) ::
118
96
119
97
// always add a trailing slash when looking for in the FTP root dir
120
98
$finder->in('ftp://example.com/');
@@ -126,18 +104,19 @@ And it also works with user-defined streams::
126
104
127
105
use Symfony\Component\Finder\Finder;
128
106
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();
131
110
132
111
$finder = new Finder();
133
112
$finder->name('photos*')->size('< 100K')->date('since 1 hour ago');
134
113
foreach ($finder->in('s3://bucket-name') as $file) {
135
114
// ... do something with the file
136
115
}
137
116
138
- .. note ::
117
+ .. seealso ::
139
118
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.
141
120
142
121
Files or Directories
143
122
~~~~~~~~~~~~~~~~~~~~
@@ -146,63 +125,30 @@ By default, the Finder returns files and directories; but the
146
125
:method: `Symfony\\ Component\\ Finder\\ Finder::files ` and
147
126
:method: `Symfony\\ Component\\ Finder\\ Finder::directories ` methods control that::
148
127
128
+ // look for files only; ignore directories
149
129
$finder->files();
150
130
131
+ // look for directories only; ignore files
151
132
$finder->directories();
152
133
153
- If you want to follow links, use the ``followLinks() `` method::
134
+ If you want to follow ` symbolic links`_ , use the ``followLinks() `` method::
154
135
155
136
$finder->files()->followLinks();
156
137
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
+ ~~~~~~~~~~~~~~~~~~~~~
183
140
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::
196
145
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);
201
147
202
148
File Name
203
149
~~~~~~~~~
204
150
205
- Restrict files by name with the
151
+ Find files by name with the
206
152
:method: `Symfony\\ Component\\ Finder\\ Finder::name ` method::
207
153
208
154
$finder->files()->name('*.php');
@@ -233,7 +179,7 @@ Multiple filenames can be excluded by chaining calls or passing an array::
233
179
File Contents
234
180
~~~~~~~~~~~~~
235
181
236
- Restrict files by contents with the
182
+ Find files by content with the
237
183
:method: `Symfony\\ Component\\ Finder\\ Finder::contains ` method::
238
184
239
185
$finder->files()->contains('lorem ipsum');
@@ -249,15 +195,16 @@ The ``notContains()`` method excludes files containing given pattern::
249
195
Path
250
196
~~~~
251
197
252
- Restrict files and directories by path with the
198
+ Find files and directories by path with the
253
199
:method: `Symfony\\ Component\\ Finder\\ Finder::path ` method::
254
200
255
201
// matches files that contain "data" anywhere in their paths (files or directories)
256
202
$finder->path('data');
257
203
// for example this will match data/*.xml and data.xml if they exist
258
204
$finder->path('data')->name('*.xml');
259
205
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.
261
208
262
209
The ``path() `` method accepts a string, a regular expression or an array of
263
210
strings or regulars expressions::
@@ -275,12 +222,15 @@ Multiple paths can be defined by chaining calls or passing an array::
275
222
Internally, strings are converted into regular expressions by escaping slashes
276
223
and adding delimiters:
277
224
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
+ ===================== =======================
282
231
283
- The :method: `Symfony\\ Component\\ Finder\\ Finder::notPath ` method excludes files by path::
232
+ The :method: `Symfony\\ Component\\ Finder\\ Finder::notPath ` me
F438
thod excludes files
233
+ by path::
284
234
285
235
$finder->notPath('other/dir');
286
236
@@ -299,7 +249,7 @@ Multiple paths can be excluded by chaining calls or passing an array::
299
249
File Size
300
250
~~~~~~~~~
301
251
302
- Restrict files by size with the
252
+ Find files by size with the
303
253
:method: `Symfony\\ Component\\ Finder\\ Finder::size ` method::
304
254
305
255
$finder->files()->size('< 1.5K');
@@ -311,8 +261,8 @@ Restrict by a size range by chaining calls or passing an array::
311
261
// same as above
312
262
$finder->files()->size(['>= 1K', '<= 2K']);
313
263
314
- The comparison operator can be any of the following: ``> ``, ``>= ``, ``< ``, `` <= ``,
315
- ``== ``, ``!= ``.
264
+ The comparison operator can be any of the following: ``> ``, ``>= ``, ``< ``,
265
+ ``<= ``, `` == ``, ``!= ``.
316
266
317
267
The target value may use magnitudes of kilobytes (``k ``, ``ki ``), megabytes
318
268
(``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`_.
321
271
File Date
322
272
~~~~~~~~~
323
273
324
- Restrict files by last modified dates with the
274
+ Find files by last modified dates with the
325
275
:method: `Symfony\\ Component\\ Finder\\ Finder::date ` method::
326
276
327
277
$finder->date('since yesterday');
@@ -333,16 +283,16 @@ Restrict by a date range by chaining calls or passing an array::
333
283
// same as above
334
284
$finder->date(['>= 2018-01-01', '<= 2018-12-31']);
335
285
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 ``< ``.
339
289
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 `.
341
291
342
292
Directory Depth
343
293
~~~~~~~~~~~~~~~
344
294
345
- By default, the Finder recursively traverse directories. Restrict the depth of
295
+ By default, the Finder recursively traverses directories. Restrict the depth of
346
296
traversing with :method: `Symfony\\ Component\\ Finder\\ Finder::depth `::
347
297
348
298
$finder->depth('== 0');
@@ -371,7 +321,7 @@ This will exclude files based on ``.gitignore`` rules as git does.
371
321
Custom Filtering
372
322
~~~~~~~~~~~~~~~~
373
323
374
- To restrict the matching file with your own strategy, use
324
+ To filter results with your own strategy, use
375
325
:method: `Symfony\\ Component\\ Finder\\ Finder::filter `::
376
326
377
327
$filter = function (\SplFileInfo $file)
@@ -388,8 +338,63 @@ it is called with the file as a :class:`Symfony\\Component\\Finder\\SplFileInfo`
388
338
instance. The file is excluded from the result set if the Closure returns
389
339
``false ``.
390
340
341
+ Sorting Results
342
+ ---------------
343
+
344
+ Sort the results by name or by type (directories first, then files)::
345
+
346
+ $finder->sortByName();
347
+
348
+ $finder->sortByType();
349
+
350
+ .. tip ::
351
+
352
+ By default, the ``sortByName() `` method uses the :phpfunction: `strcmp ` PHP
353
+ function (e.g. ``file1.txt ``, ``file10.txt ``, ``file2.txt ``). Pass ``true ``
354
+ as its argument to use PHP's `natural sort order `_ algorithm instead (e.g.
355
+ ``file1.txt ``, ``file2.txt ``, ``file10.txt ``).
356
+
357
+ Sort the files and directories by the last accessed, changed or modified time::
358
+
359
+ $finder->sortByAccessedTime();
360
+
361
+ $finder->sortByChangedTime();
362
+
363
+ $finder->sortByModifiedTime();
364
+
365
+ You can also define your own sorting algorithm with the ``sort() `` method::
366
+
367
+ $finder->sort(function (\SplFileInfo $a, \SplFileInfo $b) {
368
+ return strcmp($a->getRealPath(), $b->getRealPath());
369
+ });
370
+
371
+ You can reverse any sorting by using the ``reverseSorting() `` method::
372
+
373
+ // results will be sorted "Z to A" instead of the default "A to Z"
374
+ $finder->sortByName()->reverseSorting();
375
+
376
+ .. note ::
377
+
378
+ Notice that the ``sort* `` methods need to get all matching elements to do
379
+ their jobs. For large iterators, it is slow.
380
+
381
+ Transforming Results into Arrays
382
+ --------------------------------
383
+
384
+ A Finder instance is an :phpclass: `IteratorAggregate ` PHP class. So, in addition
385
+ to iterating over the Finder results with ``foreach ``, you can also convert it
386
+ to an array with the :phpfunction: `iterator_to_array ` function, or get the
387
+ number of items with :phpfunction: `iterator_count `.
388
+
389
+ If you call to the :method: `Symfony\\ Component\\ Finder\\ Finder::in ` method more
390
+ than once to search through multiple locations, pass ``false `` as a second
391
+ parameter to :phpfunction: `iterator_to_array ` to avoid issues (a separate
392
+ iterator is created for each location and, if you don't pass ``false `` to
393
+ :phpfunction: `iterator_to_array `, keys of result sets are used and some of them
394
+ might be duplicated and their values overwritten).
395
+
391
396
Reading Contents of Returned Files
392
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
397
+ ----------------------------------
393
398
394
399
The contents of returned files can be read with
395
400
:method: `Symfony\\ Component\\ Finder\\ SplFileInfo::getContents `::
@@ -405,9 +410,11 @@ The contents of returned files can be read with
405
410
// ...
406
411
}
407
412
408
- .. _strtotime : https://php.net/manual/en/datetime.formats.php
409
- .. _protocol : https://php.net/manual/en/wrappers.php
410
- .. _Streams : https://php.net/streams
411
- .. _IEC standard : https://physics.nist.gov/cuu/Units/binary.html
412
- .. _Packagist : https://packagist.org/packages/symfony/finder
413
+ .. _`fluent interface` : https://en.wikipedia.org/wiki/Fluent_interface
414
+ .. _`symbolic links` : https://en.wikipedia.org/wiki/Symbolic_link
415
+ .. _`Version Control Systems` : https://en.wikipedia.org/wiki/Version_control
416
+ .. _`PHP wrapper for URL-style protocols` : https://php.net/manual/en/wrappers.php
417
+ .. _`PHP streams` : https://php.net/streams
418
+ .. _`IEC standard` : https://physics.nist.gov/cuu/Units/binary.html
419
+ .. _`Packagist` : https://packagist.org/packages/symfony/finder
413
420
.. _`natural sort order` : https://en.wikipedia.org/wiki/Natural_sort_order
0 commit comments