Last active
February 4, 2016 16:41
-
-
Save haltaction/0186b9fc63dc3bbeca0e to your computer and use it in GitHub Desktop.
Symfony mongo search service
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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