ElasticsearchRouteProvider   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 117
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 10

Importance

Changes 0
Metric Value
wmc 11
c 0
b 0
f 0
lcom 1
cbo 10
dl 0
loc 117
rs 10

7 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getManager() 0 4 1
A setManager() 0 4 1
A getRouteMap() 0 4 1
B getRouteCollectionForRequest() 0 42 5
A getRouteByName() 0 4 1
A getRoutesByNames() 0 5 1
1
<?php
2
3
/*
4
 * This file is part of the ONGR package.
5
 *
6
 * (c) NFQ Technologies UAB <[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 ONGR\RouterBundle\Routing;
13
14
use ONGR\ElasticsearchBundle\Mapping\MetadataCollector;
15
use ONGR\ElasticsearchBundle\Result\DocumentIterator;
16
use ONGR\ElasticsearchBundle\Result\ObjectIterator;
17
use ONGR\ElasticsearchBundle\Service\Manager;
18
use ONGR\ElasticsearchDSL\Query\Compound\BoolQuery;
19
use ONGR\ElasticsearchDSL\Query\FullText\MatchQuery;
20
use ONGR\ElasticsearchDSL\Search;
21
use ONGR\RouterBundle\Document\SeoAwareInterface;
22
use Symfony\Cmf\Component\Routing\RouteProviderInterface;
23
use Symfony\Component\HttpFoundation\Request;
24
use Symfony\Component\Routing\Exception\RouteNotFoundException;
25
use Symfony\Component\DependencyInjection\Exception\ParameterNotFoundException;
26
use Symfony\Component\Routing\Route;
27
use Symfony\Component\Routing\RouteCollection;
28
29
class ElasticsearchRouteProvider implements RouteProviderInterface
30
{
31
    /**
32
     * @var array Route map configuration to map Elasticsearch types and Controllers.
33
     */
34
    private $routeMap;
35
36
    /**
37
     * @var Manager
38
     */
39
    private $manager;
40
41
    /**
42
     * @var MetadataCollector
43
     */
44
    private $collector;
45
46
    /**
47
     * ElasticsearchRouteProvider constructor.
48
     *
49
     * @param MetadataCollector $collector
50
     * @param array $routeMap
51
     */
52
    public function __construct($collector, array $routeMap = [])
53
    {
54
        $this->collector = $collector;
55
        $this->routeMap = $routeMap;
56
    }
57
58
    /**
59
     * Returns Elasticsearch manager instance that was set in app/config.yml.
60
     *
61
     * @return Manager
62
     */
63
    public function getManager()
64
    {
65
        return $this->manager;
66
    }
67
68
    /**
69
     * @param Manager $manager
70
     */
71
    public function setManager(Manager $manager)
72
    {
73
        $this->manager = $manager;
74
    }
75
    /**
76
     * @return array
77
     */
78
    public function getRouteMap()
79
    {
80
        return $this->routeMap;
81
    }
82
83
    /**
84
     * {@inheritdoc}
85
     */
86
    public function getRouteCollectionForRequest(Request $request)
87
    {
88
        if (!$this->manager) {
89
            throw new ParameterNotFoundException(
90
                'Manager must be set to execute query to the elasticsearch'
91
            );
92
        }
93
94
        $routeCollection = new RouteCollection();
95
        $requestPath = $request->getPathInfo();
96
97
        $search = new Search();
98
        $search->addQuery(new MatchQuery('url', $requestPath), BoolQuery::FILTER);
99
100
        $results = $this->manager->search(array_keys($this->routeMap), $search->toArray());
101
        #TODO Clean up this place.
102
        $results = new DocumentIterator($results, $this->manager);
0 ignored issues
show
Documentation introduced by
$results is of type callable, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
103
        try {
104
            /** @var SeoAwareInterface $document */
105
            foreach ($results as $document) {
106
                $type = $this->collector->getDocumentType(get_class($document));
107
                if (isset($this->routeMap[$type])) {
108
                    $route = new Route(
109
                        $document->getUrl(),
110
                        [
111
                            '_controller' => $this->routeMap[$type],
112
                            'document' => $document,
113
                            'type' => $type,
114
                        ]
115
                    );
116
117
                    $routeCollection->add('ongr_route_' . $route->getDefault('type'), $route);
118
                } else {
119
                    throw new RouteNotFoundException(sprintf('Route for type %s% cannot be generated.', $type));
120
                }
121
            }
122
        } catch (\Exception $e) {
123
            throw new RouteNotFoundException('Document is not correct or route cannot be generated.');
124
        }
125
126
        return $routeCollection;
127
    }
128
129
    /**
130
     * {@inheritdoc}
131
     */
132
    public function getRouteByName($name)
133
    {
134
        throw new RouteNotFoundException('Dynamic provider generates routes on the fly.');
135
    }
136
137
    /**
138
     * {@inheritdoc}
139
     */
140
    public function getRoutesByNames($names)
141
    {
142
        // Returns empty Route collection.
143
        return new RouteCollection();
0 ignored issues
show
Bug Best Practice introduced by
The return type of return new \Symfony\Comp...ting\RouteCollection(); (Symfony\Component\Routing\RouteCollection) is incompatible with the return type declared by the interface Symfony\Cmf\Component\Ro...rface::getRoutesByNames of type Symfony\Component\Routing\Route[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
144
    }
145
}
146