bludit/kernel/abstract/dbjson.class.php

82 lines
1.7 KiB
PHP
Raw Normal View History

2015-05-05 03:00:01 +02:00
<?php defined('BLUDIT') or die('Bludit CMS.');
class dbJSON
{
public $db;
public $file;
public $firstLine;
2015-07-14 04:16:28 +02:00
// $file, the JSON file.
// $firstLine, TRUE if you want to remove the first line, FALSE otherwise.
2015-05-05 03:00:01 +02:00
function __construct($file, $firstLine=true)
{
$this->file = $file;
$this->db = array();
$this->firstLine = $firstLine;
if(file_exists($file))
{
2015-07-14 04:16:28 +02:00
// Read JSON file.
2015-05-05 03:00:01 +02:00
$lines = file($file);
2015-07-14 04:16:28 +02:00
// Remove the first line, the first line is for security reasons.
2015-06-26 06:31:53 +02:00
if($firstLine) {
2015-05-05 03:00:01 +02:00
unset($lines[0]);
}
2015-07-14 04:16:28 +02:00
// Regenerate the JSON file.
2015-05-05 03:00:01 +02:00
$implode = implode($lines);
2015-07-14 04:16:28 +02:00
// Unserialize, JSON to Array.
2015-05-05 03:00:01 +02:00
$this->db = $this->unserialize($implode);
}
else
{
2015-06-27 03:47:12 +02:00
Log::set(__METHOD__.LOG_SEP.'File '.$file.' does not exists');
2015-05-05 03:00:01 +02:00
}
}
2015-07-14 04:16:28 +02:00
// Returns the amount of database items.
2015-06-26 06:31:53 +02:00
public function count()
{
return count($this->db);
}
2015-07-14 04:16:28 +02:00
// Save the JSON file.
2015-05-05 03:00:01 +02:00
public function save()
{
2015-07-14 04:16:28 +02:00
if($this->firstLine) {
2015-05-05 03:00:01 +02:00
$data = "<?php defined('BLUDIT') or die('Bludit CMS.'); ?>".PHP_EOL;
2015-07-14 04:16:28 +02:00
}
else {
2015-05-05 03:00:01 +02:00
$data = '';
2015-07-14 04:16:28 +02:00
}
2015-05-05 03:00:01 +02:00
$data .= $this->serialize($this->db);
// LOCK_EX flag to prevent anyone else writing to the file at the same time.
file_put_contents($this->file, $data, LOCK_EX);
}
private function serialize($data)
{
// DEBUG: La idea es siempre serializar en json, habria que ver si siempre esta cargado json_enconde y decode
2015-07-14 04:16:28 +02:00
if(JSON) {
2015-05-05 03:00:01 +02:00
return json_encode($data, JSON_PRETTY_PRINT);
2015-07-14 04:16:28 +02:00
}
2015-05-05 03:00:01 +02:00
return serialize($data);
}
private function unserialize($data)
{
// DEBUG: La idea es siempre serializar en json, habria que ver si siempre esta cargado json_enconde y decode
2015-07-14 04:16:28 +02:00
if(JSON) {
2015-05-05 03:00:01 +02:00
return json_decode($data, true);
2015-07-14 04:16:28 +02:00
}
2015-05-05 03:00:01 +02:00
return unserialize($data);
}
2015-05-31 03:06:55 +02:00
}