Completed
Push — hollodotme-fcgi ( 3f0c42...67063c )
by Samuel
04:07 queued 02:54
created

FastCGI::request()   A

Complexity

Conditions 4
Paths 20

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5.1173

Importance

Changes 0
Metric Value
dl 0
loc 30
ccs 10
cts 17
cp 0.5881
rs 9.44
c 0
b 0
f 0
cc 4
nc 20
nop 1
crap 5.1173
1
<?php
2
3
/*
4
 * This file is part of CacheTool.
5
 *
6
 * (c) Samuel Gordalina <[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 CacheTool\Adapter;
13
14
use CacheTool\Code;
15
use hollodotme\FastCGI\Client;
16
use hollodotme\FastCGI\SocketConnections\NetworkSocket;
17
use hollodotme\FastCGI\SocketConnections\UnixDomainSocket;
18
use hollodotme\FastCGI\Requests\PostRequest;
19
20
class FastCGI extends AbstractAdapter
21
{
22
    /**
23
     * @var Client
24
     */
25
    protected $client;
26
27
    /**
28
     * @var Connection
29
     */
30
    protected $connection;
31
32
    /**
33
     * @var Array of patterns matching php socket files
34
     */
35
    protected $possibleSocketFilePatterns = [
36
        '/var/run/php*.sock',
37
        '/var/run/php/*.sock'
38
    ];
39
40
    /**
41
     * @var string
42
     */
43
    protected $host;
44
45
    /**
46
     * @var string
47
     */
48
    protected $chroot;
49
50
    /**
51
     * @param string $host 127.0.0.1:9000 or /var/run/php5-fpm.sock
52
     * @param string $chroot
53
     */
54 8
    public function __construct($host = null, $chroot = null)
55
    {
56
        // try to guess where it is
57 8
        if ($host === null) {
58 7
            foreach ($this->possibleSocketFilePatterns as $possibleSocketFilePattern) {
59 7
                $possibleSocketFile = current(glob($possibleSocketFilePattern));
60 7
                if (file_exists($possibleSocketFile)) {
61 7
                    $host = $possibleSocketFile;
62 7
                    break;
63
                }
64
            }
65 7
            if ($host === null) {
66
                $host = '127.0.0.1:9000';
67
            }
68
        }
69
70 8
        $this->host = $host;
71
72 8
        if (false !== strpos($host, ':')) {
73 1
            [$host, $port] = explode(':', $host);
0 ignored issues
show
Bug introduced by
The variable $port does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
74 1
            $this->connection = new NetworkSocket(
0 ignored issues
show
Documentation Bug introduced by
It seems like new \hollodotme\FastCGI\...t, $port, 5000, 120000) of type object<hollodotme\FastCG...nections\NetworkSocket> is incompatible with the declared type object<CacheTool\Adapter\Connection> of property $connection.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
75 1
            	  $host,    # Hostname
76
            	  $port,    # Port
77 1
            	  5000,     # Connect timeout in milliseconds (default: 5000)
78 1
            	  120000    # Read/write timeout in milliseconds (default: 5000)
79
            );
80
        } else {
81 7
            $this->connection = new UnixDomainSocket(
0 ignored issues
show
Documentation Bug introduced by
It seems like new \hollodotme\FastCGI\...et($host, 5000, 120000) of type object<hollodotme\FastCG...tions\UnixDomainSocket> is incompatible with the declared type object<CacheTool\Adapter\Connection> of property $connection.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
82 7
                $host,  # Socket path to php-fpm
83 7
                5000,   # Connect timeout in milliseconds (default: 5000)
84 7
                120000  # Read/write timeout in milliseconds (default: 5000)
85
            );
86
        }
87
88 8
        $this->client = new Client();
89
90 8
        if ($chroot !== null) {
91 2
            $this->chroot = rtrim($chroot, '/');
92
        }
93 8
    }
94
95
    /**
96
     * {@inheritdoc}
97
     */
98 2
    protected function doRun(Code $code)
99
    {
100 2
        $body = $this->request($code);
101
102
        if (@unserialize($body) === false) {
103
            throw new \RuntimeException(sprintf("Error: %s", $body));
104
        }
105
106
        return $body;
107
    }
108
109 2
    protected function request(Code $code)
110
    {
111 2
        $file = $this->createTemporaryFile();
112 2
        $this->logger->info(sprintf('FastCGI: Dumped code to file: %s', $file));
113
114
        try {
115 2
            $code->writeTo($file);
116
117
            $this->logger->info(sprintf('FastCGI: Requesting FPM using socket: %s', $this->host));
118
            $request = new PostRequest($this->getScriptFileName($file), '');
119
            $response = $this->client->sendRequest($this->connection, $request);
120
            $this->logger->debug(sprintf('FastCGI: Response: %s', json_encode($response)));
121
122
            if (!@unlink($file)) {
123
                $this->logger->debug(sprintf('FastCGI: Could not delete file: %s', $file));
124
            }
125
126
            return $response->getBody();
127 2
        } catch (\Exception $e) {
128 2
            if (!@unlink($file)) {
129 2
                $this->logger->debug(sprintf('FastCGI: Could not delete file: %s', $file));
130
            }
131
132 2
            throw new \RuntimeException(
133 2
                sprintf('FastCGI error: %s (%s)', $e->getMessage(), $this->host),
134 2
                $e->getCode(),
135
                $e
136
            );
137
        }
138
    }
139
140
    /**
141
     * @param string $file
142
     * @return string
143
     * @throws \RuntimeException
144
     */
145 2
    protected function getScriptFileName($file)
146
    {
147 2
        if ($this->chroot) {
148 1
            if (substr($file, 0, strlen($this->chroot)) === $this->chroot) {
149 1
                return substr($file, strlen($this->chroot));
150
            }
151
            throw new \RuntimeException('FastCGI configured to be chrooted, but file not in chroot directory.');
152
        }
153 1
        return $file;
154
    }
155
}
156