1<?php
2
3/**
4 * Collects all files for a specified path hierachical,
5 * recursive or non recursive.
6 */
7class SplFileArray
8{
9	/**
10	 * Storage
11	 * @var array
12	 */
13	private $filesystemarray = array();
14
15	/**
16	 * Order of files
17	 * @var string
18	 */
19	private $fileorder = 'asc';
20
21	/**
22	 * Constructor
23	 * @param string  $path      Path to collect
24	 * @param boolean $recursive Collect information recursivly or not
25	 * @param string  $order 	 Defines the sort order of files
26	 */
27	public function __construct($path, $recursive = true, $fileorder)
28	{
29		$this->fileorder = $fileorder;
30		$this->filesystemarray = $this->readdir($path, $recursive);
31	}
32
33	/**
34	 * Returns the result
35	 * @return array
36	 */
37	public function get()
38	{
39		return $this->filesystemarray;
40	}
41
42	/**
43	 * Reads all files for a given path
44	 * @param  string 	$path
45	 * @param  bool 	$recursive
46	 * @return array
47	 */
48	private function readDir($path, $recursive)
49	{
50		$filesystem = new FileSystemIterator($path, FileSystemIterator::KEY_AS_FILENAME);
51
52		$array = array();
53
54		foreach ($filesystem as $key => $value) {
55
56			if ( $value->isDir() && $recursive ) {
57				$array[$key] = $this->readDir($value->getRealPath(), $recursive);
58			}
59			else if ( ! $value->isDir() ) {
60				$array[$key] = $value;
61			}
62
63		}
64
65		uasort($array, array($this, 'sortDir'));
66
67		return $array;
68	}
69
70	/**
71	 * Custom sort method
72	 * This sort down arrays (directories) and sorts up everything else
73	 * @param  mixed $a
74	 * @param  mixed $b
75	 * @return int
76	 */
77	private function sortDir($a, $b)
78	{
79		if ( is_array($a) )
80			return +1;
81
82		if ( is_array($b) )
83			return -1;
84
85		if ( $a->getFilename() == $b->getFilename() )
86			return 0;
87
88		if ( $this->fileorder === 'desc' )
89			return ($a->getFilename() < $b->getFilename()) ? +1 : -1;
90		else
91			return ($a->getFilename() > $b->getFilename()) ? +1 : -1;
92	}
93}
94