1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Automation tool mixed with code generator for easier continuous development. |
4
|
|
|
* |
5
|
|
|
* @link https://github.com/hiqdev/hidev |
6
|
|
|
* @package hidev |
7
|
|
|
* @license BSD-3-Clause |
8
|
|
|
* @copyright Copyright (c) 2015-2017, HiQDev (http://hiqdev.com/) |
9
|
|
|
*/ |
10
|
|
|
|
11
|
|
|
namespace hidev\helpers; |
12
|
|
|
|
13
|
|
|
use Yii; |
14
|
|
|
|
15
|
|
|
/** |
16
|
|
|
* Hidev FileHelper. |
17
|
|
|
*/ |
18
|
|
|
class FileHelper |
19
|
|
|
{ |
20
|
|
|
/** |
21
|
|
|
* Writes given content to the file. |
22
|
|
|
* Doesn't touch file if it has exactly same content. |
23
|
|
|
* Creates intermediate directories when necessary. |
24
|
|
|
* @param string $path |
25
|
|
|
* @param string $content |
26
|
|
|
* @return bool true if file was changed |
27
|
|
|
*/ |
28
|
5 |
|
public static function write($path, $content) |
29
|
|
|
{ |
30
|
5 |
|
$path = Yii::getAlias($path); |
31
|
5 |
|
if (is_file($path) && file_get_contents($path) === $content) { |
32
|
|
|
return false; |
33
|
|
|
} |
34
|
|
|
|
35
|
5 |
|
static::mkdir(dirname($path)); |
36
|
|
|
try { |
37
|
5 |
|
file_put_contents($path, $content); |
38
|
|
|
} catch (\Exception $e) { |
39
|
|
|
if (posix_isatty(0)) { |
40
|
|
|
$tmp = tempnam('/tmp', 'hidev.'); |
41
|
|
|
file_put_contents($tmp, $content); |
42
|
|
|
chmod($tmp, 0644); |
43
|
|
|
passthru("sudo cp $tmp $path"); |
44
|
|
|
unlink($tmp); |
45
|
|
|
} |
46
|
|
|
} |
47
|
5 |
|
Yii::warning('Written file: ' . $path, 'file'); |
48
|
|
|
|
49
|
5 |
|
return true; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
/** |
53
|
|
|
* Creates directory if not exists. |
54
|
|
|
* Creates intermediate directories when necessary. |
55
|
|
|
* @param string $path |
56
|
|
|
* @return bool true if directory did not exist and was created |
57
|
|
|
*/ |
58
|
5 |
|
public static function mkdir($path) |
59
|
|
|
{ |
60
|
5 |
|
$path = Yii::getAlias($path); |
61
|
5 |
|
$path = rtrim(trim($path), '/'); |
62
|
5 |
|
if (!file_exists($path)) { |
63
|
|
|
mkdir($path, 0777, true); |
64
|
|
|
Yii::warning('Created dir: ' . $path . '/', 'file'); |
65
|
|
|
|
66
|
|
|
return true; |
67
|
|
|
} |
68
|
|
|
|
69
|
5 |
|
return false; |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
/** |
73
|
|
|
* Creates a symlink. |
74
|
|
|
* @param string $src existing source path |
75
|
|
|
* @param string $dst destionation path to be created |
76
|
|
|
* @return true on success and false/null on failure |
77
|
|
|
*/ |
78
|
|
|
public static function symlink($src, $dst) |
79
|
|
|
{ |
80
|
|
|
try { |
81
|
|
|
return symlink($src, $dst); |
82
|
|
|
} catch (\Exception $e) { |
83
|
|
|
if (posix_isatty(0)) { |
84
|
|
|
passthru("sudo ln -s $src $dst", $retval); |
85
|
|
|
return $retval === 0; |
86
|
|
|
} |
87
|
|
|
} |
88
|
|
|
} |
89
|
|
|
} |
90
|
|
|
|