Directory::check()   B
last analyzed

Complexity

Conditions 6
Paths 6

Size

Total Lines 21
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 12
nc 6
nop 2
dl 0
loc 21
rs 8.7624
c 0
b 0
f 0
1
<?php
2
3
namespace Rostenkowski\Resize\Directory;
4
5
6
use Rostenkowski\Resize\Exceptions\DirectoryException;
7
8
/**
9
 * Directory wrapper
10
 */
11
class Directory
12
{
13
14
	/**
15
	 * @var string
16
	 */
17
	private $name;
18
19
20
	/**
21
	 * @param string  $name
22
	 * @param boolean $tryCreateDirectories
23
	 */
24
	public function __construct($name, $tryCreateDirectories = true)
25
	{
26
		$this->name = $this->check($name, $tryCreateDirectories);
27
	}
28
29
30
	/**
31
	 * Checks a directory to be existing and writable.
32
	 * Tries to create it if it does not exist.
33
	 *
34
	 * @param string  $name Directory name
35
	 * @param boolean $tryCreateDirectories
36
	 * @return string Existing and writable directory name
37
	 */
38
	private function check($name, $tryCreateDirectories = true)
39
	{
40
		$exists = true;
41
		$isWritable = true;
42
43
		if (!file_exists($name)) {
44
			$exists = false;
45
			if ($tryCreateDirectories) {
46
				umask(0002);
47
				$exists = @mkdir($name, 0775, true); // @: will be escalated to exception on failure
48
			}
49
		}
50
		if (!is_writable($name)) {
51
			$isWritable = false;
52
		}
53
54
		if (!$exists || !$isWritable) {
55
			throw new DirectoryException($name);
56
		}
57
58
		return $name;
59
	}
60
61
62
	/**
63
	 * @return string
64
	 */
65
	public function __toString()
66
	{
67
		return (string) $this->name;
68
	}
69
70
71
	/**
72
	 * Returns TRUE if the compared directory is the same as this, FALSE otherwise.
73
	 *
74
	 * @param Directory $to
75
	 * @return boolean
76
	 */
77
	public function is(Directory $to)
78
	{
79
		return realpath($this->name) === realpath($to->name);
80
	}
81
82
83
}
84