ResponseManager   A
last analyzed

Complexity

Total Complexity 5

Size/Duplication

Total Lines 68
Duplicated Lines 0 %

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 5
eloc 23
c 3
b 0
f 0
dl 0
loc 68
rs 10

4 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getHttpResponse() 0 6 1
A getResponse() 0 7 2
A getBinaryFileResponse() 0 18 1
1
<?php
2
3
/*
4
 * This file is part of the SF Forward Bundle.
5
 *
6
 * (c) DAOUDI Soufian <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace SfForward\Manager;
13
14
use Psr\Http\Message\ResponseInterface;
15
use SfForward\Util\PublicDirectory;
16
use Symfony\Component\Filesystem\Filesystem;
17
use Symfony\Component\HttpFoundation\BinaryFileResponse;
18
use Symfony\Component\HttpFoundation\Response;
19
20
class ResponseManager
21
{
22
    /**
23
     * @var ResponseInterface
24
     */
25
    protected $response;
26
27
    /**
28
     * @var string
29
     */
30
    protected $projectDir;
31
32
    /**
33
     * ResponseManager constructor.
34
     *
35
     * @param ResponseInterface $response
36
     * @param string            $projectDir
37
     */
38
    public function __construct(ResponseInterface $response, $projectDir)
39
    {
40
        $this->response = $response;
41
        $this->projectDir = $projectDir;
42
    }
43
44
    /**
45
     * @return BinaryFileResponse|Response
46
     */
47
    public function getResponse()
48
    {
49
        if ($this->response->hasHeader('Content-Disposition')) {
50
            return $this->getBinaryFileResponse();
51
        }
52
53
        return $this->getHttpResponse();
54
    }
55
56
    /**
57
     * @return BinaryFileResponse
58
     */
59
    protected function getBinaryFileResponse()
60
    {
61
        $projectDir = PublicDirectory::getPublicDir($this->projectDir);
62
        $filename = $projectDir.mt_rand();
63
64
        $fileSystem = new Filesystem();
65
        $fileSystem->dumpFile(
66
            $filename,
67
            $this->response->getBody()->getContents()
68
        );
69
70
        return (
71
            new BinaryFileResponse(
72
                $filename,
73
                $this->response->getStatusCode(),
74
                $this->response->getHeaders()
75
            )
76
        )->deleteFileAfterSend(true);
77
    }
78
79
    /**
80
     * @return Response
81
     */
82
    protected function getHttpResponse()
83
    {
84
        $response = new Response($this->response->getBody());
85
        $response->setStatusCode($this->response->getStatusCode());
86
87
        return $response;
88
    }
89
}
90