Completed
Push — master ( df91db...e1615c )
by Simonas
13:43 queued 07:21
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

2 Methods

Rating   Name   Duplication   Size   Complexity  
A ElasticsearchRouteProvider::getRouteByName() 0 4 1
A ElasticsearchRouteProvider::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\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
        try {
89
            foreach ($results as $document) {
90
                $type = $this->collector->getDocumentType(get_class($document));
91
                if (array_key_exists($type, $this->routeMap)) {
92
                    $route = new Route(
93
                        $document->url,
94
                        [
95
                            '_controller' => $this->routeMap[$type],
96
                            'document' => $document,
97
                            'type' => $type,
98
                        ]
99
                    );
100
101
                    $routeCollection->add('ongr_route_' . $route->getDefault('type'), $route);
102
                } else {
103
                    throw new RouteNotFoundException(sprintf('Route for type %s% cannot be generated.', $type));
104
                }
105
            }
106
        } catch (\Exception $e) {
107
            throw new RouteNotFoundException('Document is not correct or route cannot be generated.');
108
        }
109
110
        return $routeCollection;
111
    }
112
113
    /**
114
     * @inheritDoc
115
     */
116
    public function getRouteByName($name)
117
    {
118
        throw new RouteNotFoundException('Dynamic provider generates routes on the fly.');
119
    }
120
121
    /**
122
     * @inheritDoc
123
     */
124
    public function getRoutesByNames($names)
125
    {
126
        // Returns empty Route collection.
127
        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...
128
    }
129
}
130