Completed
Push — master ( f2054b...917ca6 )
by Oscar
03:27 queued 01:41
created

BlockSpam::__invoke()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 19
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 19
rs 9.2
c 0
b 0
f 0
cc 4
eloc 10
nc 5
nop 3
1
<?php
2
3
namespace Psr7Middlewares\Middleware;
4
5
use Psr\Http\Message\ServerRequestInterface;
6
use Psr\Http\Message\ResponseInterface;
7
use RuntimeException;
8
9
/**
10
 * Middleware to block request from blacklist referrer.
11
 */
12
class BlockSpam
13
{
14
    private $spammers;
15
    private $list;
16
17
    public function __construct($spammers = null)
18
    {
19
        if ($spammers === null) {
20
            if ( file_exists( ' __DIR__.'/../../../../vendor/piwik/referrer-spam-blacklist/spammers.txt' ) ) { 
0 ignored issues
show
Bug introduced by
This code did not parse for me. Apparently, there is an error somewhere around this line:

Syntax error, unexpected '.'
Loading history...
21
                $spammers = __DIR__.'/../../../../vendor/piwik/referrer-spam-blacklist/spammers.txt';
22
            } else if ( file_exists( ' __DIR__.'/../../../../piwik/referrer-spam-blacklist/spammers.txt' ) ) { 
23
                 $spammers = __DIR__.'/../../../../piwik/referrer-spam-blacklist/spammers.txt';
24
            } else {
25
                $spammers  =  null;
26
            }
27
        } 
28
29
        $this->spammers = $spammers;
30
    }
31
32
    /**
33
     * Execute the middleware.
34
     *
35
     * @param ServerRequestInterface $request
36
     * @param ResponseInterface      $response
37
     * @param callable               $next
38
     *
39
     * @return ResponseInterface
40
     */
41
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next)
42
    {
43
        if ($this->list === null) {
44
            if (!is_file($this->spammers)) {
45
                throw new RuntimeException(sprintf('The spammers file "%s" doest not exists', $this->spammers));
46
            }
47
48
            $this->list = file($this->spammers, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
49
        }
50
51
        $referer = parse_url($request->getHeaderLine('Referer'), PHP_URL_HOST);
52
        $referer = preg_replace('/^(www\.)/i', '', $referer);
53
54
        if (in_array($referer, $this->list, true)) {
55
            return $response->withStatus(403);
56
        }
57
58
        return $next($request, $response);
59
    }
60
}
61