GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Push — master ( c5b945...ad9544 )
by Florian
02:32
created

SearchController::getSearchTerm()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 3
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
/*
4
 * This file is part of the Stinger Entity Search package.
5
 *
6
 * (c) Oliver Kotte <[email protected]>
7
 * (c) Florian Meyer <[email protected]>
8
 *
9
 * For the full copyright and license information, please view the LICENSE
10
 * file that was distributed with this source code.
11
 */
12
namespace StingerSoft\EntitySearchBundle\Controller;
13
14
use StingerSoft\EntitySearchBundle\Form\QueryType;
15
use StingerSoft\EntitySearchBundle\Model\Document;
16
use StingerSoft\EntitySearchBundle\Model\PaginatableResultSet;
17
use StingerSoft\EntitySearchBundle\Model\Query;
18
use StingerSoft\EntitySearchBundle\Services\Mapping\DocumentToEntityMapperInterface;
19
use StingerSoft\EntitySearchBundle\Services\SearchService;
20
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
21
use Symfony\Component\HttpFoundation\JsonResponse;
22
use Symfony\Component\HttpFoundation\Request;
23
use Symfony\Component\HttpFoundation\Session\SessionInterface;
24
25
/**
26
 * Basic implementation of a search controller to offer a frontend access to the search service
27
 */
28
class SearchController extends Controller {
29
30
	/**
31
	 * Maximum number of suggestions which should be provided by the autocomplete action
32
	 *
33
	 * @var integer
34
	 */
35
	const SUGGESTION_COUNT = 10;
36
37
	/**
38
	 * Prefix to store information in the session variable
39
	 *
40
	 * @var string
41
	 */
42
	const SESSION_PREFIX = 'stinger_soft_entity_search';
43
44
	/**
45
	 * Number of results which should be displayed per page
46
	 *
47
	 * @var integer
48
	 */
49
	const RESULTS_PER_PAGE = 10;
50
51
	/**
52
	 *
53
	 * @var SearchService
54
	 */
55
	private $searchService;
0 ignored issues
show
Unused Code introduced by
The property $searchService is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
56
57
	public function searchAction(Request $request) {
58
		if($request->query->get('term', false) !== false) {
59
			$this->setSearchTerm($request->getSession(), $request->query->get('term'));
0 ignored issues
show
Bug introduced by
It seems like $request->getSession() can be null; however, setSearchTerm() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
60
			return $this->redirectToRoute('stinger_soft_entity_search_search');
61
		}
62
		
63
		$term = $this->getSearchTerm($request->getSession());
0 ignored issues
show
Bug introduced by
It seems like $request->getSession() can be null; however, getSearchTerm() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
64
		$facets = $this->getSearchFacets($request->getSession());
0 ignored issues
show
Bug introduced by
It seems like $request->getSession() can be null; however, getSearchFacets() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
65
		
66
		$query = new Query($term, $facets, $this->getAvailableFacets());
67
		
68
		$facetForm = $this->createForm(QueryType::class, $query, array(
69
			'used_facets' => $query->getUsedFacets() 
70
		));
71
		
72
		if($request->isMethod('POST')) {
73
			$facetForm->handleRequest($request);
74
			
75
			if($facetForm->get('clear')->isClicked()) {
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Symfony\Component\Form\FormInterface as the method isClicked() does only exist in the following implementations of said interface: Symfony\Component\Form\SubmitButton.

Let’s take a look at an example:

interface User
{
    /** @return string */
    public function getPassword();
}

class MyUser implements User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
76
				$query->setFacets($this->getDefaultFacets());
77
			}
78
			$this->setSearchTerm($request->getSession(), $query->getSearchTerm());
0 ignored issues
show
Bug introduced by
It seems like $request->getSession() can be null; however, setSearchTerm() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
79
			$this->setSearchFacets($request->getSession(), $query->getFacets());
0 ignored issues
show
Bug introduced by
It seems like $request->getSession() can be null; however, setSearchFacets() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
80
		}
81
		$result = $this->getSearchService()->search($query);
82
		
83
		$facetForm = $this->createForm(QueryType::class, $query, array(
84
			'result' => $result,
85
			'used_facets' => $query->getUsedFacets(),
86
			'facet_formatter' => $this->getFacetFormatter() 
87
		));
88
		
89
		$page = $request->query->get('page', 1);
90
		$results = array();
0 ignored issues
show
Unused Code introduced by
$results is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
91
		if($result instanceof PaginatableResultSet) {
92
			$results = $result->paginate($page, self::RESULTS_PER_PAGE);
93
		} else {
94
			$results = $result->getResults(($page - 1) * self::RESULTS_PER_PAGE, self::RESULTS_PER_PAGE);
95
		}
96
		
97
		return $this->render('StingerSoftEntitySearchBundle:Search:results.html.twig', array(
98
			'results' => $results,
99
			'resultSet' => $result,
100
			'term' => $query->getSearchTerm(),
101
			'mapper' => $this->get(DocumentToEntityMapperInterface::SERVICE_ID),
102
			'facetForm' => $facetForm->createView() 
103
		));
104
	}
105
106
	protected function getFacetFormatter() {
107
		return null;
108
	}
109
110
	/**
111
	 * Returns an array of preselected facets (no facet selected is the default)
112
	 *
113
	 * @return string[string][]
0 ignored issues
show
Documentation introduced by
The doc-type string[string][] could not be parsed: Expected "]" at position 2, but found "string". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
114
	 */
115
	protected function getDefaultFacets() {
116
		$availableFacets = $this->getAvailableFacets();
117
		return array_combine($availableFacets, array_fill(0, count($availableFacets), array()));
118
	}
119
120
	/**
121
	 * Returns an array of the available facets which should be offered the user as a filter
122
	 *
123
	 * @return string[]
124
	 */
125
	protected function getAvailableFacets() {
126
		return array(
127
			Document::FIELD_AUTHOR,
128
			Document::FIELD_EDITORS,
129
			Document::FIELD_TYPE 
130
		);
131
	}
132
133
	/**
134
	 * Fetches the searched facets from the session object
135
	 *
136
	 * @param SessionInterface $session        	
137
	 * @return string[string][]
0 ignored issues
show
Documentation introduced by
The doc-type string[string][] could not be parsed: Expected "]" at position 2, but found "string". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
138
	 */
139
	protected function getSearchFacets(SessionInterface $session) {
140
		$facets = $session()->get(self::SESSION_PREFIX . '_facets', false);
141
		return $facets ? json_decode($facets, true) : $this->getDefaultFacets();
142
	}
143
144
	protected function setSearchFacets(SessionInterface $session, $facets) {
0 ignored issues
show
Unused Code introduced by
The parameter $session 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...
Unused Code introduced by
The parameter $facets 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...
145
	}
146
147
	/**
148
	 * Fetches the search term from the session object
149
	 *
150
	 * @param SessionInterface $session        	
151
	 * @return mixed
152
	 */
153
	protected function getSearchTerm(SessionInterface $session) {
154
		return $session->get(self::SESSION_PREFIX . '_term', false);
155
	}
156
157
	/**
158
	 * Sets the given search term in the user's session
159
	 *
160
	 * @param SessionInterface $session        	
161
	 * @param string $term        	
162
	 */
163
	protected function setSearchTerm(SessionInterface $session, $term) {
164
		$session->set(self::SESSION_PREFIX . '_term', $term);
165
	}
166
167
	/**
168
	 * Returns a JSON array of autocompletions for the given term.
169
	 * The term can be provided as a GET or POST paramater with the name <em>term</em>
170
	 *
171
	 * @param Request $request        	
172
	 * @return \Symfony\Component\HttpFoundation\JsonResponse
173
	 */
174
	public function autocompleteAction(Request $request) {
175
		$term = $request->get('term');
176
		return new JsonResponse($this->getSearchService()->autocomplete($term, self::SUGGESTION_COUNT));
177
	}
178
179
	/**
180
	 * Provides an online help for the configured search service.
181
	 * If the search service has no online help defined a warning message will be displayed to the user.
182
	 *
183
	 * @param Request $request        	
184
	 * @return \Symfony\Component\HttpFoundation\Response
185
	 */
186
	public function onlineHelpAction(Request $request) {
187
		$template = $this->getSearchService()->getOnlineHelp($request->getLocale(), $this->getDefaultLocale());
0 ignored issues
show
Bug introduced by
The method getDefaultLocale() does not seem to exist on object<StingerSoft\Entit...oller\SearchController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
188
		return $this->render($template ?: 'StingerSoftEntitySearchBundle:Help:no_help.html.twig');
189
	}
190
191
	/**
192
	 * Inits and returns the configured search service
193
	 *
194
	 * @return SearchService
195
	 */
196
	protected function getSearchService() {
197
		$this->service = $this->get(SearchService::SERVICE_ID);
0 ignored issues
show
Bug introduced by
The property service does not seem to exist. Did you mean searchService?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
198
		$this->service->setObjectManager($this->getObjectManager());
0 ignored issues
show
Bug introduced by
The property service does not seem to exist. Did you mean searchService?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
Bug introduced by
The method getObjectManager() does not seem to exist on object<StingerSoft\Entit...oller\SearchController>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
199
		return $this->service;
0 ignored issues
show
Bug introduced by
The property service does not seem to exist. Did you mean searchService?

An attempt at access to an undefined property has been detected. This may either be a typographical error or the property has been renamed but there are still references to its old name.

If you really want to allow access to undefined properties, you can define magic methods to allow access. See the php core documentation on Overloading.

Loading history...
200
	}
201
}