Skip to content

Instantly share code, notes, and snippets.

@k-holy
Created August 30, 2012 08:22
Show Gist options
  • Save k-holy/3524127 to your computer and use it in GitHub Desktop.
Save k-holy/3524127 to your computer and use it in GitHub Desktop.
Symfony-Finderコンポーネント+Fileinfoのサンプル
<?php
namespace Acme;
include_once realpath(__DIR__ . '/vendor/autoload.php');
use \Symfony\Component\Finder\Finder;
class U {
public static function H($data, $default=null) {
$var = $default;
if (isset($data)) {
$var = htmlspecialchars($data, ENT_QUOTES, 'UTF-8');
}
return $var;
}
}
$getMimeType = new \finfo(FILEINFO_MIME_TYPE);
$targetDir = __DIR__;
$finder = Finder::create()
->files()
->in($targetDir)
// 独自の条件で絞り込む場合はfilter()
->filter(function(\SplFileInfo $file) use ($getMimeType) {
// \Symfony\Component\Finder\SplFileInfo::getRelativePath() で対象ディレクトリからの相対パスからファイル名を除去した情報が取得できる
if (strpos($file->getRelativePath(), 'thumbs') !== 0) {
return false;
}
if (!preg_match('~\A([a-f0-9]{13})-([0-9]+)-([0-9]+)-([0-9]+)\.jpg\z~', $file->getBasename())) {
return false;
}
if ($getMimeType->file($file->getRealPath()) !== 'image/jpeg') {
return false;
}
return true;
})
// 独自のソートを行う場合はsort()
->sort(function(\SplFileInfo $file1, \SplFileInfo $file2) {
return strnatcmp($file1->getRealPath(), $file2->getRealPath());
})
;
$title = sprintf('Example of %s with %s', get_class($finder), get_class($getMimeType));
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title><?=U::H($title)?></title>
</head>
<body>
<h1><?=U::H($title)?></h1>
<?php if (count($finder) >= 1) : ?>
<ul>
<?php foreach ($finder as $file) : ?>
<li>
<dl>
<dt>Basename</dt>
<dd><?=U::H($file->getBasename())?></dd>
<dt>Size</dt>
<dd><?=U::H(number_format($file->getSize()))?></dd>
<dt>MTime</dt>
<dd><?=U::H(date('Y-m-d H:i:s', $file->getMTime()))?></dd>
<dt>RelativePath</dt>
<dd><?=U::H($file->getRelativePath())?></dd>
<dt>RelativePathname</dt>
<!-- Symfony\Component\Finder\SplFileInfo::getRelativePathname() で対象ディレクトリからの相対パスが取得できる -->
<dd><?=U::H($file->getRelativePathname())?></dd>
<dt>Image</dt>
<dd><img src="<?=U::H($file->getRelativePathname())?>" /></dd>
</dl>
</li>
<?php endforeach ?>
</ul>
<?php else : ?>
<p>No files in <?=U::H($targetDir)?></p>
<?php endif ?>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment