<?php
namespace App\EventSubscriber;
use App\Entity\IASql;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityPersistedEvent;
use EasyCorp\Bundle\EasyAdminBundle\Event\AfterEntityUpdatedEvent;
use Doctrine\DBAL\Exception as DBALException;
use PDO;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class IASqlSubscriber implements EventSubscriberInterface
{
private $entityManager;
private ManagerRegistry $manager;
public function __construct(
ManagerRegistry $manager,
EntityManagerInterface $entityManager,
TokenStorageInterface $tokenStorage
) {
$this->manager = $manager;
$this->entityManager = $entityManager;
$this->tokenStorage = $tokenStorage;
}
public static function getSubscribedEvents()
{
return [
AfterEntityPersistedEvent::class => ['afterAdd'],
AfterEntityUpdatedEvent::class => ['afterUpdate'],
];
}
public function afterAdd(AfterEntityPersistedEvent $event)
{
$entity = $event->getEntityInstance();
if ($entity instanceof IASql) {
$keysSource = [];
$keysDestination = [];
$champsTable=[];
$champsTableD=[];
$sqlSource = strtolower($entity->getSourceSql());
if ($sqlSource != "") {
$sqlSource = $this->cleanTextSql($sqlSource);
$describe = $this->getTableColumnsFromQuery($sqlSource);
$tableNames = $this->getTableNamesFromQuery($sqlSource);
$resultats1 = $this->popup($sqlSource);
if ($resultats1 != null) {
foreach (array_slice($resultats1, 0, 10) as $resultat) {
$keysSource = array_keys($resultat);
}
foreach ($keysSource as $column) {
foreach ($tableNames as $tableName) {
foreach ($describe as $key => $desc) {
if ($key == $tableName) {
if (in_array($column, $desc)) {
$champsTable[] = $column . ' : ' . $tableName;
}
}
}
}
}
$entity->setIaSqlChamps(implode("\n", $champsTable));
$entity->setSourceChamps(implode("\n", $keysSource));
$this->entityManager->persist($entity);
}
} else {
$entity->setSourceChamps("");
$this->entityManager->persist($entity);
}
$sqlDestination = strtolower($entity->getDestinationSql());
if ($sqlDestination != "") {
$sqlDestination = $this->cleanTextSql($sqlDestination);
$describeD = $this->getTableColumnsFromQuery($sqlDestination);
$tableNamesD = $this->getTableNamesFromQuery($sqlDestination);
$resultats2 = $this->popup($sqlDestination);
if ($resultats2 != null) {
foreach (array_slice($resultats2, 0, 10) as $resultat) {
$keysDestination = array_keys($resultat);
}
foreach ($keysDestination as $column) {
foreach ($tableNamesD as $tableName) {
foreach ($describeD as $key => $desc) {
if ($key == $tableName) {
if (in_array($column, $desc)) {
$champsTableD[] = $column . ' : ' . $tableName;
}
}
}
}
}
$entity->setIaSqlChampsD(implode("\n", $champsTableD));
$entity->setDestinationChamps(implode("\n", $keysDestination));
$this->entityManager->persist($entity);
}
} else {
$entity->setDestinationChamps("");
$this->entityManager->persist($entity);
}
$this->entityManager->flush();
$count = 0;
$jeuxSql = $this->manager->getRepository(IASql::class)->findAll();
foreach ($jeuxSql as $jeuSql) {
if (strtolower($jeuSql->getLabel()) == strtolower($entity->getLabel())) {
$count++;
}
}
if ($count > 1) {
$this->entityManager->remove($entity);
$this->entityManager->flush();
}
}
}
public function afterUpdate(AfterEntityUpdatedEvent $event)
{
$entity = $event->getEntityInstance();
if ($entity instanceof IASql) {
$keysSource = [];
$keysDestination = [];
$sqlSource = strtolower($entity->getSourceSql());
$champsTable = [];
$champsTableD = [];
if ($sqlSource != "") {
$sqlSource = $this->cleanTextSql($sqlSource);
$describe = $this->getTableColumnsFromQuery($sqlSource);
$tableNames = $this->getTableNamesFromQuery($sqlSource);
$resultats1 = $this->popup($sqlSource);
if ($resultats1 != null) {
foreach (array_slice($resultats1, 0, 10) as $resultat) {
$keysSource = array_keys($resultat);
}
foreach ($keysSource as $column) {
foreach ($tableNames as $tableName) {
foreach ($describe as $key => $desc) {
if ($key == $tableName) {
if (in_array($column, $desc)) {
$champsTable[] = $column . ' : ' . $tableName;
}
}
}
}
}
$entity->setIaSqlChamps(implode("\n", $champsTable));
$entity->setSourceChamps(implode("\n", $keysSource));
$this->entityManager->persist($entity);
} else {
$entity->setSourceChamps("");
$this->entityManager->persist($entity);
}
} else {
$entity->setSourceChamps("");
$this->entityManager->persist($entity);
}
$sqlDestination = strtolower($entity->getDestinationSql());
if ($sqlDestination != "") {
$sqlDestination = $this->cleanTextSql($sqlDestination);
$describeD = $this->getTableColumnsFromQuery($sqlDestination);
$tableNamesD = $this->getTableNamesFromQuery($sqlDestination);
$resultats2 = $this->popup($sqlDestination);
if ($resultats2 != null) {
foreach (array_slice($resultats2, 0, 10) as $resultat) {
$keysDestination = array_keys($resultat);
}
foreach ($keysDestination as $column) {
foreach ($tableNamesD as $tableName) {
foreach ($describeD as $key => $desc) {
if ($key == $tableName) {
if (in_array($column, $desc)) {
$champsTableD[] = $column . ' : ' . $tableName;
}
}
}
}
}
$entity->setIaSqlChampsD(implode("\n", $champsTableD));
$entity->setDestinationChamps(implode("\n", $keysDestination));
$this->entityManager->persist($entity);
} else {
$entity->setDestinationChamps("");
$this->entityManager->persist($entity);
}
} else {
$entity->setDestinationChamps("");
$this->entityManager->persist($entity);
}
$this->entityManager->flush();
}
}
public function popup($reqSource)
{
try {
$entityManager = $this->manager->getManager();
if ($reqSource != "") {
$conn = $entityManager->getConnection();
$sql = $reqSource; //."WHERE projet_id = ".$projet->getId();
$stmt = $conn->prepare($sql);
$resultSet = $stmt->executeQuery();
return $resultSet->fetchAllAssociative();
} else {
return null;
}
} catch (DBALException $e) {
echo "<div class='alert alert-danger' role='alert'>Vous avez une erreur de syntaxe SQL !</p></div>";
}
}
function cleanTextSql($text)
{
$text = htmlspecialchars_decode($text);
$text = preg_replace('#<[^>]+>#', ' ', $text);
//$text = strip_tags($text);
$text = str_replace("’", '', $text);
$text = str_replace("`", '', $text);
$text = str_replace('/', 'slach', $text);
$text = str_replace(' ', '', $text);
//$text = str_replace(';', ' limit 10', $text);
$text = str_replace(';', '', $text);
$text = str_replace('< ', '<', $text);
$text = str_replace(' >', '>', $text);
$text = str_replace('»', 'mot', $text);
$text = str_replace('«', 'mot', $text);
$text = str_replace('#', '', $text);
$text = str_replace('œ', 'oe', $text);
$text = preg_replace('/\:/', 'mot', $text);
$text = str_replace('°', '', $text);
$text = str_replace(' – ', '', $text);
$utf8 = array(
'/[áàâãªä]/u' => 'a',
'/[ÁÀÂÃÄ]/u' => 'A',
'/[ÍÌÎÏ]/u' => 'I',
'/[íìîï]/u' => 'i',
'/[éèêë]/u' => 'e',
'/[ÉÈÊË]/u' => 'E',
'/[óòôõºö]/u' => 'o',
'/[ÓÒÔÕÖ]/u' => 'O',
'/[úùûü]/u' => 'u',
'/[ÚÙÛÜ]/u' => 'U',
'/ç/' => 'c',
'/Ç/' => 'C',
'/ñ/' => 'n',
'/Ñ/' => 'N',
//'/_/' => '-', // UTF-8 hyphen to "normal" hyphen
'/[’‘‹›‚]/u' => ' ', // Literally a single quote
'/[“”«»„]/u' => 'mot', // Double quote
'/ /' => ' ', // nonbreaking space (equiv. to 0x160)
);
return preg_replace(array_keys($utf8), array_values($utf8), $text);
}
// SELECT `article`.*, `article_contenu`.*
// FROM `article`
// LEFT JOIN `article_contenu` ON `article_contenu`.`article_id` = `article`.`id`;
// SELECT 'article.*' ,
// 'article_contenu.*'
// FROM article
// LEFT JOIN article_contenu ON 'article_contenu.article_id' = 'article.id';
function getTableNameFromQuery($query)
{
// Extract the table name from the FROM clause of the query
preg_match('/\bFROM\s+`?(\w+)`?\b/i', $query, $matches);
if (count($matches) > 1) {
return $matches[1];
}
return false;
}
function getTableNamesFromQuery($query)
{
try {
// $conn = $this->manager->getManager()->getConnection();
// $params = $conn->getParams();
// dd($params);
// Extract the table names from the FROM clause and the JOIN clause of the query
preg_match_all('/\bFROM\s+`?(\w+)`?\b/i', $query, $matches1);
preg_match_all('/\bJOIN\s+`?(\w+)`?\b/i', $query, $matches2);
$tableNames = array_merge($matches1[1], $matches2[1]);
$tableNames = array_unique($tableNames);
return $tableNames;
} catch (DBALException $e) {
echo "<div class='alert alert-danger' role='alert'>Vous avez une erreur de syntaxe SQL !</p></div>";
}
}
function getTableColumnsFromQuery($query)
{
try {
// Extract the table names from the FROM clause and the JOIN clause of the query
preg_match_all('/\bFROM\s+`?(\w+)`?\b/i', $query, $matches1);
preg_match_all('/\bJOIN\s+`?(\w+)`?\b/i', $query, $matches2);
$tableNames = array_merge($matches1[1], $matches2[1]);
$tableNames = array_unique($tableNames);
$conn = $this->manager->getManager()->getConnection();
$tableColumns = array();
foreach ($tableNames as $tableName) {
$stmt = $conn->prepare("DESCRIBE $tableName");
$stmt->execute();
$tableColumns[$tableName] = $stmt->executeQuery()->fetchAll(PDO::FETCH_COLUMN);
}
return $tableColumns;
} catch (DBALException $e) {
echo "<div class='alert alert-danger' role='alert'>Vous avez une erreur de syntaxe SQL !</p></div>";
}
}
// public function afterUpdate(AfterEntityUpdatedEvent $event)
// {
// $entity = $event->getEntityInstance();
// if ($entity instanceof IASql) {
// $champsSource = "";
// $champsDestination = "";
// $sqlSource = strtolower($entity->getSourceSql());
// $champs = trim(substr($sqlSource, 6, strpos($sqlSource, "from") - strlen("from") - 2));
// if($champs == "*"){
// $table_name=trim($this->get_string_between(trim($sqlSource),'from','where'));
// $columnNames=$this->getColumnName($table_name);
// foreach($columnNames as $columnName){
// $champs=(implode(",",$columnName));
// }
// }
// //dd($champs);
// $champs = explode(",", $champs);
// $resultats1 = $this->popupSource($sqlSource);
// if ($resultats1 != null) {
// foreach ($resultats1 as $resultat) {
// foreach ($champs as $champ) {
// if (array_key_exists(trim($champ), $resultat)) {
// foreach ($resultat as $value) {
// $champsSource = $champsSource . $value . ",";
// }
// }
// }
// }
// $entity->setSourceChamps($champsSource);
// } else {
// $entity->setSourceChamps("");
// }
// /*********Destination */
// $sqlDestination = strtolower($entity->getDestinationSql());
// $champs2 = trim(substr($sqlDestination, 6, strpos($sqlDestination, "from") - strlen("from") - 2));
// if($champs2 == "*"){
// $table_name=trim($this->get_string_between(trim( $sqlDestination),'from','where'));
// $columnNames=$this->getColumnName($table_name);
// foreach($columnNames as $columnName){
// $champs2=(implode(",",$columnName));
// }
// }
// $champs2 = explode(",", $champs2);
// $resultats2 = $this->popupDestination($sqlDestination);
// if ($resultats2 != null) {
// foreach ($resultats2 as $resultat) {
// foreach ($champs2 as $champ) {
// if (array_key_exists(trim($champ), $resultat)) {
// foreach ($resultat as $value) {
// $champsDestination = $champsDestination . $value . ",";
// }
// }
// }
// }
// $entity->setDestinationChamps($champsDestination);;
// } else {
// $entity->setDestinationChamps("");
// }
// $this->entityManager->persist($entity);
// $this->entityManager->flush();
// }
// }
}