openshift makefile
[mdref/mdref] / mdref / Finder.php
1 <?php
2
3 namespace mdref;
4
5 /**
6 * Find markdown reference files in several REFPATH paths.
7 *
8 * The base URL is used to extract the relative identifier out of the request
9 * url in Finder::find().
10 *
11 * Use the created Path of Finder::find() for Finder::glob() to find subrefs.
12 */
13 class Finder
14 {
15 /**
16 * Base URL
17 * @var \http\Controller\Url
18 */
19 protected $baseUrl;
20
21 /**
22 * Reference paths
23 * @var array
24 */
25 protected $refs = array();
26
27 /**
28 * @param \http\Controller\Url $baseUrl
29 * @param mixed $paths array or string of paths with markdown references
30 */
31 function __construct(\http\Controller\Url $baseUrl, $paths = ".") {
32 if (!is_array($paths)) {
33 $paths = explode(PATH_SEPARATOR, $paths);
34 }
35 $this->refs = $paths;
36 $this->baseUrl = $baseUrl;
37 }
38
39 /**
40 * @return \http\Controller\Url
41 */
42 function getBaseUrl() {
43 return $this->baseUrl;
44 }
45
46 /**
47 * Find a markdown reference file in one REFPATH. If nothing could be found
48 * an empty Path will be returned.
49 *
50 * @param \http\Url $requestUrl
51 * @return Path
52 */
53 function find(\http\Url $requestUrl, $ext = ".md") {
54 $file = implode(DIRECTORY_SEPARATOR, $this->baseUrl->params($requestUrl));
55
56 foreach ($this->refs as $base) {
57 $path = new Path($base, $file);
58 if ($path->isFile($ext)) {
59 return $path;
60 }
61 }
62
63 return new Path;
64 }
65
66 /**
67 * Glob either in a Path's base dir, or, if the path does not have a base
68 * dir set, in each REFPATH paths.
69 *
70 * @param \mdref\Path $path
71 * @param string $pattern glob pattern
72 * @param int $flags glob flags
73 * @return array glob result
74 */
75 function glob(Path $path, $pattern, $flags = GLOB_BRACE) {
76 if (strlen($path->getBaseDir())) {
77 return glob($path->getFullPath($pattern), $flags);
78 }
79 $glob = array();
80 foreach ($this->refs as $ref) {
81 $glob = array_merge($glob, array_map(function ($fn) use ($ref) {
82 return substr($fn, strlen($ref));
83 }, glob($ref . $pattern, $flags)));
84 }
85 return $glob;
86 }
87 }