3 namespace Shaarli\Bookmark
;
5 use Shaarli\Bookmark\Exception\DatastoreNotInitializedException
;
6 use Shaarli\Bookmark\Exception\EmptyDataStoreException
;
7 use Shaarli\Bookmark\Exception\NotWritableDataStoreException
;
8 use Shaarli\Config\ConfigManager
;
13 * This class performs read/write operation to the file data store.
14 * Used by BookmarkFileService.
16 * @package Shaarli\Bookmark
21 * @var string Datastore file path
26 * @var ConfigManager instance
31 * string Datastore PHP prefix
33 protected static $phpPrefix = '<?php /* ';
36 * string Datastore PHP suffix
38 protected static $phpSuffix = ' */ ?>';
41 * LinksIO constructor.
43 * @param ConfigManager $conf instance
45 public function __construct($conf)
48 $this->datastore
= $conf->get('resource.datastore');
52 * Reads database from disk to memory
54 * @return BookmarkArray instance
56 * @throws NotWritableDataStoreException Data couldn't be loaded
57 * @throws EmptyDataStoreException Datastore file exists but does not contain any bookmark
58 * @throws DatastoreNotInitializedException File does not exists
60 public function read()
62 if (! file_exists($this->datastore
)) {
63 throw new DatastoreNotInitializedException();
66 if (!is_writable($this->datastore
)) {
67 throw new NotWritableDataStoreException($this->datastore
);
70 // Note that gzinflate is faster than gzuncompress.
71 // See: http://www.php.net/manual/en/function.gzdeflate.php#96439
72 $links = unserialize(gzinflate(base64_decode(
73 substr(file_get_contents($this->datastore
),
74 strlen(self
::$phpPrefix), -strlen(self
::$phpSuffix)))));
77 if (filesize($this->datastore
) > 100) {
78 throw new NotWritableDataStoreException($this->datastore
);
80 throw new EmptyDataStoreException();
87 * Saves the database from memory to disk
89 * @param BookmarkArray $links instance.
91 * @throws NotWritableDataStoreException the datastore is not writable
93 public function write($links)
95 if (is_file($this->datastore
) && !is_writeable($this->datastore
)) {
96 // The datastore exists but is not writeable
97 throw new NotWritableDataStoreException($this->datastore
);
98 } else if (!is_file($this->datastore
) && !is_writeable(dirname($this->datastore
))) {
99 // The datastore does not exist and its parent directory is not writeable
100 throw new NotWritableDataStoreException(dirname($this->datastore
));
105 self
::$phpPrefix.base64_encode(gzdeflate(serialize($links))).self
::$phpSuffix