Lectures/includes/stories.php

61 lines
2.0 KiB
PHP
Raw Normal View History

2025-02-14 17:12:59 +01:00
<?php
class Stories {
private static $storiesDir = __DIR__ . '/../stories/';
public static function getAll() {
self::ensureDirectoryExists();
2025-02-14 17:12:59 +01:00
$stories = [];
foreach (glob(self::$storiesDir . '*.json') as $file) {
$story = json_decode(file_get_contents($file), true);
$stories[] = $story;
}
return $stories;
}
public static function get($id) {
self::ensureDirectoryExists();
2025-02-14 17:12:59 +01:00
$file = self::$storiesDir . $id . '.json';
if (!file_exists($file)) {
return null;
}
return json_decode(file_get_contents($file), true);
}
public static function save($story) {
self::ensureDirectoryExists();
// Vérifier que l'ID est valide
if (empty($story['id'])) {
throw new Exception('L\'ID du roman est requis');
}
// Créer le chemin complet du fichier
2025-02-14 17:12:59 +01:00
$file = self::$storiesDir . $story['id'] . '.json';
// Encoder en JSON avec options de formatage
$jsonContent = json_encode($story, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
if ($jsonContent === false) {
throw new Exception('Erreur lors de l\'encodage JSON: ' . json_last_error_msg());
}
// Écrire le fichier
$bytesWritten = file_put_contents($file, $jsonContent);
if ($bytesWritten === false) {
throw new Exception('Erreur lors de l\'écriture du fichier: ' . error_get_last()['message']);
}
return $bytesWritten;
}
private static function ensureDirectoryExists() {
if (!file_exists(self::$storiesDir)) {
if (!mkdir(self::$storiesDir, 0755, true)) {
throw new Exception('Impossible de créer le dossier stories/');
}
}
if (!is_writable(self::$storiesDir)) {
throw new Exception('Le dossier stories/ n\'est pas accessible en écriture');
}
2025-02-14 17:12:59 +01:00
}
}