forked from ibolmo/packager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPackage.php
More file actions
100 lines (79 loc) · 2.49 KB
/
Package.php
File metadata and controls
100 lines (79 loc) · 2.49 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?php
require_once __DIR__ . '/helpers/yaml.php';
require_once __DIR__ . '/Source.php';
class Package
{
protected $sources = array();
public function __construct($package_path = '')
{
if ($package_path){
$this->path = $this->resolve_path($package_path);
$this->root_dir = dirname($this->path);
$this->parse($this->path);
}
}
public function __toString()
{
return $this->get_name();
}
static function decode($path){
return preg_match('/\.json$/', $path) ? json_decode(file_get_contents($path), true) : YAML::decode_file($path);
}
static function glob($path, $pattern = '*', $flags = 0, $depth = 0){
$matches = array();
$folders = array(rtrim($path, DIRECTORY_SEPARATOR));
while ($folder = array_shift($folders)){
$matches = array_merge($matches, glob($folder.DIRECTORY_SEPARATOR.$pattern, $flags));
if (!$depth) continue;
$moreFolders = glob($folder.DIRECTORY_SEPARATOR.'*', GLOB_ONLYDIR);
$depth = ($depth < -1) ? -1: $depth + count($moreFolders) - 2;
$folders = array_merge($folders, $moreFolders);
}
return $matches;
}
public function add_source($source_path = '')
{
if (!is_a($source_path, 'Source')) $source_path = new Source($this->get_name(), $source_path);
$this->sources[] = $source_path;
}
public function get_name()
{
return $this->name;
}
public function get_sources()
{
return $this->sources;
}
public function parse($package_path)
{
$package = self::decode($package_path);
foreach ($package as $key => $value){
$method = 'parse_' . strtolower($key);
if (is_callable(array($this, $method))) $this->$method($value);
}
}
public function parse_name($name)
{
$this->set_name($name);
}
public function parse_sources($sources)
{
# todo(ibolmo): 5, should be a class option.
if (is_string($sources)) $sources = self::glob($this->path, $sources, 0, 5);
foreach ($sources as $source) $this->add_source($this->root_dir . '/' . $source);
}
public function set_name($name)
{
$this->name = $name;
return $this;
}
public function resolve_path($path){
if (!is_dir($path) && file_exists($path)) return $path;
$pathinfo = pathinfo($path);
$path = $pathinfo['dirname'] . '/' . $pathinfo['basename'] . '/';
if (file_exists($path . 'package.yml')) return $path . 'package.yml';
if (file_exists($path . 'package.yaml')) return $path . 'package.yaml';
if (file_exists($path . 'package.json')) return $path . 'package.json';
throw new Exception("package.(ya?ml|json) not found in $path.");
}
}