1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\Php7to5; |
4
|
|
|
|
5
|
|
|
use FilesystemIterator; |
6
|
|
|
use Spatie\Php7to5\Exceptions\InvalidParameter; |
7
|
|
|
|
8
|
|
|
class DirectoryConverter |
9
|
|
|
{ |
10
|
|
|
/** @var string */ |
11
|
|
|
protected $copyNonPhpFiles = true; |
12
|
|
|
|
13
|
|
|
public function __construct(string $sourceDirectory) |
14
|
|
|
{ |
15
|
|
|
if (!file_exists($sourceDirectory)) { |
16
|
|
|
throw InvalidParameter::directoryDoesNotExist($sourceDirectory); |
17
|
|
|
} |
18
|
|
|
|
19
|
|
|
$this->sourceDirectory = $sourceDirectory; |
|
|
|
|
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
public function alsoCopyNonPhpFiles() : self |
23
|
|
|
{ |
24
|
|
|
$this->copyNonPhpFiles = true; |
|
|
|
|
25
|
|
|
|
26
|
|
|
return $this; |
27
|
|
|
} |
28
|
|
|
|
29
|
|
|
public function doNotCopyNonPhpFiles() : self |
30
|
|
|
{ |
31
|
|
|
$this->copyNonPhpFiles = false; |
|
|
|
|
32
|
|
|
|
33
|
|
|
return $this; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
public function savePhp5FilesTo(string $destinationDirectory) |
37
|
|
|
{ |
38
|
|
|
if ($destinationDirectory === '') { |
39
|
|
|
throw InvalidParameter::directoryIsRequired(); |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
$this->copyDirectory($this->sourceDirectory, $destinationDirectory); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
protected function copyDirectory(string $sourceDirectory, string $destinationDirectory) |
46
|
|
|
{ |
47
|
|
|
if (!is_dir($destinationDirectory)) { |
48
|
|
|
mkdir($destinationDirectory); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
$items = new FilesystemIterator($sourceDirectory, FilesystemIterator::SKIP_DOTS); |
52
|
|
|
|
53
|
|
|
foreach ($items as $item) { |
54
|
|
|
$target = $destinationDirectory.'/'.$item->getBasename(); |
55
|
|
|
|
56
|
|
|
if ($item->isDir()) { |
57
|
|
|
$sourceDirectory = $item->getPathname(); |
58
|
|
|
|
59
|
|
|
$this->copyDirectory($sourceDirectory, $target); |
60
|
|
|
} else { |
61
|
|
|
if ($this->isPhpFile($target) || $this->copyNonPhpFiles) { |
62
|
|
|
copy($item->getPathname(), $target); |
63
|
|
|
|
64
|
|
|
if (strtolower(pathinfo($target, PATHINFO_EXTENSION)) === 'php') { |
65
|
|
|
$this->convertToPhp5($target); |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
protected function convertToPhp5(string $filePath) |
73
|
|
|
{ |
74
|
|
|
$converter = new Converter($filePath); |
75
|
|
|
|
76
|
|
|
$converter->saveAsPhp5($filePath); |
77
|
|
|
} |
78
|
|
|
|
79
|
|
|
protected function isPhpFile(string $filePath) : bool |
80
|
|
|
{ |
81
|
|
|
return strtolower(pathinfo($filePath, PATHINFO_EXTENSION)) === 'php'; |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: