Passed
Push — master ( 184b95...3a4432 )
by 世昌
01:52
created

CollectionFile::getIterator()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
nc 2
nop 0
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
namespace nebula\route\collection;
3
4
use Iterator;
5
use IteratorAggregate;
6
7
/**
8
 * 路由集合文件
9
 */
10
class CollectionFile implements IteratorAggregate
11
{
12
    /**
13
     * 数据源
14
     *
15
     * @var string
16
     */
17
    protected $path;
18
19
    
20
    public static function fromFile(string $path)
21
    {
22
        $collection = new static;
23
        $collection->path = $path;
24
        return $collection;
25
    }
26
27
    /**
28
     * 保存到文件
29
     *
30
     * @param string $path
31
     * @return boolean
32
     */
33
    public function save(string $path):bool
34
    {
35
        foreach ($this as $name => $value) {
36
            if (\file_put_contents($path, $name .'|'. \serialize($value), FILE_APPEND) === false) {
37
                return false;
38
            }
39
        }
40
        return true;
41
    }
42
43
    /**
44
     * 获取迭代器
45
     *
46
     * @return Iterator
47
     */
48
    public function getIterator():Iterator
49
    {
50
        foreach (new ReadLineIterator($this->path) as $line) {
51
            $data = \explode('|', $line);
52
            yield $data[0] => \unserialize($data[1]);
53
        }
54
    }
55
}
56