aboutsummaryrefslogtreecommitdiffstats
path: root/apps/files_external/3rdparty/icewind/streams/src/IteratorDirectory.php
blob: 24a4723d1e33e6dc28c8f8247248e2b8ef1a3594 (plain)
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
101
102
103
104
105
106
107
108
109
110
111
112
<?php
/**
 * SPDX-FileCopyrightText: 2014 Robin Appelman <robin@icewind.nl>
 * SPDX-License-Identifier: MIT
 */

namespace Icewind\Streams;

/**
 * Create a directory handle from an iterator or array
 *
 * The following options should be passed in the context when opening the stream
 * [
 *     'dir' => [
 *        'array'    => string[]
 *        'iterator' => \Iterator
 *     ]
 * ]
 *
 * Either 'array' or 'iterator' need to be set, if both are set, 'iterator' takes preference
 */
class IteratorDirectory extends WrapperHandler implements Directory {
	/**
	 * @var resource
	 */
	public $context;

	/**
	 * @var \Iterator
	 */
	protected $iterator;

	/**
	 * Load the source from the stream context and return the context options
	 *
	 * @param string $name
	 * @return array
	 * @throws \BadMethodCallException
	 */
	protected function loadContext($name = null) {
		$context = parent::loadContext($name);
		if (isset($context['iterator'])) {
			$this->iterator = $context['iterator'];
		} elseif (isset($context['array'])) {
			$this->iterator = new \ArrayIterator($context['array']);
		} else {
			throw new \BadMethodCallException('Invalid context, iterator or array not set');
		}
		return $context;
	}

	/**
	 * @param string $path
	 * @param array $options
	 * @return bool
	 */
	public function dir_opendir($path, $options) {
		$this->loadContext();
		return true;
	}

	/**
	 * @return string|bool
	 */
	public function dir_readdir() {
		if ($this->iterator->valid()) {
			$result = $this->iterator->current();
			$this->iterator->next();
			return $result;
		} else {
			return false;
		}
	}

	/**
	 * @return bool
	 */
	public function dir_closedir() {
		return true;
	}

	/**
	 * @return bool
	 */
	public function dir_rewinddir() {
		$this->iterator->rewind();
		return true;
	}

	/**
	 * Creates a directory handle from the provided array or iterator
	 *
	 * @param \Iterator | array $source
	 * @return resource|false
	 *
	 * @throws \BadMethodCallException
	 */
	public static function wrap($source) {
		if ($source instanceof \Iterator) {
			$options = [
				'iterator' => $source
			];
		} elseif (is_array($source)) {
			$options = [
				'array' => $source
			];
		} else {
			throw new \BadMethodCallException('$source should be an Iterator or array');
		}
		return self::wrapSource(self::NO_SOURCE_DIR, $options);
	}
}