Completed
Push — master ( cfda18...16b364 )
by Tomas
05:21 queued 11s
created

FakeIpPlugin::handleQuery()   A

Complexity

Conditions 4
Paths 5

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 4.016

Importance

Changes 0
Metric Value
dl 0
loc 19
ccs 9
cts 10
cp 0.9
rs 9.6333
c 0
b 0
f 0
cc 4
nc 5
nop 3
crap 4.016
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the BazingaGeocoderBundle package.
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 *
10
 * @license    MIT License
11
 */
12
13
namespace Bazinga\GeocoderBundle\Plugin;
14
15
use Faker\Generator;
16
use Faker\Provider\Internet;
17
use Geocoder\Plugin\Plugin;
18
use Geocoder\Query\GeocodeQuery;
19
use Geocoder\Query\Query;
20
21
/**
22
 * Replace local IP with something better.
23
 *
24
 * @author Tobias Nyholm <[email protected]>
25
 */
26
class FakeIpPlugin implements Plugin
27
{
28
    /**
29
     * @var string
30
     */
31
    private $needle;
32
33
    /**
34
     * @var string
35
     */
36
    private $replacement;
37
38
    /**
39
     * @var bool
40
     */
41
    private $useFaker;
42
43
    /**
44
     * @var Generator|null
45
     */
46
    private $faker;
47
48 2
    public function __construct(string $needle, string $replacement = null, bool $useFaker = false)
49
    {
50 2
        $this->needle = $needle;
51 2
        $this->replacement = $replacement;
52 2
        $this->useFaker = $useFaker;
53
54 2
        if ($useFaker) {
55 1
            $this->faker = new Generator();
56 1
            $this->faker->addProvider(new Internet($this->faker));
57
        }
58 2
    }
59
60
    /**
61
     * {@inheritdoc}
62
     */
63 2
    public function handleQuery(Query $query, callable $next, callable $first)
64
    {
65 2
        if (!$query instanceof GeocodeQuery) {
66
            return $next($query);
67
        }
68
69 2
        $replacement = $this->replacement;
70
71 2
        if (null !== $this->faker) {
72 1
            $replacement = $this->faker->ipv4;
73
        }
74
75 2
        $text = str_replace($this->needle, $replacement, $query->getText(), $count);
76 2
        if ($count > 0) {
77 2
            $query = $query->withText($text);
78
        }
79
80 2
        return $next($query);
81
    }
82
}
83