mirror of
https://github.com/jbcr/core.git
synced 2026-04-30 04:03:11 +02:00
Add Bolt\Storage\Query and Bolt\Twig\TwigRecordsView from Bolt 3
This is commit c3ead6d48cc2431d72ae7f81947df7fa5fefa92b in https://github.com/bolt/bolt Copied on 2018-10-30 14:00 Once Query works, it could be refactored from `Bolt\Storage\Query` to `Bolt\Query`
This commit is contained in:
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
|
||||
namespace Bolt\Storage\Query\Directive;
|
||||
|
||||
use Bolt\Storage\Query\QueryInterface;
|
||||
|
||||
/**
|
||||
* Directive to alter query based on 'order' parameter.
|
||||
*
|
||||
* eg: 'pages', ['order'=>'-datepublish']
|
||||
*/
|
||||
class OrderDirective
|
||||
{
|
||||
/**
|
||||
* @param QueryInterface $query
|
||||
* @param string $order
|
||||
*/
|
||||
public function __invoke(QueryInterface $query, $order)
|
||||
{
|
||||
if (!$order) {
|
||||
return;
|
||||
}
|
||||
|
||||
// remove default order
|
||||
$query->getQueryBuilder()->resetQueryPart('orderBy');
|
||||
|
||||
$separatedOrders = $this->getOrderBys($order);
|
||||
foreach ($separatedOrders as $order) {
|
||||
$order = trim($order);
|
||||
if (strpos($order, '-') === 0) {
|
||||
$direction = 'DESC';
|
||||
$order = substr($order, 1);
|
||||
} elseif (strpos($order, ' DESC') !== false) {
|
||||
$direction = 'DESC';
|
||||
$order = str_replace(' DESC', '', $order);
|
||||
} else {
|
||||
$direction = null;
|
||||
}
|
||||
$query->getQueryBuilder()->addOrderBy($order, $direction);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $order
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
protected function getOrderBys($order)
|
||||
{
|
||||
$separatedOrders = [$order];
|
||||
|
||||
if ($this->isMultiOrderQuery($order)) {
|
||||
$separatedOrders = explode(',', $order);
|
||||
}
|
||||
|
||||
return $separatedOrders;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param $order
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
protected function isMultiOrderQuery($order)
|
||||
{
|
||||
return strpos($order, ',') !== false;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user