1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Spatie\Export\Jobs; |
4
|
|
|
|
5
|
|
|
use RecursiveDirectoryIterator; |
6
|
|
|
use RecursiveIteratorIterator; |
7
|
|
|
use RuntimeException; |
8
|
|
|
use Spatie\Export\Destination; |
9
|
|
|
|
10
|
|
|
class IncludeFile |
11
|
|
|
{ |
12
|
|
|
/** @var string */ |
13
|
|
|
protected $source; |
14
|
|
|
|
15
|
|
|
/** @var string */ |
16
|
|
|
protected $target; |
17
|
|
|
|
18
|
|
|
/** @var string[] */ |
19
|
|
|
protected $excludeFilePatterns; |
20
|
|
|
|
21
|
|
|
public function __construct(string $source, string $target, array $excludeFilePatterns) |
22
|
|
|
{ |
23
|
|
|
$this->source = $source; |
24
|
|
|
$this->target = $target; |
25
|
|
|
$this->excludeFilePatterns = $excludeFilePatterns; |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
public function handle(Destination $destination) |
29
|
|
|
{ |
30
|
|
|
if (is_file($this->source)) { |
31
|
|
|
$this->exportIncludedFile($this->source, $this->target, $destination); |
32
|
|
|
} elseif (is_dir($this->source)) { |
33
|
|
|
$this->exportIncludedDirectory($this->source, $this->target, $destination); |
34
|
|
|
} else { |
35
|
|
|
throw new RuntimeException("File or directory [{$this->source}] not found"); |
36
|
|
|
} |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
protected function exportIncludedFile(string $source, string $target, Destination $destination) |
40
|
|
|
{ |
41
|
|
|
if ($this->shouldExclude($source)) { |
42
|
|
|
return; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
$target = '/'.ltrim($target, '/'); |
46
|
|
|
|
47
|
|
|
$destination->write($target, file_get_contents($source)); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
protected function exportIncludedDirectory(string $source, string $target, Destination $destination) |
51
|
|
|
{ |
52
|
|
|
$iterator = new RecursiveIteratorIterator( |
53
|
|
|
new RecursiveDirectoryIterator($source, RecursiveDirectoryIterator::SKIP_DOTS), |
54
|
|
|
RecursiveIteratorIterator::SELF_FIRST |
55
|
|
|
); |
56
|
|
|
|
57
|
|
|
foreach ($iterator as $item) { |
58
|
|
|
if ($item->isDir()) { |
59
|
|
|
continue; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
$this->exportIncludedFile( |
63
|
|
|
$item->getPathname(), |
64
|
|
|
$target.'/'.$iterator->getSubPathName(), |
65
|
|
|
$destination |
66
|
|
|
); |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
protected function shouldExclude(string $source): bool |
71
|
|
|
{ |
72
|
|
|
foreach ($this->excludeFilePatterns as $pattern) { |
73
|
|
|
if (preg_match($pattern, $source)) { |
74
|
|
|
return true; |
75
|
|
|
} |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
return false; |
79
|
|
|
} |
80
|
|
|
} |
81
|
|
|
|