Skip to content

Commit

Permalink
Second round of testing.
Browse files Browse the repository at this point in the history
  • Loading branch information
fmizzell committed Jan 30, 2020
1 parent b0c14ff commit 57fa931
Show file tree
Hide file tree
Showing 3 changed files with 188 additions and 24 deletions.
64 changes: 40 additions & 24 deletions modules/custom/dkan_search_api/src/Controller.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,28 +3,28 @@
namespace Drupal\dkan_search_api;

use Drupal\dkan_common\JsonResponseTrait;
use Drupal\dkan_metastore\Service;
use Drupal\search_api\Query\QueryInterface;
use Drupal\search_api\Query\ResultSet;
use Symfony\Component\HttpFoundation\RequestStack;

/**
*
*/
class Controller {
use JsonResponseTrait;

public function __construct()
{
}

/**
*
*/
public function search() {
$storage = \Drupal::service("entity.manager")->getStorage('search_api_index');
/** @var \Drupal\search_api\IndexInterface $index */

/* @var \Drupal\search_api\IndexInterface $index */
$index = $storage->load('dkan');

if (!$index) {
return $this->getResponse("No index name 'dkan' exists.", 500);
return $this->getResponse((object) ['message' => "An index named [dkan] does not exist."], 500);
}

$fields = array_keys($index->getFields());
Expand All @@ -45,9 +45,9 @@ public function search() {

$this->setSort($query, $params, $fields);

$end = ($params['page'] * $params['pageSize']);
$start = $end - $params['pageSize'];
$query->range($start, $params['pageSize']);
$end = ($params['page'] * $params['page-size']);
$start = $end - $params['page-size'];
$query->range($start, $params['page-size']);

/** @var $result ResultSet*/
$result = $query->execute();
Expand Down Expand Up @@ -78,18 +78,21 @@ public function search() {
*/
private function getParams() {
$defaults = [
"pageSize" => 10,
"page-size" => 10,
"page" => 1,
];

$params = \Drupal::request()->query->all();
/* @var $requestStack RequestStack */
$requestStack = \Drupal::service('request_stack');
$request = $requestStack->getCurrentRequest();
$params = $request->query->all();

foreach ($defaults as $param => $default) {
$params[$param] = isset($params[$param]) ? $params[$param] : $default;
}

if ($params["pageSize"] > 100) {
$params["pageSize"] = 100;
if ($params["page-size"] > 100) {
$params["page-size"] = 100;
}

return $params;
Expand All @@ -99,13 +102,15 @@ private function getParams() {
*
*/
private function setFullText(QueryInterface $query, $params, $index) {
if ($params['fulltext']) {
if (isset($params['fulltext'])) {
$fulltextFields = $index->getFulltextFields();
$cg = $query->createConditionGroup('OR');
foreach ($fulltextFields as $field) {
$cg->addCondition($field, $params['fulltext']);
if (!empty($fulltextFields)) {
$values = [];
foreach ($fulltextFields as $field) {
$values[$field][] = $params['fulltext'];
}
$this->createConditionGroup($query, $values, 'OR');
}
$query->addConditionGroup($cg);
}
}

Expand All @@ -115,11 +120,11 @@ private function setFullText(QueryInterface $query, $params, $index) {
private function setFieldConditions(QueryInterface $query, $fields, $params) {
foreach ($fields as $field) {
if (isset($params[$field])) {
$cg = $query->createConditionGroup();
$values = [];
foreach (explode(",", $params[$field]) as $value) {
$cg->addCondition($field, trim($value));
$values[$field][] = trim($value);
}
$query->addConditionGroup($cg);
$this->createConditionGroup($query, $values);
}
}
}
Expand All @@ -135,7 +140,8 @@ private function getFacets(QueryInterface $query, $fields) {
$metastore = \Drupal::service("dkan_metastore.service");

foreach ($facetsTypes as $type) {
if (in_array($type, $fields)) {
$inArray = in_array($type, $fields);
if ($inArray) {
foreach ($metastore->getAll($type) as $thing) {
$myquery = clone $query;
$myquery->addCondition($type, $thing->data);
Expand All @@ -157,8 +163,8 @@ private function getFacets(QueryInterface $query, $fields) {
*/
private function setSort(QueryInterface $query, $params, $fields) {
if (isset($params['sort']) && in_array($params['sort'], $fields)) {
if (isset($params['sort_order']) && ($params['sort_order'] == 'asc' || $params['sort_order'] == 'desc')) {
$order = ($params['sort_order'] == 'asc') ? $query::SORT_ASC : $query::SORT_DESC;
if (isset($params['sort-order']) && ($params['sort-order'] == 'asc' || $params['sort-order'] == 'desc')) {
$order = ($params['sort-order'] == 'asc') ? $query::SORT_ASC : $query::SORT_DESC;
$query->sort($params['sort'], $order);
}
else {
Expand All @@ -170,4 +176,14 @@ private function setSort(QueryInterface $query, $params, $fields) {
}
}

private function createConditionGroup(QueryInterface $query, $array, $conjuction = 'AND') {
$cg = $query->createConditionGroup($conjuction);
foreach ($array as $field => $values) {
foreach ($values as $value) {
$cg->addCondition($field, $value);
}
}
$query->addConditionGroup($cg);
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
<?php

use PHPUnit\Framework\TestCase;
use MockChain\Options;
use Drupal\Core\DependencyInjection\Container;

class DatasetTest extends TestCase
{
public function test() {
$schema = '
{
"$id": "https://example.com/person.schema.json",
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "Person",
"type": "object",
"properties": {
"firstName": {
"type": "string",
"description": "The person\'s first name."
},
"lastName": {
"type": "string",
"description": "The person\'s last name."
},
"age": {
"description": "Age in years which must be equal to or greater than zero.",
"type": "integer",
"minimum": 0
}
}
}
';

$options = (new Options())
->add('dkan_schema.schema_retriever', \Drupal\dkan_schema\SchemaRetriever::class);


$container = (new MockChain\Chain($this))
->add(Container::class, "get", $options)
->add(\Drupal\dkan_schema\SchemaRetriever::class, 'retrieve', $schema)
->getMock();

\Drupal::setContainer($container);

$thing = (object) ['firstName' => 'hello', 'lastName' => 'goodbye', 'age' => 5000];
$json = json_encode($thing);
$dataset = new \Drupal\dkan_search_api\ComplexData\Dataset($json);
$this->assertEquals($json, json_encode($dataset->getValue()));

$properties = $dataset->getProperties();
$this->assertEquals(3, count($properties));
}
}
95 changes: 95 additions & 0 deletions modules/custom/dkan_search_api/tests/src/Unit/ControllerTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
<?php

use Drupal\search_api\Item\Item;
use Drupal\search_api\Query\ConditionGroup;
use Drupal\search_api\Query\ResultSet;
use MockChain\Chain;
use MockChain\Options;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Component\DependencyInjection\Container;
use Drupal\Core\Entity\EntityManager;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\search_api\IndexInterface;
use Drupal\search_api\Query\QueryInterface;
use Drupal\search_api\Utility\QueryHelperInterface;
use Drupal\dkan_metastore\Service;
use Drupal\dkan_search_api\Controller;

class ControllerTest extends TestCase {

public function test() {

$paramsBag = (new Chain($this))
->add(ParameterBag::class, 'all',
['page-size' => 500,
'fulltext' => 'hello',
'description' => 'goodbye',
'sort' => 'description',
'sort-order' => 'asc'])
->getMock();

$request = (new Chain($this))
->add(Request::class, 'blah', null)
->getMock();

$reflection = new ReflectionClass($request);
$reflection_property = $reflection->getProperty('query');
$reflection_property->setAccessible(true);
$reflection_property->setValue($request, $paramsBag);

$options = (new Options())
->add('entity.manager', EntityManager::class)
->add('request_stack', RequestStack::class)
->add('search_api.query_helper', QueryHelperInterface::class)
->add('dkan_metastore.service', Service::class);

$item = (new Chain($this))
->add(Item::class, 'getId', 1)
->getMock();

$thing = (object) ['title' => 'hello', 'description' => 'goodbye'];

$container = (new MockChain\Chain($this))
->add(Container::class, "get", $options)
->add(EntityManager::class, 'getStorage', EntityStorageInterface::class)
->add(EntityStorageInterface::class, 'load', IndexInterface::class)
->add(IndexInterface::class, 'getFields', ['description' => 'blah'])
->add(IndexInterface::class, 'getFulltextFields', ['title'])
->add(RequestStack::class, 'getCurrentRequest', $request)
->add(QueryHelperInterface::class, 'createQuery', QueryInterface::class)
->add(QueryInterface::class, 'execute', ResultSet::class)
->add(QueryInterface::class, 'createConditionGroup', ConditionGroup::class)
->add(ResultSet::class, 'getResultCount', 1)
->add(ResultSet::class, 'getResultItems', [$item])
->add(Service::class, 'get', json_encode($thing))
->getMock();

\Drupal::setContainer($container);

$controller = new Controller();

/* @var $response \Symfony\Component\HttpFoundation\JsonResponse */
$response = $controller->search();
$this->assertEquals(
json_encode((object) ['total' => 1, 'results' => [$thing], 'facets' => []]),
$response->getContent());
}

public function testNoIndex() {
$container = (new MockChain\Chain($this))
->add(Container::class, "get", EntityManager::class)
->add(EntityManager::class, 'getStorage', EntityStorageInterface::class)
->getMock();

\Drupal::setContainer($container);

$controller = new Controller();

/* @var $response \Symfony\Component\HttpFoundation\JsonResponse */
$response = $controller->search();
$this->assertEquals(json_encode((object) ['message' => "An index named [dkan] does not exist."]), $response->getContent());
}
}

0 comments on commit 57fa931

Please sign in to comment.