Merge pull request #15198 from spencerrlongg/feature/add_trait_to_request

Add MayContainCustomFields Trait to Asset Update Request
This commit is contained in:
snipe 2024-08-13 14:12:52 +01:00 committed by GitHub
commit c163d6774f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 29 additions and 3 deletions

View file

@ -15,8 +15,7 @@ trait MayContainCustomFields
$asset_model = AssetModel::find($this->model_id);
}
if ($this->method() == 'PATCH' || $this->method() == 'PUT') {
// this is dependent on the asset update request PR
$asset_model = $this->asset;
$asset_model = $this->asset->model;
}
// collect the custom fields in the request
$validator->after(function ($validator) use ($asset_model) {
@ -25,7 +24,7 @@ trait MayContainCustomFields
});
// if there are custom fields, find the one's that don't exist on the model's fieldset and add an error to the validator's error bag
if (count($request_fields) > 0) {
$request_fields->diff($asset_model->fieldset->fields->pluck('db_column'))
$request_fields->diff($asset_model?->fieldset?->fields?->pluck('db_column'))
->each(function ($request_field_name) use ($request_fields, $validator) {
if (CustomField::where('db_column', $request_field_name)->exists()) {
$validator->errors()->add($request_field_name, trans('validation.custom.custom_field_not_found_on_model'));

View file

@ -2,12 +2,14 @@
namespace App\Http\Requests;
use App\Http\Requests\Traits\MayContainCustomFields;
use App\Models\Asset;
use Illuminate\Support\Facades\Gate;
use Illuminate\Validation\Rule;
class UpdateAssetRequest extends ImageUploadRequest
{
use MayContainCustomFields;
/**
* Determine if the user is authorized to make this request.
*

View file

@ -454,4 +454,29 @@ class UpdateAssetTest extends TestCase
])
->assertStatusMessageIs('success');
}
public function testCustomFieldCannotBeUpdatedIfNotOnCurrentAssetModel()
{
$this->markIncompleteIfMySQL('Custom Field Tests do not work in MySQL');
$customField = CustomField::factory()->create();
$customField2 = CustomField::factory()->create();
$asset = Asset::factory()->hasMultipleCustomFields([$customField])->create();
$user = User::factory()->editAssets()->create();
// successful
$this->actingAsForApi($user)->patchJson(route('api.assets.update', $asset->id), [
$customField->db_column_name() => 'test attribute',
])->assertStatusMessageIs('success');
// custom field exists, but not on this asset model
$this->actingAsForApi($user)->patchJson(route('api.assets.update', $asset->id), [
$customField2->db_column_name() => 'test attribute',
])->assertStatusMessageIs('error');
// custom field does not exist
$this->actingAsForApi($user)->patchJson(route('api.assets.update', $asset->id), [
'_snipeit_non_existent_custom_field_50' => 'test attribute',
])->assertStatusMessageIs('error');
}
}