<?php declare(strict_types=1);


namespace Newland\Toubiz\Sync\Neos\Utility;

use Doctrine\ORM\EntityManagerInterface;

class DatabaseUtility
{

    public static function withoutForeignKeyChecks(EntityManagerInterface $entityManager, callable $block): void
    {
        $isMysql = static::isMysql($entityManager);
        $onSql = $isMysql ? 'SET FOREIGN_KEY_CHECKS=1' : null;
        $offSql = $isMysql ? 'SET FOREIGN_KEY_CHECKS=0' : null;

        static::executeSql($entityManager, $offSql);
        try {
            $block();
        } catch (\Throwable $e) {
            static::executeSql($entityManager, $onSql);
            throw $e;
        }
        static::executeSql($entityManager, $onSql);
    }

    public static function isMysql(EntityManagerInterface $entityManager): bool
    {
        return $entityManager->getConnection()->getDatabasePlatform()->getName() === 'mysql';
    }

    public static function executeSql(EntityManagerInterface $entityManager, ?string $sql): void
    {
        if (!$sql) {
            return;
        }
        $entityManager->getConnection()->exec($sql);
    }
}
