1
|
|
|
<?php
|
2
|
|
|
/**
|
3
|
|
|
* This file is part of the O2System Framework package.
|
4
|
|
|
*
|
5
|
|
|
* For the full copyright and license information, please view the LICENSE
|
6
|
|
|
* file that was distributed with this source code.
|
7
|
|
|
*
|
8
|
|
|
* @author Steeve Andrian Salim
|
9
|
|
|
* @copyright Copyright (c) Steeve Andrian Salim
|
10
|
|
|
*/
|
11
|
|
|
|
12
|
|
|
// ------------------------------------------------------------------------
|
13
|
|
|
|
14
|
|
|
namespace O2System\Filesystem\Files;
|
15
|
|
|
|
16
|
|
|
// ------------------------------------------------------------------------
|
17
|
|
|
|
18
|
|
|
use O2System\Filesystem\File;
|
19
|
|
|
use O2System\Filesystem\Files\Abstracts\AbstractFile;
|
20
|
|
|
use O2System\Spl\DataStructures\SplArrayObject;
|
21
|
|
|
use O2System\Spl\Iterators\ArrayIterator;
|
22
|
|
|
|
23
|
|
|
/**
|
24
|
|
|
* Class JsonFile
|
25
|
|
|
*
|
26
|
|
|
* @package O2System\Filesystem\Factory
|
27
|
|
|
*/
|
28
|
|
|
class JsonFile extends AbstractFile
|
29
|
|
|
{
|
30
|
|
|
protected $fileExtension = '.json';
|
31
|
|
|
|
32
|
|
|
/**
|
33
|
|
|
* JsonFile::readFile
|
34
|
|
|
*
|
35
|
|
|
* @param string $filePath Path to the file.
|
36
|
|
|
* @param array $options Read file options.
|
37
|
|
|
*
|
38
|
|
|
* @return mixed
|
39
|
|
|
*/
|
40
|
|
|
public function readFile($filePath = null, array $options = [])
|
41
|
|
|
{
|
42
|
|
|
$filePath = empty($filePath)
|
43
|
|
|
? $this->filePath
|
44
|
|
|
: $filePath;
|
45
|
|
|
|
46
|
|
|
$result = new ArrayIterator();
|
47
|
|
|
|
48
|
|
|
if (false !== ($contents = json_decode(file_get_contents($filePath), true))) {
|
49
|
|
|
if (json_last_error() === JSON_ERROR_NONE) {
|
50
|
|
|
foreach ($contents as $content) {
|
51
|
|
|
$result[] = new SplArrayObject($content);
|
52
|
|
|
}
|
53
|
|
|
}
|
54
|
|
|
}
|
55
|
|
|
|
56
|
|
|
return $result;
|
57
|
|
|
}
|
58
|
|
|
|
59
|
|
|
// ------------------------------------------------------------------------
|
60
|
|
|
|
61
|
|
|
/**
|
62
|
|
|
* JsonFile::writeFile
|
63
|
|
|
*
|
64
|
|
|
* @param string $filePath Path to the file.
|
65
|
|
|
* @param array $options Write file options.
|
66
|
|
|
*
|
67
|
|
|
* @return bool Returns TRUE on success or FALSE on failure.
|
68
|
|
|
*/
|
69
|
|
|
public function writeFile($filePath = null, array $options = [])
|
70
|
|
|
{
|
71
|
|
|
$filePath = empty($filePath)
|
72
|
|
|
? $this->filePath
|
73
|
|
|
: $filePath;
|
74
|
|
|
|
75
|
|
|
if ($this->count()) {
|
76
|
|
|
return (new File())->write($filePath, json_encode($this->getArrayCopy(), JSON_PRETTY_PRINT));
|
77
|
|
|
}
|
78
|
|
|
}
|
79
|
|
|
} |