LoginSignup
5
7

More than 5 years have passed since last update.

[PHP]ジェネレーターを用いた再帰

Last updated at Posted at 2014-11-08

今さら感がありますが、PHP5.5で追加されたジェネレータの再帰で少しハマったのでメモ。
ジェネレータを使った再帰を試してみたくて、ファイル探索で試してみた。
基本的には、参考URLの「1. scandir()とis_file()/is_dir()を組み合わせる」の方法を
ジェネレータの再帰で書きなおしてみました。
んーなんか無理矢理感があるけど、これでよいのかな??

参考:
(PHPで)指定ディレクトリ以下を全部チェックしてファイル一覧を取得する方法
http://blog.asial.co.jp/1250

書き直したもの。

FindFile.php
/*
 *再帰的に特定ディレクトからファイル名の完全一致で検索する
 */
class FindFile
{
    /**
     * 再帰的に指定フォルダ以下からファイル名の完全一致からファイルを探す
     * @param $dir
     * @param $filename
     * @return \Generator
     */
    public static function find($dir, $filename)
    {
        foreach (self::ls($dir) as $data) {
            if ($data['name'] === $filename) {
                yield $data;
            }
        }
    }

    /**
     * 再帰的に指定フォルダ以下のファイル一覧を取得
     * @param $dir
     * @return \Generator
     */
    public static function ls($dir)
    {
        $files = scandir($dir);
        $files = array_filter($files, function ($file) {
            return !in_array($file, array('.', '..'));
        });
        foreach ($files as $file) {
            $fullPath = rtrim($dir, '/') . '/' . $file;
            if (is_dir($fullPath)) {
                foreach (self::ls($fullPath) as $res) {
                    yield $res;
                }
            } else {
                yield ['dir' => $dir . '/', 'name' => $file];
            }
        }

    }
}
5
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
7