<?php
declare(strict_types=1);
namespace DoctrineMigrations;
use App\Entity\InsuranceCompany;
use Doctrine\DBAL\Schema\Schema;
use Doctrine\Migrations\AbstractMigration;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerAwareTrait;
final class Version20241030075504 extends AbstractMigration implements ContainerAwareInterface
{
use ContainerAwareTrait;
public function getDescription(): string
{
return 'Import all insurances from a CSV file';
}
/**
* @throws \Exception
*/
public function up(Schema $schema): void
{
$csvFile = __DIR__ . '/../var/insurances/list.csv';
if (!file_exists($csvFile) || !is_readable($csvFile)) {
throw new \Exception('File not found or not readable');
}
$em = $this->container->get('doctrine.orm.entity_manager');
if (($handle = fopen($csvFile, 'r')) !== false) {
$headers = fgetcsv($handle, 1000, ',');
$line = 1;
while (($data = fgetcsv($handle, 1000, ';')) !== false) {
$insurance = $em->getRepository(InsuranceCompany::class)->find($line);
$streetNumber = $this->extractStreetNumber($data[2]);
if ($insurance) {
$this->addSql('UPDATE insurance_company SET gmaps_address = ?, city = ?, zipCode = ?, streetNumber = ?, address = ?, name = ?, site = ?, bp = ?, phone = ?, email = ? WHERE id = ?', [
$data[7],
strtoupper($data[5]),
$data[4],
$streetNumber,
$data[2],
$data[0],
'https://',
$data[3],
'0102030405',
null,
$line,
]);
} else {
$datetime = new \DateTime();
$this->addSql('INSERT INTO insurance_company (id, is_deleted, createdAt, gmaps_address, city, zipCode, streetNumber, address, name, site, bp, phone, email) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [
$line,
0,
$datetime->format('Y-m-d H:i:s'),
$data[7],
strtoupper($data[5]),
$data[4],
$streetNumber,
$data[2],
$data[0],
'https://',
$data[3],
'0102030405',
null
]);
}
$line++;
}
fclose($handle);
}
}
public function down(Schema $schema): void
{
}
/**
* @param string $address
* @return int|null
*/
private function extractStreetNumber(string $address): ?int
{
$address = ltrim($address);
$pattern = '/^(\d+)/';
if (preg_match($pattern, $address, $matches)) {
return (int)$matches[1];
} else {
return null;
}
}
}