1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* This file is part of the Console-Kit library. |
4
|
|
|
* For the full copyright and license information, please view |
5
|
|
|
* the LICENSE file that was distributed with this source code. |
6
|
|
|
* |
7
|
|
|
* @copyright Alexander Obuhovich <[email protected]> |
8
|
|
|
* @link https://github.com/console-helpers/console-kit |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace ConsoleHelpers\ConsoleKit; |
12
|
|
|
|
13
|
|
|
|
14
|
|
|
use ConsoleHelpers\ConsoleKit\Exception\ApplicationException; |
15
|
|
|
|
16
|
|
|
class WorkingDirectory |
17
|
|
|
{ |
18
|
|
|
|
19
|
|
|
/** |
20
|
|
|
* Name of sub folder placed in user's home directory. |
21
|
|
|
* |
22
|
|
|
* @var string |
23
|
|
|
*/ |
24
|
|
|
private $_subFolder; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* WorkingDirectory constructor. |
28
|
|
|
* |
29
|
|
|
* @param string $sub_folder Sub folder. |
30
|
|
|
* |
31
|
|
|
* @throws ApplicationException When $sub_folder is a path or empty. |
32
|
|
|
*/ |
33
|
13 |
|
public function __construct($sub_folder) |
34
|
|
|
{ |
35
|
13 |
|
if ( !strlen($sub_folder) || strpos($sub_folder, DIRECTORY_SEPARATOR) !== false ) { |
36
|
2 |
|
throw new ApplicationException('The $sub_folder is a path or empty.'); |
37
|
|
|
} |
38
|
|
|
|
39
|
11 |
|
$this->_subFolder = $sub_folder; |
40
|
11 |
|
} |
41
|
|
|
|
42
|
|
|
/** |
43
|
|
|
* Creates (if missing) working directory and returns full path to it. |
44
|
|
|
* |
45
|
|
|
* @return string |
46
|
|
|
*/ |
47
|
11 |
|
public function get() |
48
|
|
|
{ |
49
|
11 |
|
$working_directory = $this->getUserHomeDirectory() . '/' . $this->_subFolder; |
50
|
|
|
|
51
|
9 |
|
if ( !file_exists($working_directory) ) { |
52
|
2 |
|
mkdir($working_directory, 0777, true); |
53
|
2 |
|
} |
54
|
|
|
|
55
|
9 |
|
return $working_directory; |
56
|
|
|
} |
57
|
|
|
|
58
|
|
|
/** |
59
|
|
|
* Returns path to user's home directory. |
60
|
|
|
* |
61
|
|
|
* @return string |
62
|
|
|
* @throws ApplicationException When user's home directory can't be found. |
63
|
|
|
*/ |
64
|
11 |
|
protected function getUserHomeDirectory() |
65
|
|
|
{ |
66
|
11 |
|
if ( defined('PHP_WINDOWS_VERSION_MAJOR') ) { |
67
|
1 |
|
if ( !getenv('APPDATA') ) { |
68
|
1 |
|
throw new ApplicationException('The APPDATA environment variable must be set to run correctly.'); |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
return strtr(getenv('APPDATA'), '\\', '/'); |
72
|
|
|
} |
73
|
|
|
|
74
|
10 |
|
if ( !getenv('HOME') ) { |
75
|
1 |
|
throw new ApplicationException('The HOME environment variable must be set to run correctly.'); |
76
|
|
|
} |
77
|
|
|
|
78
|
9 |
|
return rtrim(getenv('HOME'), '/'); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
} |
82
|
|
|
|