Completed
Push — master ( f146ce...fa6bcb )
by Samuel
02:58 queued 30s
created

FastCGI   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 109
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Test Coverage

Coverage 35.85%

Importance

Changes 4
Bugs 0 Features 0
Metric Value
wmc 12
lcom 1
cbo 4
dl 0
loc 109
ccs 19
cts 53
cp 0.3585
rs 10
c 4
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A doRun() 0 15 2
B __construct() 0 30 6
B request() 0 35 4
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 Adoy\FastCGI\Client;
16
17
class FastCGI extends AbstractAdapter
18
{
19
    /**
20
     * @var Client
21
     */
22
    protected $client;
23
24
    /**
25
     * @var Array of patterns matching php socket files
26
     */
27
    protected $possibleSocketFilePatterns = [
28
        '/var/run/php*.sock',
29
        '/var/run/php/*.sock'
30
    ];
31
32
    /**
33
     * @var string
34
     */
35
    protected $host;
36
37
    /**
38
     * @param string $host 127.0.0.1:9000 or /var/run/php5-fpm.sock
39
     */
40 3
    public function __construct($host = null)
41
    {
42
        // try to guess where it is
43 3
        if ($host === null) {
44 2
            foreach ($this->possibleSocketFilePatterns as $possibleSocketFilePattern) {
45 2
                $possibleSocketFile = current(glob($possibleSocketFilePattern));
46 2
                if (file_exists($possibleSocketFile)) {
47
                    $host = $possibleSocketFile;
48
                    break;
49
                }
50 2
            }
51 2
            if ($host === null) {
52 2
                $host = '127.0.0.1:9000';
53 2
            }
54 2
        }
55
56 3
        $this->host = $host;
57
58 3
        if (false !== strpos($host, ':')) {
59 3
            list($host, $port) = explode(':', $host);
60 3
            $this->client = new Client($host, $port);
61 3
        } else {
62
            // socket
63
            $this->client = new Client('unix://' . $host, -1);
64
        }
65
66 3
        $this->client->setReadWriteTimeout(60 * 1000);
67 3
        $this->client->setPersistentSocket(false);
68 3
        $this->client->setKeepAlive(true);
69 3
    }
70
71
    /**
72
     * {@inheritdoc}
73
     */
74
    protected function doRun(Code $code)
75
    {
76
        $response = $this->request($code);
77
        $parts = explode("\r\n\r\n", $response);
78
79
        // remove headers
80
        array_shift($parts);
81
        $body = implode("\r\n\r\n", $parts);
82
83
        if (@unserialize($body) === false) {
84
            throw new \RuntimeException(sprintf("Error: %s", $response));
85
        }
86
87
        return $body;
88
    }
89
90
    protected function request(Code $code)
91
    {
92
        $file = $this->createTemporaryFile();
93
        $this->logger->info(sprintf('FastCGI: Dumped code to file: %s', $file));
94
95
        try {
96
            $code->writeTo($file);
97
98
            $environment = array(
99
                'REQUEST_METHOD'  => 'POST',
100
                'REQUEST_URI'     => '/',
101
                'SCRIPT_FILENAME' => $file,
102
            );
103
104
            $this->logger->info(sprintf('FastCGI: Requesting FPM using socket: %s', $this->host));
105
            $response = $this->client->request($environment, '');
106
            $this->logger->debug(sprintf('FastCGI: Response: %s', json_encode($response)));
107
108
            if (!@unlink($file)) {
109
                $this->logger->debug(sprintf('FastCGI: Could not delete file: %s', $file));
110
            }
111
112
            return $response;
113
        } catch (\Exception $e) {
114
            if (!@unlink($file)) {
115
                $this->logger->debug(sprintf('FastCGI: Could not delete file: %s', $file));
116
            }
117
118
            throw new \RuntimeException(
119
                sprintf('FastCGI error: %s (%s)', $e->getMessage(), $this->host),
120
                $e->getCode(),
121
                $e
122
            );
123
        }
124
    }
125
}
126