3 namespace Shaarli\Bookmark
;
5 use Shaarli\Bookmark\Exception\EmptyDataStoreException
;
6 use Shaarli\Bookmark\Exception\NotWritableDataStoreException
;
7 use Shaarli\Config\ConfigManager
;
12 * This class performs read/write operation to the file data store.
13 * Used by BookmarkFileService.
15 * @package Shaarli\Bookmark
20 * @var string Datastore file path
25 * @var ConfigManager instance
30 * string Datastore PHP prefix
32 protected static $phpPrefix = '<?php /* ';
35 * string Datastore PHP suffix
37 protected static $phpSuffix = ' */ ?>';
40 * LinksIO constructor.
42 * @param ConfigManager $conf instance
44 public function __construct($conf)
47 $this->datastore
= $conf->get('resource.datastore');
51 * Reads database from disk to memory
53 * @return BookmarkArray instance
55 * @throws NotWritableDataStoreException Data couldn't be loaded
56 * @throws EmptyDataStoreException Datastore doesn't exist
58 public function read()
60 if (! file_exists($this->datastore
)) {
61 throw new EmptyDataStoreException();
64 if (!is_writable($this->datastore
)) {
65 throw new NotWritableDataStoreException($this->datastore
);
68 // Note that gzinflate is faster than gzuncompress.
69 // See: http://www.php.net/manual/en/function.gzdeflate.php#96439
70 $links = unserialize(gzinflate(base64_decode(
71 substr(file_get_contents($this->datastore
),
72 strlen(self
::$phpPrefix), -strlen(self
::$phpSuffix)))));
75 if (filesize($this->datastore
) > 100) {
76 throw new NotWritableDataStoreException($this->datastore
);
78 throw new EmptyDataStoreException();
85 * Saves the database from memory to disk
87 * @param BookmarkArray $links instance.
89 * @throws NotWritableDataStoreException the datastore is not writable
91 public function write($links)
93 if (is_file($this->datastore
) && !is_writeable($this->datastore
)) {
94 // The datastore exists but is not writeable
95 throw new NotWritableDataStoreException($this->datastore
);
96 } else if (!is_file($this->datastore
) && !is_writeable(dirname($this->datastore
))) {
97 // The datastore does not exist and its parent directory is not writeable
98 throw new NotWritableDataStoreException(dirname($this->datastore
));
103 self
::$phpPrefix.base64_encode(gzdeflate(serialize($links))).self
::$phpSuffix