Skip to content

Instantly share code, notes, and snippets.

@haltaction
Last active February 4, 2016 16:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save haltaction/0186b9fc63dc3bbeca0e to your computer and use it in GitHub Desktop.
Save haltaction/0186b9fc63dc3bbeca0e to your computer and use it in GitHub Desktop.
Symfony mongo search service
public function searchAction(Request $request)
{
$search = $request->query->get('s');
$searchResult = $this->get('booking.core.service.search_service')
->searchByDocument(
'NewsBundle\Document\News',
[
'_id',
'type',
'title',
'content',
'author',
],
$search
);
<?php
namespace CoreBundle\Service;
use Doctrine\ODM\MongoDB\DocumentManager;
use Doctrine\ODM\MongoDB\Query\Query;
class SearchService
{
private $dm;
public function __construct(DocumentManager $documentManager)
{
$this->dm = $documentManager;
}
/**
* @param null $documentName
* @param array $fields
* @param string $search
* @return bool|Query
*/
public function searchByDocument($documentName = null, array $fields = [], $search = '')
{
$search = preg_quote(trim($search));
if (empty($search)) {
return false;
}
if (0 == count($fields)) {
return false;
}
$query = $this->dm
->createQueryBuilder($documentName);
foreach ($fields as $filed) {
if (('_id' === $filed) && (1 === preg_match("/^[abcdef\\d]{24}$/", $search))) {
$query
->addOr($query->expr()->field($filed)->equals(new \MongoId($search)));
} else {
$query
->addOr($query->expr()->field($filed)->equals(new \MongoRegex('/.*'.htmlspecialchars($search).'.*/i')));
}
}
return $query
// ->hydrate(false)
->getQuery();
}
}
<service id="booking.core.service.search_service"
class="CoreBundle\Service\SearchService">
<argument type="service" id="doctrine.odm.mongodb.document_manager"/>
</service>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment