Cakephp-upload - validate unique filename

I have a FileStorageTable that uses cakephp-upload. Currently the code allows for uploading multiple files with the same name, but the files end up in the same location overwriting one another. I set up a unique constraint on the database, however this does not fire until the upload is already successful (thus it still overwrites the original file). I tried setting up build rules with a unique constraint like so:

    /**
     * @param \Cake\ORM\RulesChecker $rules The rules object to be modified.
     * @return \Cake\ORM\RulesChecker
     */
    public function buildRules(\Cake\Datasource\RulesChecker $rules): RulesChecker
    {
        $rules->add($rules->isUnique(
            ['foreign_key', 'model', 'filename'],
            'File with this name already exists.'
        ));

        return $rules;
    }

However, the filename field is the one associated with cakephp-upload - thus the field is currently recognised as a Laminas\Diactoros\UploadedFile object rather than a string and it throws an error. Any suggestions on how I can implement this validation? Thanks.

you can set a new file name before it save to your storage, can you provide more details?? a sample code can help

Not sure how much more context I can add here, but I’ll try!

So I am using cakephp-upload and I have the Model configured like so:

      $this->addBehavior('Josegonzalez/Upload.Upload', [
          'filename' => [
              'fields' => [
                  'dir' => 'filepath',
                  'ext' => 'extension',
                  'size' => 'filesize',
                  'type' => 'mime_type',
              ],
              'path' =>
                  '{field-value:client_name}{DS}{field-value:model}{DS}{field-value:foreign_key}{DS}',
              'filesystem' => [
                  'adapter' => $adapter,
                  'options' => [
                      'visibility' => 'private',
                  ],
              ],
              'writer' => 'App\File\Writer\AppWriter',
                'keepFilesOnDelete' => false,
            ],
        ]);

Files get uploaded through forms or API post requests, so the entity receives a field called filename which is the uploaded file. cakephp-upload then handles uploading the file, and ultimately converts the filename field to a string containing the filename.

What I want to do is to confirm that the foreign_key/model/filename combo is unique prior to attempting the upload.

Thinking about it now, I guess I could just do some custom logic in a lifecycle hook rather than relying on buildRules.