Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2: how to validate UploadedFile without form?

I need to upload download file from URL to my server and persist it with Uploadable (DoctrineExtensions). Almost everything works fine, my approach is:

  1. Download file with curl to temp folder on my server
  2. Create UploadedFile method and fill it with property values
  3. Insert it to uploadable entity Media
  4. Do validation
  5. Persist and flush

The simplified code:

// ... download file with curl

// Create UploadedFile object
$fileInfo = new File($tpath);
$file = new UploadedFile($tpath, basename($url), $fileInfo->getMimeType(), $fileInfo->getSize(), null);

// Insert file to Media entity
$media = new Media();
$media = $media->setFile($file);
$uploadableManager->markEntityToUpload($media, $file);

// Validate file (by annotations in entity)
$errors = $validator->validate($media);

// If no errors, persist and flush
if(empty($errors)) {
    $em->persist($this->parentEntity);
    $em->flush();
}

If I skip the validation, everything is OK. File is succesfully moved to right path (configured by Uploadable extension in config.yml) and persisted to database. But validation with manualy created UploadedFile return this error:

The file could not be uploaded.

I can disable Validator for upload from URL and validate file with custom method, but doing it with Symfony Validator object would seem to be a cleaner solution to me.

Is there any way to make it work?

like image 271
Tomas S. Avatar asked Oct 20 '22 05:10

Tomas S.


1 Answers

IN the symfony validation component, the constraint UploadedFile internally uses this functin http://php.net/manual/es/function.is-uploaded-file.php

you can see it here https://github.com/symfony/HttpFoundation/blob/master/File/UploadedFile.php#L213

/**
 * Returns whether the file was uploaded successfully.
 *
 * @return bool True if the file has been uploaded with HTTP and no error occurred.
 *
 * @api
 */
public function isValid()
{
    $isOk = $this->error === UPLOAD_ERR_OK;
    return $this->test ? $isOk : $isOk && is_uploaded_file($this->getPathname());
}

You will have to create your own Downloadvalidator (yes, you are actually DOWNLOADING the file with curl)

like image 114
Javier Neyra Avatar answered Dec 25 '22 10:12

Javier Neyra