1<?php
2
3/*
4 * This file is part of the Symfony package.
5 *
6 * (c) Fabien Potencier <fabien@symfony.com>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Symfony\Component\Finder\Iterator;
13
14/**
15 * FilecontentFilterIterator filters files by their contents using patterns (regexps or strings).
16 *
17 * @author Fabien Potencier  <fabien@symfony.com>
18 * @author Włodzimierz Gajda <gajdaw@gajdaw.pl>
19 */
20class FilecontentFilterIterator extends MultiplePcreFilterIterator
21{
22    /**
23     * Filters the iterator values.
24     *
25     * @return bool true if the value should be kept, false otherwise
26     */
27    public function accept()
28    {
29        if (!$this->matchRegexps && !$this->noMatchRegexps) {
30            return true;
31        }
32
33        $fileinfo = $this->current();
34
35        if ($fileinfo->isDir() || !$fileinfo->isReadable()) {
36            return false;
37        }
38
39        $content = $fileinfo->getContents();
40        if (!$content) {
41            return false;
42        }
43
44        return $this->isAccepted($content);
45    }
46
47    /**
48     * Converts string to regexp if necessary.
49     *
50     * @param string $str Pattern: string or regexp
51     *
52     * @return string regexp corresponding to a given string or regexp
53     */
54    protected function toRegex(string $str)
55    {
56        return $this->isRegex($str) ? $str : '/'.preg_quote($str, '/').'/';
57    }
58}
59