Skip to content

Commit

Permalink
Merge pull request #73 from Propaganistas/patch-1
Browse files Browse the repository at this point in the history
Handle null values correctly in casts
  • Loading branch information
stevebauman authored Apr 6, 2023
2 parents f4ac052 + 8642905 commit 7b63762
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 4 deletions.
8 changes: 6 additions & 2 deletions src/Casts/PurifyHtmlOnGet.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,14 @@ class PurifyHtmlOnGet extends Caster implements CastsAttributes
* @param mixed $value
* @param array $attributes
*
* @return string|array
* @return string|array|null
*/
public function get($model, $key, $value, $attributes)
{
if (is_null($value)) {
return null;
}

return Purify::config($this->config)->clean($value);
}

Expand All @@ -30,7 +34,7 @@ public function get($model, $key, $value, $attributes)
* @param mixed $value
* @param array $attributes
*
* @return array|string
* @return array|string|null
*/
public function set($model, $key, $value, $attributes)
{
Expand Down
8 changes: 6 additions & 2 deletions src/Casts/PurifyHtmlOnSet.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ class PurifyHtmlOnSet extends Caster implements CastsAttributes
* @param mixed $value
* @param array $attributes
*
* @return string|array
* @return string|array|null
*/
public function get($model, string $key, $value, array $attributes)
{
Expand All @@ -30,10 +30,14 @@ public function get($model, string $key, $value, array $attributes)
* @param mixed $value
* @param array $attributes
*
* @return array|string
* @return array|string|null
*/
public function set($model, string $key, $value, array $attributes)
{
if (is_null($value)) {
return null;
}

return Purify::config($this->config)->clean($value);
}
}
16 changes: 16 additions & 0 deletions tests/CastsTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,14 @@ public function test_purifies_on_get_with_custom_config()
$this->assertEquals('<p>Test<span>bar</span></p>', $model->body);
}

public function test_returns_null_on_get_when_value_is_null()
{
$model = new PurifyingDefaultOnGetModel();
$model->body = null;

$this->assertNull($model->body);
}

public function test_purifies_on_set_with_default_config()
{
$this->app['config']->set('purify.configs.default', [
Expand All @@ -59,6 +67,14 @@ public function test_purifies_on_set_with_custom_config()

$this->assertEquals('<p>Test<span>bar</span></p>', $model->getAttributes()['body']);
}

public function test_sets_null_on_set_when_value_is_null()
{
$model = new PurifyingDefaultOnSetModel();
$model->body = null;

$this->assertNull($model->getAttributes()['body']);
}
}

class PurifyingDefaultOnGetModel extends Model
Expand Down

0 comments on commit 7b63762

Please sign in to comment.