Passed
Push — master ( c547da...5d2787 )
by 世昌
02:10 queued 15s
created

Builder::scan()   B

Complexity

Conditions 7
Paths 7

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 8
nc 7
nop 2
dl 0
loc 11
rs 8.8333
c 0
b 0
f 0
1
<?php
2
namespace suda\application\module;
3
4
use Iterator;
5
use ZipArchive;
6
use suda\application\config\Config;
7
use suda\application\module\Module;
8
use suda\application\filesystem\FileSystem;
9
10
/**
11
 * 模块构建工具
12
 */
13
class Builder
14
{
15
    /**
16
     * 从配置文件构建模块
17
     *
18
     * @param string $path
19
     * @return Module
20
     */
21
    public static function build(string $path):Module
22
    {
23
        $config = new Config;
24
        $config->load($path);
25
        if (!$config->has('name')) {
26
            $config->set('name', basename(dirname($path)));
27
        }
28
        $module = new Module(dirname($path), $config);
29
        return $module;
30
    }
31
    
32
    public static function check(string $path): ?string
33
    {
34
        return Config::resolve($path.'/module');
35
    }
36
37
    public static function checkPack(string $path, string $unpackPath): ?string
38
    {
39
        $extension = pathinfo($path, PATHINFO_EXTENSION);
40
        if (
41
            $extension !== 'mod' &&
42
            $extension !== 'module') {
43
            return null;
44
        }
45
        $zip=new ZipArchive;
46
        if ($zip->open($path, ZipArchive::CHECKCONS)) {
47
            $unzipPath = $unpackPath.'/'. pathinfo($path, PATHINFO_FILENAME) .'-'.substr(md5_file($path), 0, 8);
48
            $zip->extractTo($unzipPath);
49
            $zip->close();
50
            return Config::resolve($unzipPath.'/module');
51
        }
52
        return null;
53
    }
54
55
    /**
56
     * 扫描模块
57
     *
58
     * @param array $scanPaths
59
     * @param string $extractPath
60
     * @return Iterator
61
     */
62
    public static function scan(array $scanPaths, string $extractPath): Iterator
63
    {
64
        foreach ($scanPaths as $modulesPath) {
65
            foreach (FileSystem::read($modulesPath) as $path) {
66
                if (is_file($path)) {
67
                    if ($configPath = static::checkPack($path, $extractPath)) {
68
                        yield static::build($configPath);
69
                    }
70
                } elseif (is_dir($path)) {
71
                    if ($configPath = static::check($path)) {
72
                        yield static::build($configPath);
73
                    }
74
                }
75
            }
76
        }
77
    }
78
}
79