Skip to content

Commit

Permalink
Merge pull request #52 from spira/feature/default-order-by
Browse files Browse the repository at this point in the history
allow default ordering for getAllEntities
  • Loading branch information
Jeremy Sik committed Apr 17, 2016
2 parents 47b8fc8 + 75934a7 commit 1d31ab7
Show file tree
Hide file tree
Showing 11 changed files with 223 additions and 3 deletions.
2 changes: 1 addition & 1 deletion Controllers/EntityController.php
Original file line number Diff line number Diff line change
Expand Up @@ -385,7 +385,7 @@ protected function countEntities()
*/
protected function getAllEntities($limit = null, $offset = null)
{
return $this->getModel()->take($limit)->skip($offset)->get();
return $this->getModel()->getDefaultOrder()->take($limit)->skip($offset)->get();
}

/**
Expand Down
21 changes: 21 additions & 0 deletions Model/Model/BaseModel.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@
* @method static Builder whereNull($column)
* @method static BaseModel skip($offset)
* @method static BaseModel take($limit)
*
* * scopes
* @method static Builder getDefaultOrder modifies query to order by $defaultOrderBy
*/
abstract class BaseModel extends Model
{
Expand All @@ -49,6 +52,13 @@ abstract class BaseModel extends Model

protected static $validationRules = [];

/**
* The default order by value.
*
* @var string
*/
protected $defaultOrderBy;

/**
* Temporary fix of polymorphic relation naming.
*
Expand Down Expand Up @@ -313,4 +323,15 @@ public static function booted($callback, $priority = 0)
{
static::registerModelEvent('booted', $callback, $priority);
}

/**
* Allows for default ordering of queries if required and specified.
*
* @param Builder $query
* @return Builder
*/
public function scopeGetDefaultOrder(Builder $query)
{
return ($this->defaultOrderBy) ? $query->orderBy($this->defaultOrderBy) : $query;
}
}
47 changes: 47 additions & 0 deletions Model/Test/OrderedTestEntity.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
<?php

/*
* This file is part of the Spira framework.
*
* @link https://github.com/spira/spira
*
* For the full copyright and license information, please view the LICENSE file that was distributed with this source code.
*/

namespace Spira\Core\Model\Test;

use Illuminate\Database\Eloquent\Collection;
use Spira\Core\Model\Model\BaseModel;
use Spira\Core\Model\Model\LocalizableModelInterface;
use Spira\Core\Model\Model\LocalizableModelTrait;

/**
* Class OrderedTestEntity.
*
* @property Collection $testMany
*/
class OrderedTestEntity extends BaseModel implements LocalizableModelInterface
{
use LocalizableModelTrait;

/**
* The database table used by the model.
*
* @var string
*/
public $table = 'ordered_test_entities';
protected $primaryKey = 'entity_id';
public $timestamps = false;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = ['entity_id', 'varchar', 'integer'];
/**
* Override default order by value.
*
* @var string
*/
protected $defaultOrderBy = 'varchar';
}
2 changes: 1 addition & 1 deletion Responder/Transformers/BaseTransformer.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
use Spira\Core\Responder\Contract\TransformerInterface;
use Spira\Core\Responder\TransformerService;

abstract class BaseTransformer extends TransformerAbstract implements TransformerInterface
abstract class BaseTransformer extends TransformerAbstract implements TransformerInterface
{
/**
* @var TransformerService
Expand Down
2 changes: 1 addition & 1 deletion Validation/ValidationException.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\HttpException;

class ValidationException extends HttpException implements TransformableInterface
class ValidationException extends HttpException implements TransformableInterface
{
/**
* The validation error messages.
Expand Down
9 changes: 9 additions & 0 deletions database/factories/ModelFactory.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
* For the full copyright and license information, please view the LICENSE file that was distributed with this source code.
*/

use Spira\Core\Model\Test\OrderedTestEntity;
use Spira\Core\Model\Test\TestEntity;
use Illuminate\Support\Facades\Hash;
use Spira\Core\Model\Test\SecondTestEntity;
Expand Down Expand Up @@ -42,6 +43,14 @@
];
});

$factory->define(OrderedTestEntity::class, function ($faker) {
return [
'entity_id' => $faker->uuid,
'varchar' => $faker->word,
'integer' => $faker->numberBetween(0, 500),
];
});

$factory->defineAs(TestEntity::class, 'custom', function ($faker) use ($factory) {
$testEntity = $factory->raw(TestEntity::class);

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

/*
* This file is part of the Spira framework.
*
* @link https://github.com/spira/spira
*
* For the full copyright and license information, please view the LICENSE file that was distributed with this source code.
*/

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Spira\Core\Model\Test\OrderedTestEntity;

class CreateOrderedTestEntitiesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
if (env('APP_ENV') !== 'spira-core-testing') {
return true;
}
Schema::create(OrderedTestEntity::getTableName(), function (Blueprint $table) {
$table->uuid('entity_id');
$table->string('varchar', 255);
$table->integer('integer');

$table->primary('entity_id');
}
);
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
if (env('APP_ENV') !== 'spira-core-testing') {
return true;
}
Schema::drop(OrderedTestEntity::getTableName());
}
}
35 changes: 35 additions & 0 deletions tests/Extensions/AssertionsTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -228,4 +228,39 @@ public function assertResponseStatusWithDebug($code)
throw $e;
}
}

/**
* Assert array is ordered.
*
* @return $this
*/
public function assertArrayOrdered($orderByKey)
{
$array = json_decode($this->response->getContent(), true);

$this->assertTrue(is_array($array), 'Expected response is json array for order comparison');

$ordered = true;
$prevVal = null;
foreach ($array as $k => $v) {
// First item, nothing to compare to so set and bail
if (empty($prevVal)) {
$prevVal = $v[$orderByKey];
continue;
}

// Compare current item to previous item
if ($v[$orderByKey] < $prevVal) {
$ordered = false;
break;
}

// Set previous item for the next comparison
$prevVal = $v[$orderByKey];
}

$this->assertTrue($ordered, 'Expected json response ordered by '.$orderByKey);

return $this;
}
}
12 changes: 12 additions & 0 deletions tests/integration/EntityTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Mockery;
use Rhumsaa\Uuid\Uuid;
use Spira\Core\Model\Model\Localization;
use Spira\Core\Model\Test\OrderedTestEntity;
use Spira\Core\Model\Test\SecondTestEntity;
use Spira\Core\Model\Test\TestEntity;
use Spira\Core\tests\Extensions\ElasticSearchIndexerTrait;
Expand Down Expand Up @@ -130,6 +131,17 @@ public function testGetAll()
$this->assertJsonMultipleEntries();
}

public function testGetAllDefaultOrdered()
{
$entity = $this->getFactory(OrderedTestEntity::class)->count(10)->create();
$this->getJson('/test/ordered-entities');
$this->assertArrayOrdered('varchar');
$this->assertResponseOk();
$this->shouldReturnJson();
$this->assertJsonArray();
$this->assertJsonMultipleEntries();
}

public function testGetAllWithNested()
{
$this->getFactory(TestEntity::class)->count(10)->create();
Expand Down
46 changes: 46 additions & 0 deletions tests/integration/OrderedEntityTestController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
<?php

/*
* This file is part of the Spira framework.
*
* @link https://github.com/spira/spira
*
* For the full copyright and license information, please view the LICENSE file that was distributed with this source code.
*/

namespace Spira\Core\tests\integration;

use Illuminate\Http\Request;
use Spira\Core\Controllers\EntityController;
use Spira\Core\Controllers\LocalizableTrait;
use Spira\Core\Model\Test\OrderedTestEntity;
use Spira\Core\Responder\Transformers\EloquentModelTransformer;

class OrderedEntityTestController extends EntityController
{
use LocalizableTrait;

protected $permissionsEnabled = false;

protected $defaultRole = 'user';

public function __construct(OrderedTestEntity $model, EloquentModelTransformer $transformer)
{
parent::__construct($model, $transformer);
}

/**
* Get ordered entities.
*
* @param Request $request
* @return ApiResponse
*/
public function getOrdered()
{
$collection = $this->getAllEntities();

return $this->getResponse()
->transformer($this->getTransformer())
->collection($collection);
}
}
1 change: 1 addition & 0 deletions tests/integration/test_routes.php
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
$app->get('test/internal-exception', 'TestController@internalException');
$app->get('test/fatal-error', 'TestController@fatalError');
$app->get('test/entities', 'TestController@getAll');
$app->get('test/ordered-entities', 'OrderedEntityTestController@getOrdered');
$app->get('test/entities/pages', 'TestController@getAllPaginated');
$app->get('test/entities/search', 'TestController@searchPaginated');
$app->get('test/entities_encoded/{id}', 'TestController@urlEncode');
Expand Down

0 comments on commit 1d31ab7

Please sign in to comment.