Commit 161de3f3 authored by Bertrand Gauthier's avatar Bertrand Gauthier
Browse files

Refactorisation des Helper et CodeGenerator.

Abandon de la table SYNCHRO_LOG et création de IMPORT_LOG(type,name,success,log,started_on,ended_on).
parent 32f73720
Loading
Loading
Loading
Loading
+19 −20
Changes for src/UnicaenDbImport/CodeGenerator/CodeGenerator.php: 19 added lines, 20 removed lines.
Original line number Diff line number Diff line
@@ -11,6 +11,7 @@ use UnicaenDbImport\CodeGenerator\Helper\SynchroLogHelper;
use UnicaenDbImport\CodeGenerator\Helper\TableValidationHelper;
use UnicaenDbImport\Domain\DestinationInterface;
use UnicaenDbImport\Domain\Operation;
use UnicaenDbImport\Domain\ResultInterface;
use UnicaenDbImport\Domain\SourceInterface;
use UnicaenDbImport\Domain\Synchro;

@@ -44,17 +45,15 @@ abstract class CodeGenerator implements CodeGeneratorInterface
    /**
     * AbstractCodeGenerator constructor.
     *
     * @param TableValidationHelper $tableValidationHelper
     * @param DiffViewHelper        $diffViewHelper
     * @param SynchroLogHelper      $synchroLogHelper
     * @param AbstractPlatform $platform
     */
    public function __construct(TableValidationHelper $tableValidationHelper,
                                DiffViewHelper $diffViewHelper,
                                SynchroLogHelper $synchroLogHelper)
    public function __construct(AbstractPlatform $platform)
    {
        $this->tableValidationHelper = $tableValidationHelper;
        $this->diffViewHelper = $diffViewHelper;
        $this->synchroLogHelper = $synchroLogHelper;
        $this->platform = $platform;

        //
        // NB: Les classes filles ont le responsabilité d'instancier les helpers concrets.
        //
    }

    /**
@@ -263,14 +262,12 @@ EOT;
     * @param array                $rows
     * @param SourceInterface      $source
     * @param DestinationInterface $destination
     * @param string               $hash
     * @return string
     */
    public function generateSQLForDestinationUpdateFromDiffViewRequestResult(
        array $rows,
        SourceInterface $source,
        DestinationInterface $destination,
        $hash)
        DestinationInterface $destination)
    {
        $destinationTable = $destination->getTable();
        $sourceCodeColumn = $source->getSourceCodeColumn();
@@ -310,16 +307,18 @@ EOT;
            }
        }

        // génération des INSERT à faire dans la table
        $sqls[] = $this->synchroLogHelper->generateSQLForInsertsFromDiffResults(
            $rows,
            $destinationTable,
            $sourceCodeColumn,
            $columns,
            $hash);

        $sql = empty($sqls) ? '' : implode(PHP_EOL, $sqls);

        return $sql;
    }

    /**
     * @param ResultInterface $result
     * @return string
     */
    public function generateSQLForInsertResultIntoSynchroLog(ResultInterface $result)
    {
        return $this->synchroLogHelper->generateSQLForInsertResultIntoSynchroLogTable($result);

    }
}
 No newline at end of file
+1 −3
Changes for src/UnicaenDbImport/CodeGenerator/CodeGeneratorInterface.php: 1 added line, 3 removed lines.
Original line number Diff line number Diff line
@@ -120,13 +120,11 @@ interface CodeGeneratorInterface
     * @param array                $rows
     * @param SourceInterface      $source
     * @param DestinationInterface $destination
     * @param string               $hash
     * @return string
     */
    public function generateSQLForDestinationUpdateFromDiffViewRequestResult(
        array $rows,
        SourceInterface $source,
        DestinationInterface $destination,
        $hash);
        DestinationInterface $destination);

}
 No newline at end of file
+13 −3
Changes for src/UnicaenDbImport/CodeGenerator/Helper.php: 13 added lines, 3 removed lines.
Original line number Diff line number Diff line
@@ -12,9 +12,19 @@ use Doctrine\DBAL\Platforms\AbstractPlatform;
abstract class Helper
{
    /**
     * @return AbstractPlatform
     * @var AbstractPlatform
     */
    abstract protected function getPlatform();
    protected $platform;

    /**
     * TableValidationHelper constructor.
     *
     * @param AbstractPlatform $platform
     */
    public function __construct(AbstractPlatform $platform)
    {
        $this->platform = $platform;
    }

    /**
     * @param string $argument
@@ -22,7 +32,7 @@ abstract class Helper
     */
    protected function getQuoteLiteralFunctionCallSQLSnippet($argument)
    {
        throw CodeGeneratorException::methodToImplement(__METHOD__, get_called_class(), $this->getPlatform());
        throw CodeGeneratorException::methodToImplement(__METHOD__, get_called_class(), $this->platform);
    }

    /**
+2 −2
Changes for src/UnicaenDbImport/CodeGenerator/Helper/DiffViewHelper.php: 2 added lines, 2 removed lines.
Original line number Diff line number Diff line
@@ -94,7 +94,7 @@ EOT;
    {
        $name = $this->generateViewName($destinationTable);

        return $this->getPlatform()->getDropViewSQL($name);
        return $this->platform->getDropViewSQL($name);
    }

    /**
@@ -196,7 +196,7 @@ EOT;
    {
        $diffViewName = $this->generateViewName($destinationTable);

        $now = $this->getPlatform()->getNowExpression();
        $now = $this->platform->getNowExpression();

        $cols = array_merge([$sourceCodeColumn], $columns);
        $sourceCols = array_map(function ($col) {
+51 −83
Changes for src/UnicaenDbImport/CodeGenerator/Helper/SynchroLogHelper.php: 51 added lines, 83 removed lines.
Original line number Diff line number Diff line
@@ -2,9 +2,12 @@

namespace UnicaenDbImport\CodeGenerator\Helper;

use BadMethodCallException;
use UnicaenApp\Exception\RuntimeException;
use UnicaenDbImport\CodeGenerator\Helper;
use UnicaenDbImport\Domain\Operation;
use UnicaenDbImport\Domain\ImportResult;
use UnicaenDbImport\Domain\ResultInterface;
use UnicaenDbImport\Domain\Synchro;
use UnicaenDbImport\Domain\SynchroResult;

/**
 * Génération de code SQL concernant la table de log de synchro.
@@ -18,98 +21,63 @@ abstract class SynchroLogHelper extends Helper
    /**
     * {@inheritDoc}
     */
    protected function getPlatform()
    public function generateSQLForSynchroLogTableCreation()
    {
        throw new BadMethodCallException("Méthode à implémenter pour fournir la pateforme de base de données concernée");
    }
        $tableName = Synchro::SYNCHRO_LOG_TABLE_NAME;

    /**
     * {@inheritDoc}
     */
    protected function getQuoteLiteralFunctionCallSQLSnippet($argument)
    {
        throw new BadMethodCallException("Méthode à implémenter pour la pateforme de base de données concernée");
    }
        $varchar = $this->platform->getVarcharTypeDeclarationSQL(['length' => 128]);
        $smallint = $this->platform->getSmallIntTypeDeclarationSQL([]);
        $text = $this->platform->getClobTypeDeclarationSQL([]);
        $datetime = $this->platform->getDateTimeTypeDeclarationSQL([]);

    /**
     * @return string
     */
    public function generateSQLForSynchroLogTableCreation()
    {
        throw new BadMethodCallException("Méthode à implémenter pour la pateforme de base de données concernée");
        $sql = <<<EOT
CREATE TABLE $tableName (
    type $varchar not null,
    name $varchar not null,
    success $smallint not null,
    log $text not null,
    started_on $datetime not null,
    ended_on   $datetime not null
);
EOT;
        return $sql;
    }

    /**
     * Génération des INSERT à faire dans la table de log de synchro à partir des résultats de la requête de diff.
     *
     * @param array  $rows
     * @param string $destinationTable
     * @param string $sourceCodeColumn
     * @param array  $columns
     * @param string $hash
     * @return string
     * {@inheritDoc}
     */
    public function generateSQLForInsertsFromDiffResults(
        array $rows,
        $destinationTable,
        $sourceCodeColumn,
        array $columns,
        $hash)
    public function generateSQLForInsertResultIntoSynchroLogTable(ResultInterface $result)
    {
        // préparation des données concernant les colonnes mises à jour
        $uColumnsPrefix = 'U_';
        $uColumns = array_map(function($col) use ($uColumnsPrefix) {
            return $uColumnsPrefix . $col;
        }, $columns);
        $uData = [];
        foreach ($rows as $row) {
            $operation = $row[strtoupper('operation')] ?? $row[strtolower('operation')];
            if (in_array($operation, [Operation::OPERATION_INSERT, Operation::OPERATION_UNDELETE, Operation::OPERATION_DELETE])) {
                $uData[] = [
                    'operation'   => $operation,
                    'table_name'  => $destinationTable,
                    'source_code' => $row[strtoupper($sourceCodeColumn)] ?? $row[strtolower($sourceCodeColumn)],
                    'field_name'  => NULL,
                    'to_value'    => NULL,
                    'from_value'  => NULL,
                    'import_hash' => $hash,
                ];
                continue;
            } else {
                // parcours des colonnes U_*
                foreach ($uColumns as $uCol) {
                    $uColValue = $row[strtoupper($uCol)] ?? $row[strtolower($uCol)] ?? 0;
                    if ($uColValue === 1) {
                        $col = substr($uCol, strlen($uColumnsPrefix)); // la colonne $col fait partie des colonnes à mettre à jour
                        $uData[] = [
                            'operation'   => $operation,
                            'table_name'  => $destinationTable,
                            'source_code' => $row[strtoupper($sourceCodeColumn)] ?? $row[strtolower($sourceCodeColumn)],
                            'field_name'  => $col,
                            'to_value'    => $row[strtoupper("S_$col")] ?? $row[strtolower("s_$col")],
                            'from_value'  => $row[strtoupper("D_$col")] ?? $row[strtolower("d_$col")],
                            'import_hash' => $hash,
                        ];
                    }
                }
            }
        }
        $tableName = Synchro::SYNCHRO_LOG_TABLE_NAME;

        // génération SQL
        $sqls = [];
        foreach ($uData as $row) {
            $sqls[] = $this->generateInsertRowSQLSnippet($row) . ';';
        switch (true) {
            case $result instanceof ImportResult:
                $type = 'import';
                $name = $result->getImport()->getName();
                break;
            case $result instanceof SynchroResult:
                $type = 'synchro';
                $name = $result->getSynchro()->getName();
                break;
            default:
                throw new RuntimeException("Type de résultat inattendu");
                break;
        }
        $success = $result->getException() ? 0 : 1;
        $startDate = $result->getStartDate()->format("Y-m-d H:i:s");
        $endDate = $result->getEndDate()->format("Y-m-d H:i:s");

        return implode(PHP_EOL, $sqls);
    }
        $sql = '';
        $sql .= "INSERT INTO $tableName (type, name, success, log, started_on, ended_on) ";
        $sql .= sprintf("VALUES (%s, %s, %s, %s, %s, %s)",
            $this->platform->quoteStringLiteral($type),
            $this->platform->quoteStringLiteral($name),
            $success,
            $this->platform->quoteStringLiteral($result->toString(true)),
            $this->platform->quoteStringLiteral($startDate),
            $this->platform->quoteStringLiteral($endDate)
        );

    /**
     * @param array $row
     * @return string
     */
    protected function generateInsertRowSQLSnippet(array $row)
    {
        throw new BadMethodCallException("Méthode à implémenter pour la pateforme de base de données concernée");
        return $sql;
    }
}
 No newline at end of file
Loading