Always return an array from selectValues method

This commit is contained in:
Marcus Moore 2023-12-21 16:38:51 -08:00
parent 4fc8e8dd61
commit 7f153b32e4
No known key found for this signature in database
3 changed files with 15 additions and 12 deletions

View file

@ -76,17 +76,17 @@ class ReportTemplate extends Model
return $this->options[$property] ?? null;
}
public function selectValues(string $property, string $model = null)
public function selectValues(string $property, string $model = null): iterable
{
if (!isset($this->options[$property])) {
return null;
return [];
}
// @todo: I think this was added to support the null object pattern
// @todo: Check if this is still needed and if so, add a test for it.
if ($this->options[$property] === [null]) {
return null;
}
// @todo: Check if this is still needed and if so, add a test for it (testParsingSelectValues()).
// if ($this->options[$property] === [null]) {
// return null;
// }
// If a model is provided then we should ensure we only return
// the ids of models that exist and are not deleted.

View file

@ -5,7 +5,7 @@
<div class="col-md-6">
<select class="js-data-ajax" data-endpoint="departments" data-placeholder="{{ trans('general.select_department') }}" name="{{ $fieldname }}" style="width: 100%" id="department_select" aria-label="{{ $fieldname }}"{{ (isset($multiple) && ($multiple=='true')) ? " multiple='multiple'" : '' }}>
@isset ($selected)
@if (!is_array($selected))
@if (!is_iterable($selected))
@php
$selected = [$selected];
@endphp

View file

@ -80,14 +80,17 @@ class ReportTemplateTest extends TestCase
{
$template = ReportTemplate::factory()->create([
'options' => [
'is_an_array' => ['2', '3', '4'],
'is_an_array_containing_null' => [null],
'an_array' => ['2', '3', '4'],
'an_empty_array'=> [],
'an_array_containing_null' => [null],
],
]);
$this->assertEquals(['2', '3', '4'], $template->selectValues('is_an_array'));
$this->assertEquals(null, $template->selectValues('non_existent_key'));
$this->assertNull($template->selectValues('is_an_array_containing_null'));
$this->assertEquals(['2', '3', '4'], $template->selectValues('an_array'));
$this->assertEquals([], $template->selectValues('an_empty_array'));
// @todo: should this actually be []?
$this->assertEquals([null], $template->selectValues('an_array_containing_null'));
$this->assertEquals([], $template->selectValues('non_existent_key'));
}
public function testSelectValueDoesNotIncludeDeletedOrNonExistentModels()