Skip to content

Instantly share code, notes, and snippets.

@guillaumepotier
Last active November 17, 2015 13:08
Show Gist options
  • Save guillaumepotier/417b3dbe0a9de2cf9853 to your computer and use it in GitHub Desktop.
Save guillaumepotier/417b3dbe0a9de2cf9853 to your computer and use it in GitHub Desktop.
Algolia blog
// https://www.algolia.com/doc/php#example-2
var client = algoliasearch("{{ app_id }}", "{{ token }}");
var index = client.initIndex("{{ index }}");
// repeat the security filters here
client.setExtraHeader('X-Algolia-QueryParameters', 'tagFilters=({{ parameters }})&validUntil={{ validUntil }}');
index.search($('#q').val(), function searchDone(err, content) {
if (err) {
console.error(err);
return;
}
console.log(content);
});
<?php
// ...
class Api5Controller extends Controller
{
/**
* Get a token
*
* @Route("/algolia/bootstrap", name="api5_search_algolia")
* @Method("GET")
*/
public function bootstrapAction()
{
if ($this->get('security.token_storage')->getToken()->isAnonymous()) {
throw new ApiException('must_be_logged', 401);
}
$user = $this->getUser();
$tokenService = $this->get('algolia.token');
$filters = $tokenService->getFilters($user);
return new ApiResponse([
'app_id' => $this->container->getParameter('algolia.app_id'),
'index' => $this->container->getParameter('wisembly.search.index.name'),
'token' => $tokenService->getToken($filters),
'validUntil' => isset($filters['validUntil']) ? $filters['validUntil'] : null,
'parameters' => $tokenService->getTagFilter($filters)
], 200);
}
}
{
"meeting": {
"id" : "rdc4368",
"name" : "A meeting name",
"description" : "This is a great meeting description",
"recurring" : false,
"expected_start" : "2015-12-21T18:00:00+00:00",
"expected_end" : "2015-12-21T20:00:00+00:00",
"real_start" : null,
"real_end" : null,
"expected_duration" : "02:00",
"real_duration" : "00:00",
"counts" : {
"participants" : 3,
"actions" : 0,
"decisions" : 0,
"issues" : 0
},
"owner" : "w44261a",
"participants" : ["w44261a", "f8acaef", "ce48a27"],
"items" : []
},
"custom_ranking": {
"expected_start" : 1450720800,
"prepared" : 0
},
"_tags": ["user_w44261a", "user_f8acaef", "user_ce48a27"]
}
<?php
// ...
class Token
{
/**
* generates an api user token for algolia search
* the search is limited for specific user's tags
* as defined into getTagFilter
*
* @link https://www.algolia.com/doc/php#example-1
*/
public function getToken(array $filters)
{
return $this->client->generateSecuredApiKey(
$this->searchApiKey,
$this->getTagFilter($filters)
);
}
/**
* gives a tagFilter available and mandatory for user
* as a querystring form
*
* @link https://www.algolia.com/doc/php#example-2
*/
public function getTagFilter(array $filters)
{
return implode('&', array_map(function ($key, $value) {
return sprintf('%s=%s', $key, $value);
}, array_keys($filters), array_values($filters)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment