Reputation: 3812
I'm writing an import script for our database (which is running on mySql) from CSV files. Since importing with doctrine entities is so slow and memory intensive, I'm opting for the option to write native queries to do the import task.
However, before the actual import, I need to validate the values in the csv file, and I wonder if there is any way to make use of the entity properties definition (already defined in the orm xml files) to do the validation. For example, if that field is already defined as a string with max 255 char in length then I can some how grab that definition and do the validation of the value in the csv file.
I hope it makes sense, please let me know if my question is not clear at any part.
Upvotes: 1
Views: 1183
Reputation: 7672
You could use the Symfony2 validator service to check data before importing it. However you would have to add the max length constraint as an assertion.
Example entity:
<?php
// src/Acme/YourBundle/Entity/Author.php
// ...
use Symfony\Component\Validator\Constraints as Assert;
class YourEntity
{
/**
* @Assert\Length(max=255)
*/
public $someString;
}
Your controller which handles the import:
<?php
// ...
use Acme\YourBundle\Entity\YourEntity;
public function indexAction()
{
//omitted: get your csv data first
// create a new instance of your entity
$entity = new YourEntity();
// populate your entity with data from your csv file
$entity->setSomeString($stringFromCsvFile);
// get the validator and validate your entity
$validator = $this->get('validator');
$errors = $validator->validate($entity);
if (count($errors) > 0) {
// there are errors! do something with them
} else {
// there are no errors, persist the entity
$em = $this->getDoctrine()->getManager();
$em->persist($entity);
$em->flush();
}
}
See http://symfony.com/doc/current/book/validation.html for more information.
Upvotes: 3