-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBookHandler.php
More file actions
67 lines (58 loc) · 1.65 KB
/
BookHandler.php
File metadata and controls
67 lines (58 loc) · 1.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<?php
require_once("Book.php");
final class BookHandler {
private static $instance = null;
private $fileName;
private $fileStream;
private $books;
private function __construct() {
$this->fileName = "books.json";
$this->fileStream = fopen($this->fileName, "r+") or die("Unable to open/create file");
$this->books = array_map(
array: json_decode(fread($this->fileStream, filesize($this->fileName))),
callback: function($book) {
$bookData = (array) $book;
return new Book(
$bookData["title"],
$bookData["author"],
$bookData["pages"]
);
}
);
}
public function getBooks(): array {return $this->books;}
public function addBook(Book $newBook): bool {
array_push($this->books, $newBook);
$booksData = array_map(
array: $this->books,
callback: function(Book $book) {
return array(
"title"=>$book->getTitle(),
"author"=>$book->getAuthor(),
"pages"=>$book->getPages()
);
}
);
ftruncate($this->fileStream, 0);
fseek($this->fileStream, 0);
fwrite($this->fileStream, json_encode($booksData));
return fflush($this->fileStream);
}
public function exist(Book $newBook): bool {
foreach ($this->books as $key=>$book) {
if (
$book->getTitle() == $newBook->getTitle()
&& $book->getAuthor() == $newBook->getAuthor()
&& $book->getPages() == $newBook->getPages()
) return true;
}
return false;
}
static function getInstance(): BookHandler {
self::$instance = self::$instance == null?
new BookHandler(): self::$instance;
return self::$instance;
}
public function __destruct() {fclose($this->fileStream);}
}
?>