1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Hhxsv5\LaravelS\Swoole; |
4
|
|
|
|
5
|
|
|
use Symfony\Component\HttpFoundation\BinaryFileResponse; |
6
|
|
|
use Symfony\Component\HttpFoundation\File\File; |
7
|
|
|
|
8
|
|
|
class StaticResponse extends Response |
9
|
|
|
{ |
10
|
|
|
/**@var BinaryFileResponse */ |
11
|
|
|
protected $laravelResponse; |
12
|
|
|
|
13
|
|
|
public function gzip() |
14
|
|
|
{ |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
/** |
18
|
|
|
* @throws \Exception |
19
|
|
|
*/ |
20
|
|
|
public function sendContent() |
21
|
|
|
{ |
22
|
|
|
/**@var File $file */ |
23
|
|
|
$file = $this->laravelResponse->getFile(); |
24
|
|
|
$this->swooleResponse->header('Content-Type', $file->getMimeType()); |
25
|
|
|
if ($this->laravelResponse->getStatusCode() == BinaryFileResponse::HTTP_NOT_MODIFIED) { |
26
|
|
|
$this->swooleResponse->end(); |
27
|
|
|
} else { |
28
|
|
|
$path = $file->getRealPath(); |
29
|
|
|
$size = filesize($path); |
30
|
|
|
if ($size > 0) { |
31
|
|
|
if (version_compare(swoole_version(), '1.7.21', '<')) { |
32
|
|
|
throw new \RuntimeException('sendfile() require Swoole >= 1.7.21'); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
// Support deleteFileAfterSend: https://github.com/symfony/http-foundation/blob/5.0/BinaryFileResponse.php#L305 |
36
|
|
|
$reflection = new \ReflectionObject($this->laravelResponse); |
37
|
|
|
try { |
38
|
|
|
$deleteFileAfterSend = $reflection->getProperty('deleteFileAfterSend'); |
39
|
|
|
$deleteFileAfterSend->setAccessible(true); |
40
|
|
|
$deleteFile = $deleteFileAfterSend->getValue($this->laravelResponse); |
41
|
|
|
} catch (\Exception $e) { |
42
|
|
|
$deleteFile = false; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
if ($deleteFile) { |
46
|
|
|
$fp = fopen($file->getPathname(), 'rb'); |
47
|
|
|
|
48
|
|
|
for ($offset = 0, $limit = floor(1.99 * 1024 * 1024); $offset < $size; $offset += $limit) { |
49
|
|
|
fseek($fp, $offset, SEEK_SET); |
|
|
|
|
50
|
|
|
$chunk = fread($fp, $limit); |
|
|
|
|
51
|
|
|
$this->swooleResponse->write($chunk); |
52
|
|
|
} |
53
|
|
|
$this->swooleResponse->end(); |
54
|
|
|
|
55
|
|
|
fclose($fp); |
|
|
|
|
56
|
|
|
|
57
|
|
|
if (file_exists($file->getPathname())) { |
58
|
|
|
unlink($file->getPathname()); |
59
|
|
|
} |
60
|
|
|
} else { |
61
|
|
|
$this->swooleResponse->sendfile($path); |
62
|
|
|
} |
63
|
|
|
} else { |
64
|
|
|
$this->swooleResponse->end(); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
} |