Skip to content

Commit

Permalink
Add tests for empty attributes cast to array
Browse files Browse the repository at this point in the history
  • Loading branch information
specialtactics committed Sep 4, 2019
1 parent cc2259e commit 2212551
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 8 deletions.
30 changes: 24 additions & 6 deletions test/tests/Fixtures/Models/ModelWithCasts.php
Original file line number Diff line number Diff line change
@@ -1,7 +1,25 @@
<?php
/**
* Created by PhpStorm.
* User: max
* Date: 4/09/19
* Time: 8:15 PM
*/

namespace Specialtactics\L5Api\Tests\Fixtures\Models;

use Specialtactics\L5Api\Models\RestfulModel;

class ModelWithCasts extends RestfulModel
{
/**
* @var string UUID key
*/
public $primaryKey = 'model_with_casts_id';

/**
* @var array The attributes that are mass assignable.
*/
protected $fillable = ['model_with_casts_id', 'array_attribute'];

/**
* @var array Casts
*/
protected $casts = [
'array_attribute' => 'array'
];
}
26 changes: 24 additions & 2 deletions test/tests/Unit/BaseTransformerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@

namespace Specialtactics\L5Api\Tests\Unit;

use Ramsey\Uuid\Uuid;
use Specialtactics\L5Api\Tests\AppTestCase;
use Specialtactics\L5Api\Tests\Fixtures\Models\ModelWithCasts;
use Specialtactics\L5Api\Tests\Fixtures\Models\ModelWithIdPK;
use Specialtactics\L5Api\Transformers\RestfulTransformer;

Expand All @@ -25,9 +27,29 @@ public function canTransformModelWithPKOfId()
$this->assertEquals($transformed['exampleAttribute'], 'abc123');
}


/**
* @todo: Test for the situation of an attribute casted as array being null, and being converted to string inadvertently on transformation
* Make sure that an array cast attribute is transformed correctly, in situations when it's blank
*
* @test
*/
public function nullArrayCastWillBeEmptyArray()
{
//
// Array attribute is null
$model = new ModelWithCasts(['model_with_casts_id' => Uuid::uuid4()->toString(), 'array_attribute' => null]);

$transformed = (new RestfulTransformer)->transform($model);

$this->assertArrayHasKey('arrayAttribute', $transformed);
$this->assertNull($transformed['arrayAttribute']);

//
// Array attribute is empty
$model = new ModelWithCasts(['model_with_casts_id' => Uuid::uuid4()->toString(), 'array_attribute' => []]);

$transformed = (new RestfulTransformer)->transform($model);

$this->assertArrayHasKey('arrayAttribute', $transformed);
$this->assertCount(0, $transformed['arrayAttribute']);
}
}

0 comments on commit 2212551

Please sign in to comment.