|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace TreeHouse\Feeder\Resource\Transformer; |
|
4
|
|
|
|
|
5
|
|
|
use TreeHouse\Feeder\Resource\FileResource; |
|
6
|
|
|
use TreeHouse\Feeder\Resource\ResourceCollection; |
|
7
|
|
|
use TreeHouse\Feeder\Resource\ResourceInterface; |
|
8
|
|
|
use TreeHouse\Feeder\Transport\FileTransport; |
|
9
|
|
|
|
|
10
|
|
|
/** |
|
11
|
|
|
* Strips all control characters from the resource, except space characters. |
|
12
|
|
|
*/ |
|
13
|
|
|
class RemoveControlCharactersTransformer implements ResourceTransformerInterface |
|
14
|
|
|
{ |
|
15
|
|
|
/** |
|
16
|
|
|
* @var int |
|
17
|
|
|
*/ |
|
18
|
|
|
protected $length; |
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* @param int $length The number of bytes to read/write while processing the resource |
|
22
|
|
|
*/ |
|
23
|
6 |
|
public function __construct($length = 8192) |
|
24
|
|
|
{ |
|
25
|
6 |
|
$this->length = intval($length); |
|
26
|
6 |
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* @inheritdoc |
|
30
|
|
|
*/ |
|
31
|
6 |
|
public function transform(ResourceInterface $resource, ResourceCollection $collection) |
|
32
|
|
|
{ |
|
33
|
6 |
|
$file = $resource->getFile()->getPathname(); |
|
34
|
|
|
|
|
35
|
6 |
|
$tmpFile = tempnam(sys_get_temp_dir(), $file); |
|
36
|
|
|
|
|
37
|
|
|
// remove control characters |
|
38
|
6 |
|
$old = fopen($file, 'r'); |
|
39
|
6 |
|
$new = fopen($tmpFile, 'w'); |
|
40
|
|
|
|
|
41
|
|
|
// list control characters, but leave out \t\r\n |
|
42
|
6 |
|
$chars = array_map('chr', range(0, 31)); |
|
43
|
6 |
|
$chars[] = chr(127); |
|
44
|
6 |
|
unset($chars[9], $chars[10], $chars[13]); |
|
45
|
|
|
|
|
46
|
6 |
|
while (!feof($old)) { |
|
47
|
6 |
|
fwrite($new, str_replace($chars, '', fread($old, $this->length))); |
|
48
|
6 |
|
} |
|
49
|
|
|
|
|
50
|
6 |
|
fclose($old); |
|
51
|
6 |
|
fclose($new); |
|
52
|
|
|
|
|
53
|
|
|
// atomic write |
|
54
|
6 |
|
$this->rename($tmpFile, $file); |
|
55
|
|
|
|
|
56
|
6 |
|
$transport = FileTransport::create($file); |
|
57
|
|
|
|
|
58
|
6 |
|
if ($resource->getTransport()) { |
|
59
|
|
|
$transport->setDestinationDir($resource->getTransport()->getDestinationDir()); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
6 |
|
return new FileResource($transport); |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
|
|
/** |
|
66
|
|
|
* @inheritdoc |
|
67
|
|
|
*/ |
|
68
|
|
|
public function needsTransforming(ResourceInterface $resource) |
|
69
|
|
|
{ |
|
70
|
|
|
return true; |
|
71
|
|
|
} |
|
72
|
|
|
|
|
73
|
|
|
/** |
|
74
|
|
|
* @param string $old |
|
75
|
|
|
* @param string $new |
|
76
|
|
|
* |
|
77
|
|
|
* @throws \RuntimeException |
|
78
|
|
|
*/ |
|
79
|
6 |
|
protected function rename($old, $new) |
|
80
|
|
|
{ |
|
81
|
6 |
|
if (!rename($old, $new)) { |
|
82
|
|
|
throw new \RuntimeException(sprintf('Could not rename %s to %s', $old, $new)); |
|
83
|
|
|
} |
|
84
|
6 |
|
} |
|
85
|
|
|
} |
|
86
|
|
|
|