Completed
Push — master ( 3428c1...e29901 )
by Simonas
23:11
created

ElasticsearchRouteProvider::getRouteFromDocument()   A

Complexity

Conditions 3
Paths 5

Size

Total Lines 23
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 23
rs 9.0857
cc 3
eloc 14
nc 5
nop 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\Result;
16
use ONGR\ElasticsearchBundle\Service\Manager;
17
use ONGR\ElasticsearchDSL\Query\MatchQuery;
18
use ONGR\ElasticsearchDSL\Search;
19
use Symfony\Cmf\Component\Routing\RouteProviderInterface;
20
use Symfony\Component\HttpFoundation\Request;
21
use Symfony\Component\Routing\Exception\RouteNotFoundException;
22
use Symfony\Component\Routing\Route;
23
use Symfony\Component\Routing\RouteCollection;
24
25
class ElasticsearchRouteProvider implements RouteProviderInterface
26
{
27
    /**
28
     * @var array Route map configuration to map Elasticsearch types and Controllers
29
     */
30
    private $routeMap;
31
32
    /**
33
     * @var Manager
34
     */
35
    private $manager;
36
37
    /**
38
     * @var MetadataCollector
39
     */
40
    private $collector;
41
42
    /**
43
     * ElasticsearchRouteProvider constructor.
44
     *
45
     * @param MetadataCollector $collector
46
     * @param array             $routeMap
47
     */
48
    public function __construct($collector, array $routeMap = [])
49
    {
50
        $this->collector = $collector;
51
        $this->routeMap = $routeMap;
52
    }
53
54
    /**
55
     * Returns Elasticsearch manager instance that was set in app/config.yml.
56
     *
57
     * @return Manager
58
     */
59
    public function getManager()
60
    {
61
        return $this->manager;
62
    }
63
64
    /**
65
     * @param Manager $manager
66
     */
67
    public function setManager(Manager $manager)
68
    {
69
        $this->manager = $manager;
70
    }
71
72
    /**
73
     * @inheritDoc
74
     */
75
    public function getRouteCollectionForRequest(Request $request)
76
    {
77
        if (!$this->manager) {
78
            throw new \Exception('Manager must be set to execute query to the elasticsearch');
79
        }
80
81
        $routeCollection =  new RouteCollection();
82
        $requestPath = $request->getPathInfo();
83
84
        $search = new Search();
85
        $search->addQuery(new MatchQuery('url', $requestPath));
86
87
        $results = $this->manager->execute(array_keys($this->routeMap), $search, Result::RESULTS_OBJECT);
88
89
        foreach ($results as $document) {
90
            if ($route = $this->getRouteFromDocument($document)) {
91
                $routeCollection->add('ongr_route_'.$route->getDefault('type'), $route);
92
            }
93
        }
94
95
        return $routeCollection;
96
    }
97
98
    /**
99
     * @inheritDoc
100
     */
101
    public function getRouteByName($name)
102
    {
103
        $args = func_get_args();
104
        $parameters = $args[1];
105
        return $this->getRouteFromDocument($parameters['document']);
106
    }
107
108
    private function getRouteFromDocument($document)
109
    {
110
        try {
111
            $type = $this->collector->getDocumentType(get_class($document));
112
113
            if (array_key_exists($type, $this->routeMap)) {
114
                $route = new Route(
115
                    $document->url,
116
                    [
117
                        '_controller' => $this->routeMap[$type],
118
                        'document' => $document,
119
                        'type' => $type,
120
                    ]
121
                );
122
123
                return $route;
124
            } else {
125
                throw new RouteNotFoundException(sprintf('Route for type %s% cannot be generated.', $type));
126
            }
127
        } catch (\Exception $e) {
128
            throw new RouteNotFoundException('Document is not correct or route cannot be generated.');
129
        }
130
    }
131
132
    /**
133
     * @inheritDoc
134
     */
135
    public function getRoutesByNames($names)
136
    {
137
        // Returns empty Route collection.
138
        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...
139
    }
140
}
141