1: <?php
2:
3: namespace WebLoader;
4:
5: /**
6: * FileCollection
7: *
8: * @author Jan Marek
9: */
10: class FileCollection implements IFileCollection
11: {
12:
13: /** @var string */
14: private $root;
15:
16: /** @var array */
17: private $files = array();
18:
19: /** @var array */
20: private $remoteFiles = array();
21:
22: /**
23: * @param string|null $root files root for relative paths
24: */
25: public function __construct($root = NULL)
26: {
27: $this->root = $root;
28: }
29:
30: /**
31: * Get file list
32: * @return array
33: */
34: public function getFiles()
35: {
36: return array_values($this->files);
37: }
38:
39: /**
40: * Make path absolute
41: * @param $path string
42: * @throws \WebLoader\FileNotFoundException
43: * @return string
44: */
45: public function cannonicalizePath($path)
46: {
47:
48: $rel = Path::normalize($this->root . "/" . $path);
49: if (file_exists($rel)) {
50: return $rel;
51: }
52:
53: $abs = Path::normalize($path);
54: if (file_exists($abs)) {
55: return $abs;
56: }
57:
58: throw new FileNotFoundException("File '$path' does not exist.");
59: }
60:
61:
62: /**
63: * Add file
64: * @param $file string filename
65: */
66: public function addFile($file)
67: {
68: $file = $this->cannonicalizePath((string) $file);
69:
70: if (in_array($file, $this->files)) {
71: return;
72: }
73:
74: $this->files[] = $file;
75: }
76:
77:
78: /**
79: * Add files
80: * @param array|\Traversable $files array list of files
81: */
82: public function addFiles($files)
83: {
84: foreach ($files as $file) {
85: $this->addFile($file);
86: }
87: }
88:
89:
90: /**
91: * Remove file
92: * @param $file string filename
93: */
94: public function removeFile($file)
95: {
96: $this->removeFiles(array($file));
97: }
98:
99:
100: /**
101: * Remove files
102: * @param array $files list of files
103: */
104: public function removeFiles(array $files)
105: {
106: $files = array_map(array($this, 'cannonicalizePath'), $files);
107: $this->files = array_diff($this->files, $files);
108: }
109:
110:
111: /**
112: * Add file in remote repository (for example Google CDN).
113: * @param string $file URL address
114: */
115: public function addRemoteFile($file)
116: {
117: if (in_array($file, $this->remoteFiles)) {
118: return;
119: }
120:
121: $this->remoteFiles[] = $file;
122: }
123:
124: /**
125: * Add multiple remote files
126: * @param array|\Traversable $files
127: */
128: public function addRemoteFiles($files)
129: {
130: foreach ($files as $file) {
131: $this->addRemoteFile($file);
132: }
133: }
134:
135: /**
136: * Remove all files
137: */
138: public function clear()
139: {
140: $this->files = array();
141: $this->remoteFiles = array();
142: }
143:
144: /**
145: * @return array
146: */
147: public function getRemoteFiles()
148: {
149: return $this->remoteFiles;
150: }
151:
152: /**
153: * @return string
154: */
155: public function getRoot()
156: {
157: return $this->root;
158: }
159:
160: }
161: