レポジトリ種類: SVN
<?php
namespace Site\Controller;
class BlogPost {
/**
* ブログ投稿を取得する
*
* @return array 投稿の配列
*/
public function getPosts(): array {
$path = ROOT.'/blog/';
$posts = [];
if (!is_dir($path)) return $posts;
$files = glob($path.'/*.md');
foreach ($files as $file) {
$content = file_get_contents($file);
$parts = explode('----', $content, 2);
if (count($parts) != 2) continue;
$metadata = [];
$meta = explode("\n", trim($parts[0]));
foreach ($meta as $line) {
$line = trim($line);
if (empty($line)) continue;
$colonPos = strpos($line, ':');
if ($colonPos === false) continue;
$key = trim(substr($line, 0, $colonPos));
$value = trim(substr($line, $colonPos + 1));
$value = trim($value, '"\'');
if ($key == 'category') {
$metadata[$key] = array_map('trim', explode(',', $value));
} else {
$metadata[$key] = $value;
}
}
$articleBody = trim($parts[1]);
$preview = mb_substr(strip_tags($articleBody), 0, 50) . '...';
$slug = basename($file, '.md');
$posts[] = [
'title' => $metadata['title'] ?? '',
'date' => $metadata['date'] ?? '',
'thumbnail' => $metadata['thumbnail'] ?? '',
'thumborient' => $metadata['thumborient'] ?? '',
'category' => $metadata['category'] ?? [],
'uuid' => $metadata['uuid'] ?? '',
'preview' => $preview,
'slug' => $slug,
];
}
// 日付でソート(新しい順)
usort($posts, function($a, $b) {
return strtotime($b['date']) - strtotime($a['date']);
});
return $posts;
}
}