Hardis/models/Csvdb.php

89 lines
2.2 KiB
PHP
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* Class Csvdb
*
* Singleton
* Stock en son objet l'intégralité du fichier CSV (performance)
*/
class Csvdb {
private $_db = array();
private static $_instance;
private $_filename = 'db.csv';
/**
* Csvdb constructor.
*
* Le contructeur se charge de contruire la base de donnée interne au singleton ($_bd)
*/
protected function __construct()
{
if (file_exists($this->_filename)) {
$i = 0;
$headers = array();
$filedata = file($this->_filename);
for ($i = 0; $i < count($filedata); $i++) {
// Première ligne, index 0 = headers
if (!$i) {
foreach (str_getcsv($filedata[$i], ';') as $headerdata) {
$headers[] = trim($headerdata);
}
} else {
$linedata = str_getcsv($filedata[$i], ';');
$nline = $i - 1;
$this->_db[$nline] = array();
for ($j = 0; $j < count($linedata); $j++) {
$this->_db[$nline][$headers[$j]] = trim($linedata[$j]);
}
}
}
if (empty($this->_db)) {
throw new Exception('Aucun adhérent nest présent', 200);
}
} else {
throw new Exception('Le fichier dentrée est introuvable', 404);
}
}
/**
* @return Csvdb
*
* Retourne l'instance du Singleton
*/
public static function getInstance() {
if (is_null(self::$_instance)) {
self::$_instance = new Csvdb();
}
return self::$_instance;
}
/**
* @param $id
* @return array|null
*
* Retourne un adhérent en fonction de son identifiant
*/
public function get($id) {
foreach ($this->_db as $item) {
if ($item['identifiant'] == $id) {
return $item;
}
}
return null;
}
/**
* @return array
*
* Retourne toute la base de données
*/
public function getAll() {
return $this->_db;
}
}