symfony validate gpx file (variant xml)

1

I'm trying to filter the upload of a file through the form. The type of file I work with is .gpx (gps positions). Internally it is an xml file, but its mimetype is application / gpx + xml.

I have put the following in the validation.yml file about the route entity:

AppBundle\Entity\Route:
    properties:
        pointsFile:
            - NotBlank: ~
            - File:
                mimeTypes: "application/gpx, application/gpx+xml"
                disallowEmptyMessage: "Required"
                uploadErrorMessage: The file could not be uploaded

The property that represents the file is pointsFile .

When I upload a .gpx file, it shows me the error message:

El tipo mime del archivo no es válido ("application/xml"). Los tipos mime válidos son "application/gpx, application/gpx+xml".

The .gpx format is actually an xml. From what I see when uploading a file it identifies it as xml and throws me the error. What I want to achieve is to only upload correct .gpx files, and if it is another error file (both xml and not)

Does anyone know how to force this guy? Or should I make a constraint of my own to evaluate the content first ???

    
asked by Jakala 22.03.2017 в 11:13
source

1 answer

1

In the end I've done what @Muriano says by writing a Constraint, following the symfony manual. I leave my solution here, although I would prefer something more "symfony", as I said at the beginning, using the mimetype ...

The constraint:

<?php
namespace AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;

/**
 * @Annotation
 */
class ConstraintsGPXFile extends Constraint
{
    public $message = 'Invalid file content';
}

the validator:

<?php
namespace AppBundle\Validator\Constraints;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\DomCrawler\Crawler;

class ConstraintsGPXFileValidator extends ConstraintValidator
{
    public function validate($value, Constraint $constraint)
    {
        if(!empty($value)) {
            $crawler = new Crawler();
            $crawler->addXmlContent(file_get_contents($value));

            try {
                $crawler->filter('default|trkpt');
            } catch (\Exception $e) {
                $this->context->buildViolation($constraint->message)
                    ->addViolation();
            }
        }
    }
}

What I do is check the contents of the file that is uploaded. ! Empty is in case you are editing (it is not mandatory to upload the file). I use the domcrawler component of symfony, and if I do not find a node 'default | trkpt' I add an addViolation ().

    
answered by 23.03.2017 в 07:19