spatie /
laravel-varnish
| 1 | <?php |
||
| 2 | |||
| 3 | namespace Spatie\Varnish; |
||
| 4 | |||
| 5 | use Symfony\Component\Process\Exception\ProcessFailedException; |
||
| 6 | use Symfony\Component\Process\Process; |
||
| 7 | |||
| 8 | class Varnish |
||
| 9 | { |
||
| 10 | /** |
||
| 11 | * @param string|array $host |
||
| 12 | * @param string $url |
||
| 13 | * |
||
| 14 | * @return \Symfony\Component\Process\Process |
||
| 15 | */ |
||
| 16 | public function flush($host = null, string $url = null): Process |
||
| 17 | { |
||
| 18 | $host = $this->getHosts($host); |
||
| 19 | |||
| 20 | $command = $this->generateBanCommand($host, $url); |
||
| 21 | |||
| 22 | return $this->executeCommand($command); |
||
| 23 | } |
||
| 24 | |||
| 25 | /** |
||
| 26 | * @param array|string $host |
||
| 27 | * |
||
| 28 | * @return array |
||
| 29 | */ |
||
| 30 | protected function getHosts($host = null): array |
||
| 31 | { |
||
| 32 | $host = $host ?? config('varnish.host'); |
||
| 33 | |||
| 34 | if (! is_array($host)) { |
||
| 35 | $host = [$host]; |
||
| 36 | } |
||
| 37 | |||
| 38 | return $host; |
||
| 39 | } |
||
| 40 | |||
| 41 | /** |
||
| 42 | * @param array $hosts |
||
| 43 | * @param string $url |
||
| 44 | * @return string |
||
| 45 | */ |
||
| 46 | public function generateBanCommand(array $hosts, string $url = null): string |
||
| 47 | { |
||
| 48 | $hostsRegex = collect($hosts) |
||
| 49 | ->map(function (string $host) { |
||
| 50 | return "(^{$host}$)"; |
||
| 51 | }) |
||
| 52 | ->implode('|'); |
||
| 53 | |||
| 54 | $config = config('varnish'); |
||
| 55 | |||
| 56 | $urlRegex = ''; |
||
| 57 | if (! empty($url)) { |
||
| 58 | $urlRegex = " && req.url ~ {$url}"; |
||
| 59 | } |
||
| 60 | |||
| 61 | return "sudo varnishadm -S {$config['administrative_secret']} -T 127.0.0.1:{$config['administrative_port']} 'ban req.http.host ~ {$hostsRegex}{$urlRegex}'"; |
||
| 62 | } |
||
| 63 | |||
| 64 | protected function executeCommand(string $command): Process |
||
| 65 | { |
||
| 66 | $process = new Process($command); |
||
|
0 ignored issues
–
show
Bug
introduced
by
Loading history...
|
|||
| 67 | |||
| 68 | $process->run(); |
||
| 69 | |||
| 70 | if (! $process->isSuccessful()) { |
||
| 71 | throw new ProcessFailedException($process); |
||
| 72 | } |
||
| 73 | |||
| 74 | return $process; |
||
| 75 | } |
||
| 76 | } |
||
| 77 |