Completed
Push — fm-matches ( f867e2...7fc64f )
by Vladimir
14:12
created

SearchController::searchAction()   C

Complexity

Conditions 9
Paths 36

Size

Total Lines 49
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
c 0
b 0
f 0
dl 0
loc 49
rs 5.7446
cc 9
eloc 27
nc 36
nop 2
1
<?php
2
3
use Symfony\Component\HttpFoundation\JsonResponse;
4
use Symfony\Component\HttpFoundation\Request;
5
6
class SearchController extends JSONController
7
{
8
    /**
9
     * The maximum number of objects to allow being excluded
10
     *
11
     * @var int
12
     */
13
    const MAX_EXCLUDED_OBJECTS = 10;
14
15
    /**
16
     * A list of types that can be returned when searching
17
     *
18
     * @var array
19
     */
20
    private static $acceptableTypes = array('player', 'team');
21
22
    public function searchAction(Request $request, Player $me)
0 ignored issues
show
Unused Code introduced by
The parameter $me is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
23
    {
24
        if (!$request->query->has('types')) {
25
            throw new \BadRequestException();
26
        }
27
28
        $types = explode(',', $request->query->get('types'));
29
        $excludeQuery = $request->query->get('exclude');
30
31
        $queries = $results = array();
32
33
        foreach ($types as &$type) {
34
            if (!in_array($type, self::$acceptableTypes)) {
35
                throw new \BadRequestException("An invalid type was provided");
36
            }
37
38
            $type = ucfirst($type);
39
            $queries[$type] = $type::getQueryBuilder();
40
        }
41
42
        $excluded = $this->decompose($excludeQuery, $types, false, self::MAX_EXCLUDED_OBJECTS);
43
44
        foreach ($queries as $type => $query) {
45
            if ($startsWith = $request->query->get('startsWith')) {
46
                $query->where('name')->startsWith($startsWith);
47
            }
48
49
            $query->active()->sortBy('name');
50
51
            foreach ($excluded[$type] as $exclude) {
52
                $query->except($exclude);
53
            }
54
55
            if ($type === 'Player') {
56
                $result = $this->playerQuery($query, $request);
57
            } else {
58
                $result = $query->getArray(array('name'));
59
            }
60
61
            foreach ($result as $model) {
62
                $model['type'] = $type;
63
                $results[] = $model;
64
            }
65
        }
66
67
        return new JsonResponse(array(
68
            'results' => $results
69
        ));
70
    }
71
72
    private function playerQuery(\QueryBuilder $query, Request $request)
73
    {
74
        if ($team = $request->query->get('team')) {
75
            $query->where('team')->is($team);
76
        }
77
78
        return $query->getArray(array('name', 'outdated'));
79
    }
80
}
81