SizeDriverAggregator::getFileSize()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 19
rs 9.4285
cc 3
eloc 13
nc 3
nop 1
1
<?php
2
3
namespace BigFileTools\Driver;
4
5
use Brick\Math\BigInteger;
6
7
/**
8
 * Aggregates results from more ISizeDrivers. First successful call to driver will return value.
9
 * Exceptions thrown during unsuccessful calls are saved into class state and are available over getter.
10
 *
11
 * @package BigFileTools\Driver
12
 */
13
class SizeDriverAggregator implements ISizeDriver
14
{
15
	/**
16
	 * @var ISizeDriver[]
17
	 */
18
	private $drivers = [];
19
20
	/**
21
	 * @var ISizeDriver
22
	 */
23
	private $lastUsedDriver = null;
24
25
	/**
26
	 * @var Exception[]
27
	 */
28
	private $lastExceptions = [];
29
30
	/**
31
	 * @param ISizeDriver[] $drivers Ordered array of driver instances
32
	 */
33
	public function __construct(array $drivers)
34
	{
35
		foreach($drivers as $driver) {
36
			$this->addDriver($driver);
37
		}
38
	}
39
40
	private function addDriver(ISizeDriver $driver)
41
	{
42
		$this->drivers[] = $driver;
43
	}
44
45
	/**
46
	 * Returns first non-failing driver from last used of getFileSize()
47
	 * @return ISizeDriver
48
	 * @internal Should be used for debugging only
49
	 */
50
	public function getLastUsedDriver()
51
	{
52
		return $this->lastUsedDriver;
53
	}
54
55
	/**
56
	 * Returns file size
57
	 * @param string $path Full path to file
58
	 * @return BigInteger
59
	 * @throws Exception
60
	 */
61
	public function getFileSize($path)
62
	{
63
		$this->lastExceptions = [];
64
		foreach($this->drivers as $driver) {
65
			try{
66
				$result = $driver->getFileSize($path);
67
				$this->lastUsedDriver = $driver;
68
				return $result;
69
			} catch (Exception $exception) {
70
				$this->lastExceptions[] = $exception;
71
			}
72
		}
73
74
		throw new AggregateException(
75
			"Cannot get file size. All methods failed. Call getPreviousExceptions() to get more information.",
76
			null,
77
			$this->lastExceptions
78
		);
79
	}
80
}
81