Skip to content

Commit 0c236ed

Browse files
committed
Refactored the feature
1 parent da43022 commit 0c236ed

File tree

9 files changed

+78
-58
lines changed

9 files changed

+78
-58
lines changed

app/Resources/translations/messages.en.xlf

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,10 @@
255255
<source>menu.rss</source>
256256
<target>Blog Posts RSS</target>
257257
</trans-unit>
258+
<trans-unit id="menu.search">
259+
<source>menu.search</source>
260+
<target>Search</target>
261+
</trans-unit>
258262

259263
<trans-unit id="post.to_publish_a_comment">
260264
<source>post.to_publish_a_comment</source>

app/Resources/views/base.html.twig

Lines changed: 4 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -37,13 +37,6 @@
3737
<span class="icon-bar"></span>
3838
</button>
3939
</div>
40-
<div class="search-bar col-sm-5">
41-
<form action="{{ path('blog_search') }}" method="get">
42-
<div class="input-group-sm">
43-
<input name="q" type="text" class="form-control" placeholder="{{ 'post.search_for'|trans }}" autocomplete="off">
44-
</div>
45-
</form>
46-
</div>
4740
<div class="navbar-collapse collapse">
4841
<ul class="nav navbar-nav navbar-right">
4942

@@ -71,6 +64,10 @@
7164
</li>
7265
{% endif %}
7366

67+
<li>
68+
<a href="{{ path('blog_search') }}"> <i class="fa fa-search"></i> {{ 'menu.search'|trans }}</a>
69+
</li>
70+
7471
<li class="dropdown">
7572
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false" id="locales">
7673
<i class="fa fa-globe" aria-hidden="true"></i>
@@ -142,15 +139,6 @@
142139
<script src="{{ asset('build/manifest.js') }}"></script>
143140
<script src="{{ asset('build/js/common.js') }}"></script>
144141
<script src="{{ asset('build/js/app.js') }}"></script>
145-
<script>
146-
(function($) {
147-
$(function() {
148-
$('.search-bar input[name="q"]').instantSearch({
149-
noItemsFoundMessage: '{{ 'post.no_posts_found'|trans }}'
150-
});
151-
});
152-
})(window.jQuery);
153-
</script>
154142
{% endblock %}
155143

156144
{# it's not mandatory to set the timezone in localizeddate(). This is done to
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
{% extends 'base.html.twig' %}
2+
3+
{% block javascripts %}
4+
{{ parent() }}
5+
<script src="{{ asset('build/js/search.js') }}"></script>
6+
{% endblock %}
7+
8+
{% block main %}
9+
<form action="{{ path('blog_search') }}" method="get">
10+
<div class="form-group">
11+
<input name="q" type="text" class="form-control search-field" placeholder="{{ 'post.search_for'|trans }}" autocomplete="off" autofocus>
12+
</div>
13+
</form>
14+
15+
<div id="results">
16+
</div>
17+
{% endblock %}

assets/js/app.js

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,7 @@
1-
// Exposes jQuery as a global variable
2-
global.$ = global.jQuery = require('jquery');
3-
41
// loads the Bootstrap jQuery plugins
52
import 'bootstrap-sass/assets/javascripts/bootstrap/dropdown.js';
63
import 'bootstrap-sass/assets/javascripts/bootstrap/modal.js';
74
import 'bootstrap-sass/assets/javascripts/bootstrap/transition.js';
85

96
// loads the code syntax highlighting library
107
import './highlight.js';
11-
12-
// loads the instant search library
13-
import './jquery.instantSearch.js';

assets/js/jquery.instantSearch.js

Lines changed: 8 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,3 @@
1-
/*
2-
* This file is part of the Symfony package.
3-
*
4-
* (c) Fabien Potencier <[email protected]>
5-
*
6-
* For the full copyright and license information, please view the LICENSE
7-
* file that was distributed with this source code.
8-
*/
9-
101
/**
112
* jQuery plugin for an instant searching.
123
*
@@ -23,7 +14,7 @@
2314
minQueryLength: 2,
2415
maxPreviewItems: 10,
2516
previewDelay: 500,
26-
noItemsFoundMessage: 'No items found'
17+
noItemsFoundMessage: 'No results found.'
2718
};
2819

2920
function debounce(fn, delay) {
@@ -55,17 +46,19 @@
5546
}
5647

5748
var addItemToPreview = function(item) {
58-
var $link = $('<a>').attr('href', item.url).text(item.result);
59-
var $li = $('<li class="list-group-item">').append($link);
49+
var $link = $('<a>').attr('href', item.url).text(item.title);
50+
var $title = $('<h3>').attr('class', 'm-b-0').append($link);
51+
var $summary = $('<p>').text(item.summary);
52+
var $result = $('<div>').append($title).append($summary);
6053

61-
$preview.append($li);
54+
$preview.append($result);
6255
}
6356

6457
var noItemsFound = function() {
65-
var $li = $('<li class="list-group-item">').text(config.noItemsFoundMessage);
58+
var $result = $('<div>').text(config.noItemsFoundMessage);
6659

6760
$preview.empty();
68-
$preview.append($li);
61+
$preview.append($result);
6962
}
7063

7164
var updatePreview = function() {

assets/js/search.js

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import './jquery.instantSearch.js';
2+
3+
$(function() {
4+
$('.search-field').instantSearch();
5+
});

src/AppBundle/Controller/BlogController.php

Lines changed: 9 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -160,31 +160,20 @@ public function commentFormAction(Post $post)
160160
*/
161161
public function searchAction(Request $request)
162162
{
163-
$query = $request->query->get('q', '');
164-
165-
// Sanitizing the query: removes all non-alphanumeric characters except whitespaces
166-
$query = preg_replace('/[^[:alnum:] ]/', '', trim(preg_replace('/[[:space:]]+/', ' ', $query)));
167-
168-
// Splits the query into terms and removes all terms which
169-
// length is less than 2
170-
$terms = array_unique(explode(' ', mb_strtolower($query)));
171-
$terms = array_filter($terms, function ($term) {
172-
return 2 <= mb_strlen($term);
173-
});
174-
175-
$posts = [];
176-
177-
if (!empty($terms)) {
178-
$posts = $this->getDoctrine()->getRepository(Post::class)->findByTerms($terms);
163+
if (!$request->isXmlHttpRequest()) {
164+
return $this->render('blog/search.html.twig');
179165
}
180166

181-
$results = [];
167+
$query = $request->query->get('q', '');
168+
$posts = $this->getDoctrine()->getRepository(Post::class)->findBySearchQuery($query);
182169

170+
$results = [];
183171
foreach ($posts as $post) {
184-
array_push($results, [
185-
'result' => htmlspecialchars($post->getTitle()),
172+
$results[] = [
173+
'title' => htmlspecialchars($post->getTitle()),
174+
'summary' => htmlspecialchars($post->getSummary()),
186175
'url' => $this->generateUrl('blog_post', ['slug' => $post->getSlug()]),
187-
]);
176+
];
188177
}
189178

190179
return new JsonResponse($results);

src/AppBundle/Repository/PostRepository.php

Lines changed: 30 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,8 +60,15 @@ private function createPaginator(Query $query, $page)
6060
return $paginator;
6161
}
6262

63-
public function findByTerms(array $terms, $limit = Post::NUM_ITEMS)
63+
public function findBySearchQuery($rawQuery, $limit = Post::NUM_ITEMS)
6464
{
65+
$query = $this->sanitizeSearchQuery($rawQuery);
66+
$terms = $this->extractSearchTerms($query);
67+
68+
if (empty($terms)) {
69+
return [];
70+
}
71+
6572
$queryBuilder = $this->createQueryBuilder('p');
6673

6774
foreach ($terms as $key => $term) {
@@ -77,4 +84,26 @@ public function findByTerms(array $terms, $limit = Post::NUM_ITEMS)
7784
->getQuery()
7885
->getResult();
7986
}
87+
88+
private function sanitizeSearchQuery($query)
89+
{
90+
// remove all non-alphanumeric characters except whitespaces
91+
return preg_replace('/[^[:alnum:] ]/', '', trim(preg_replace('/[[:space:]]+/', ' ', $query)));
92+
}
93+
94+
/**
95+
* Splits the query into terms and removes the ones which are too short.
96+
*
97+
* @param string $query
98+
*
99+
* @return array
100+
*/
101+
private function extractSearchTerms($searchQuery)
102+
{
103+
$terms = array_unique(explode(' ', mb_strtolower($searchQuery)));
104+
105+
return array_filter($terms, function ($term) {
106+
return 2 <= mb_strlen($term);
107+
});
108+
}
80109
}

webpack.config.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ Encore
1616
.addEntry('js/app', './assets/js/app.js')
1717
.addEntry('js/login', './assets/js/login.js')
1818
.addEntry('js/admin', './assets/js/admin.js')
19+
.addEntry('js/search', './assets/js/search.js')
1920
.addStyleEntry('css/app', ['./assets/scss/app.scss'])
2021
.addStyleEntry('css/admin', ['./assets/scss/admin.scss'])
2122
;

0 commit comments

Comments
 (0)