Commit 36f186e1 authored by Bertrand Gauthier's avatar Bertrand Gauthier
Browse files

Premier commit

parents
Loading
Loading
Loading
Loading

Module.php

0 → 100644
+75 −0
Original line number Diff line number Diff line
<?php

namespace UnicaenDbfakator;

use Laminas\Config\Factory as ConfigFactory;
use Laminas\Console\Adapter\AdapterInterface;
use Laminas\ModuleManager\Feature\ConsoleBannerProviderInterface;
use Laminas\ModuleManager\Feature\ConsoleUsageProviderInterface;
use Laminas\Mvc\ModuleRouteListener;
use Laminas\Mvc\MvcEvent;
use Laminas\Stdlib\Glob;

class Module implements ConsoleBannerProviderInterface, ConsoleUsageProviderInterface
{
    public function onBootstrap(MvcEvent $e)
    {
        $eventManager        = $e->getApplication()->getEventManager();
        $moduleRouteListener = new ModuleRouteListener();
        $moduleRouteListener->attach($eventManager);
    }

    public function getConfig()
    {
        $paths = array_merge(
            [__DIR__ . '/config/module.config.php'],
            Glob::glob(__DIR__ . '/config/others/{,*.}{config}.php', Glob::GLOB_BRACE)
        );

        return ConfigFactory::fromFiles($paths);
    }

    public function getAutoloaderConfig(): array
    {
        return array(
            'Laminas\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }

    /**
     * @inheritDoc
     */
    public function getConsoleBanner(AdapterInterface $console): ?string
    {
        return "UnicaenDbfakator";
    }

    /**
     * @inheritDoc
     */
    public function getConsoleUsage(AdapterInterface $console)
    {
        return [
            /**
             * @see ConsoleController::genererAction()
             */
            'unicaen-dbfakator generer' => "Génère le script d'anonymisation et le script de restauration.",

            /**
             * @see ConsoleController::anonymiserAction()
             */
            'unicaen-dbfakator anonymiser' => "Lance le script SQL d'anonymisation généré précédemment.",
            [],

            /**
             * @see ConsoleController::restaurerAction()
             */
            'unicaen-dbfakator restaurer' => "Lance le script SQL de restauration généré précédemment.",
            [],
        ];
    }
}
+167 −0
Original line number Diff line number Diff line
<?php

namespace UnicaenDbfakator;

use Laminas\Mvc\Console\Router\Simple;
use UnicaenAuth\Guard\PrivilegeController;
use UnicaenDbfakator\Controller\ConsoleController;
use UnicaenDbfakator\Controller\ConsoleControllerFactory;
use UnicaenDbfakator\Controller\IndexController;
use UnicaenDbfakator\Controller\IndexControllerFactory;
use UnicaenDbfakator\Service\DbfakatorService;
use UnicaenDbfakator\Service\DbfakatorServiceFactory;

return [
    'router' => [
        'routes' => [
            'unicaen-dbfakator' => [
                'type' => 'Literal',
                'options' => [
                    'route' => '/unicaen-dbfakator',
                    'defaults' => [
                        'controller' => IndexController::class,
                        'action' => 'index',
                    ],
                ],
                'may_terminate' => true,
                'child_routes' => [
                    'generer' => [
                        'type' => 'Literal',
                        'options' => [
                            'route' => '/generer',
                            'defaults' => [
                                'controller' => IndexController::class,
                                'action' => 'generer',
                            ],
                        ],
                    ],
                    'anonymiser' => [
                        'type' => 'Literal',
                        'options' => [
                            'route' => '/anonymiser',
                            'defaults' => [
                                'controller' => IndexController::class,
                                'action' => 'anonymiser',
                            ],
                        ],
                    ],
                    'restaurer' => [
                        'type' => 'Literal',
                        'options' => [
                            'route' => '/restaurer',
                            'defaults' => [
                                'controller' => IndexController::class,
                                'action' => 'restaurer',
                            ],
                        ],
                    ],
                ],
            ],
        ],
    ],
    'navigation' => [
        'default' => [
            'home' => [
                'pages' => [

                ],
            ],
        ],
    ],
    'console' => [
        'router' => [
            'routes' => [
                'generer' => [
                    'type' => Simple::class,
                    'options' => [
                        'route'    => 'unicaen-dbfakator generer',
                        'defaults' => [
                            /**
                             * @see ConsoleController::genererAction()
                             */
                            'controller' => ConsoleController::class,
                            'action'     => 'generer',
                        ],
                    ],
                ],
                'anonymiser' => [
                    'type' => Simple::class,
                    'options' => [
                        'route'    => 'unicaen-dbfakator anonymiser',
                        'defaults' => [
                            /**
                             * @see ConsoleController::anonymiserAction()
                             */
                            'controller' => ConsoleController::class,
                            'action'     => 'anonymiser',
                        ],
                    ],
                ],
                'restaurer' => [
                    'type' => Simple::class,
                    'options' => [
                        'route'    => 'unicaen-dbfakator restaurer',
                        'defaults' => [
                            /**
                             * @see ConsoleController::restaurerAction()
                             */
                            'controller' => ConsoleController::class,
                            'action'     => 'restaurer',
                        ],
                    ],
                ],
            ],
        ],
    ],
    'bjyauthorize' => [
        'guards' => [
            PrivilegeController::class => [
                [
                    /**
                     * @see ConsoleController::genererAction()
                     */
                    'controller' => ConsoleController::class,
                    'action' => [
                        'generer',
                        'anonymiser',
                        'restaurer',
                    ],
                    'role' => [],
                ],
                [
                    /**
                     * @see IndexController::indexAction()
                     */
                    'controller' => IndexController::class,
                    'action' => [
                        'index',
                        'generer',
                        'anonymiser',
                        'restaurer',
                    ],
                    'role' => [],
                ],
                [
                    'controller' => 'DoctrineModule\Controller\Cli',
                    'role' => [],
                ],
            ],
        ],
    ],
    'service_manager' => [
        'factories' => [
            DbfakatorService::class => DbfakatorServiceFactory::class,
        ],
    ],
    'controllers' => [
        'factories' => [
            IndexController::class => IndexControllerFactory::class,
            ConsoleController::class => ConsoleControllerFactory::class,
        ],
    ],
    'view_manager' => [
        'template_path_stack' => [
            __DIR__ . '/../view',
        ],
    ],
];
 No newline at end of file
+48 −0
Original line number Diff line number Diff line
<?php

namespace Application;

use Application\Entity\Db\Individu;
use Application\Entity\Db\Utilisateur;

return [
    'unicaen-db-fake' => [
        'entities' => [
            /**
             * Config par classe d'entité Doctrine.
             */
            Individu::class => [
                'mapping' => [
                    /**
                     * 'field' => 'xxxxx'            : pour appeler le formatter sans arguments `$faker->xxxxx()` (@see https://fakerphp.github.io/formatters)
                     * 'field' => ['xxxxx', 3, true] : pour appeler le formatter avec arguments `$faker->xxxxx(3, true)`
                     * 'field' => 'null'             : pour mettre le champ à NULL.
                     */
                    'nomUsuel' => 'lastName',
                    'nomPatronymique' => 'null',
                    'prenom1' => 'firstName',
                    'email' => 'safeEmail',
                    'leitmotiv' => ['words', 3, true], // càd `$faker->words(3, true)`
                ],
                /**
                 * Enregistrements à écarter, selon la valeur d'un attribut.
                 */
                'except' => [
                    /**
                     * 'field' => [valeur1, valeur2, ...]
                     */
                    'id' => [1234, 5678],
                ],
            ],
            Utilisateur::class => [
                'mapping' => [
                    'email' => 'safeEmail',
                    'displayName' => 'name',
                ],
                'except' => [
                    'username' => ['onelogin', 'anotherlogin'],
                ],
            ],
        ],
    ],
];
+82 −0
Original line number Diff line number Diff line
<?php

namespace UnicaenDbfakator\Controller;

use Exception;
use Laminas\Mvc\Console\Controller\AbstractConsoleController;
use UnicaenApp\Exception\RuntimeException;
use UnicaenDbfakator\Service\DbfakatorServiceAwareTrait;

class ConsoleController extends AbstractConsoleController
{
    use DbfakatorServiceAwareTrait;

    /**
     * @var string
     */
    protected $outputDir;

    public function genererAction()
    {
        $start = microtime(true);

        $this->console->writeLine("Generation des scripts SQL...");

        $anonymisationScriptPath = $this->dbfakatorService->getAnonymisationScriptPath();
        $restaurationScriptPath = $this->dbfakatorService->getRestaurationScriptPath();
        try {
            $gen = $this->dbfakatorService->generer($anonymisationScriptPath, $restaurationScriptPath);
            foreach ($gen as ['table' => $table, 'fields' => $fields, 'count' => $count]) {
                $this->console->writeLine(
                    sprintf("- Table %s (colonnes %s) : %d lignes", $table, implode(', ', $fields), $count)
                );
            }
        } catch (Exception $e) {
            throw new RuntimeException("Une erreur est survenue pendant la génération des scripts SQL.", null, $e);
        }

        $end = microtime(true);

        $this->console->writeLine("> Script d'anonymisation : " . realpath($anonymisationScriptPath));
        $this->console->writeLine("> Script de restauration : " . realpath($restaurationScriptPath));
        $this->console->writeLine(sprintf("Duree : %.2f s", $end - $start));
    }

    public function anonymiserAction()
    {
        $scriptPath = $this->dbfakatorService->getAnonymisationScriptPath();

        $this->console->writeLine("Lancement du script d'anonymisation '$scriptPath'...");

        $start = microtime(true);
        $this->lancerAction($scriptPath);
        $end = microtime(true);

        $this->console->writeLine(sprintf("Duree : %.2f s", $end - $start));
    }

    public function restaurerAction()
    {
        $scriptPath = $this->dbfakatorService->getRestaurationScriptPath();

        $this->console->writeLine("Lancement du script de restauration '$scriptPath'...");

        $start = microtime(true);
        $this->lancerAction($scriptPath);
        $end = microtime(true);

        $this->console->writeLine(sprintf("Duree : %.2f s", $end - $start));
    }

    protected function lancerAction(string $scriptPath)
    {
        try {
            $result = $this->dbfakatorService->lancer($scriptPath);
        } catch (Exception $e) {
            throw new RuntimeException("Une erreur est survenue lors du lancement du script '$scriptPath'.", null, $e);
        }

        $this->console->writeLine("> Résultat : " . ($result->isSuccess() ? 'Succès' : 'Échec'));
        $this->console->writeLine("> Log file : " . $result->getLogFilePath());
    }
}
 No newline at end of file
+26 −0
Original line number Diff line number Diff line
<?php

namespace UnicaenDbfakator\Controller;

use UnicaenDbfakator\Service\DbfakatorService;
use Interop\Container\ContainerInterface;

class ConsoleControllerFactory
{
    /**
     * @param \Interop\Container\ContainerInterface $container
     * @return \UnicaenDbfakator\Controller\ConsoleController
     * @throws \Psr\Container\ContainerExceptionInterface
     * @throws \Psr\Container\NotFoundExceptionInterface
     */
    public function __invoke(ContainerInterface $container): ConsoleController
    {
        /** @var \UnicaenDbfakator\Service\DbfakatorService $service */
        $dbFakeService = $container->get(DbfakatorService::class);

        $controller = new ConsoleController();
        $controller->setDbfakatorService($dbFakeService);

        return $controller;
    }
}
 No newline at end of file
Loading