Commit 1ee0dc01 authored by Bertrand Gauthier's avatar Bertrand Gauthier
Browse files

Import: poursuite de la séparation des responsabilités (SoC)!

parent ed3f8fbc
Loading
Loading
Loading
Loading
Loading
+1 −2
Changes for module/Application/src/Application/Entity/Db/Etablissement.php: 1 added line, 2 removed lines.
Original line number Diff line number Diff line
@@ -98,8 +98,7 @@ class Etablissement implements StructureConcreteInterface, HistoriqueAwareInterf
    }

    /**
     * @deprecated
     * @return mixed
     * @return string
     */
    public function getCode()
    {
+8 −1
Changes for module/Import/config/module.config.php: 8 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -3,6 +3,7 @@
use Doctrine\Common\Persistence\Mapping\Driver\MappingDriverChain;
use Doctrine\DBAL\Driver\OCI8\Driver as OCI8;
use Doctrine\ORM\Mapping\Driver\XmlDriver;
use Import\Service\CallService;
use Zend\Mvc\Router\Console\Simple;
use Zend\Mvc\Router\Http\Literal;
use Zend\Mvc\Router\Http\Segment;
@@ -58,7 +59,6 @@ return array(
            ],
        ],
    ],

    'console' => [
        'router' => [
            'routes' => [
@@ -84,6 +84,10 @@ return array(
                ],
            ],
        ],
        'view_manager' => [
            'display_not_found_reason' => true,
            'display_exceptions'       => true,
        ]
    ],
    'router' => [
        'routes' => [
@@ -173,6 +177,9 @@ return array(
        ],
    ],
    'service_manager' => [
        'invokables' => [
            CallService::class => CallService::class,
        ],
        'abstract_factories' => [
            'Zend\Cache\Service\StorageCacheAbstractServiceFactory',
            'Zend\Log\LoggerAbstractServiceFactory',
+10 −6
Changes for module/Import/src/Import/Controller/ImportController.php: 10 added lines, 6 removed lines.
Original line number Diff line number Diff line
@@ -69,8 +69,8 @@ class ImportController extends AbstractActionController

        $queryParams = $this->params()->fromQuery();

        $logs = [];
        $logs[] = $this->importService->import($service, $etablissement, $sourceCode, $queryParams);
        $this->importService->import($service, $etablissement, $sourceCode, $queryParams);
        $logs = $this->importService->getLogs();

        return new ViewModel([
            'service'       => $service,
@@ -89,9 +89,9 @@ class ImportController extends AbstractActionController
    public function importAllAction()
    {
        $etablissement = $this->params('etablissement');
        $logs = [];

        $logs[] = $this->importService->importAll($etablissement);
        $this->importService->importAll($etablissement);
        $logs = $this->importService->getLogs();

        return new ViewModel([
            'service'       => 'Tous',
@@ -138,17 +138,21 @@ class ImportController extends AbstractActionController
        $etablissement = $this->params('etablissement');
        $sourceCode = $this->params('source_code');

        $this->importService->setDebugLevel(1);
        $this->importService->import($service, $etablissement, $sourceCode);

        echo "Importation des données du service '$service' de l'établissement '$etablissement' réussie." . PHP_EOL;
        echo $this->importService->getFormattedLogs() . PHP_EOL;
        echo "Importation des données du service '$service' de l'établissement '$etablissement' effectuée." . PHP_EOL;
    }

    public function importAllConsoleAction()
    {
        $etablissement = $this->params('etablissement');

        $this->importService->setDebugLevel(1);
        $this->importService->importAll($etablissement);

        echo "Importation de toutes les données de l'établissement '$etablissement' réussie" . PHP_EOL;
        echo $this->importService->getFormattedLogs() . PHP_EOL;
        echo "Importation de toutes les données de l'établissement '$etablissement' effectuée." . PHP_EOL;
    }
}
+60
Changes for module/Import/src/Import/Exception/CallException.php: 60 added lines, 0 removed lines.
Original line number Diff line number Diff line
<?php

namespace Import\Exception;

use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ServerException;
use GuzzleHttp\Psr7;
use UnicaenApp\Exception\RuntimeException;
use Zend\Http\Response;

class CallException extends RuntimeException
{
    static public function error($uri, \Exception $previous = null)
    {
        return new self("Erreur inattendue rencontrée lors de l'envoi de la requête au WS (URI '$uri')", null, $previous);
    }

    static public function badConfig(\Exception $previous = null)
    {
        return new self("La config fournie est incorrecte.", null, $previous);

    }

    static public function unexpectedResponse($uri, Response $response)
    {
        return new self("Mauvaise réponse du WS (URI '$uri') ! Status : " . $response->getStatusCode());
    }

    static public function invalidJSON($uri)
    {
        return new self("Impossible de décoder la réponse JSON du WS (URI '$uri') : " . json_last_error_msg());
    }

    static public function clientError(ClientException $error)
    {
        return new self("Erreur ClientException rencontrée lors de l'envoi de la requête au WS", null, $error);
    }

    static public function serverError(ServerException $error)
    {
        $message = "Erreur distante rencontrée par le serveur du WS";
        $previous = null;
        if ($error->hasResponse()) {
            $previous = new RuntimeException($error->getResponse()->getBody());
        }

        return new self($message, null, $previous);
    }

    static public function networkError(RequestException $error)
    {
        $message = "Erreur réseau rencontrée lors de l'envoi de la requête au WS";
        if ($error->hasResponse()) {
            $message .= " : " . Psr7\str($error->getResponse());
        }

        return new self($message, null, $error);
    }
}
 No newline at end of file
+195
Changes for module/Import/src/Import/Service/CallService.php: 195 added lines, 0 removed lines.
Original line number Diff line number Diff line
<?php

namespace Import\Service;

use Assert\Assertion;
use Assert\AssertionFailedException;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\GuzzleException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Exception\ServerException;
use Import\Exception\CallException;
use Zend\Http\Response;

/**
 * Service dédié à l'envoi de requêtes au Web Service.
 */
class CallService
{
    /**
     * $config est fourni par la factory et permet l'acces à la config
     *
     * @var array $config
     */
    protected $config;

    /**
     * les quatres variables $url, $code, $user et $password sont des données de configuration pour l'acces au Web
     * Service
     *
     * @var string         $url      : le chemin d'acces au web service
     * @var string         $user     : l'identifiant pour l'authentification
     * @var string         $password : le mot de passe pour l'authentification
     * @var string|null    $proxy    : le champ proxy
     * @var boolean|string $verify   : le champ pour le mode https
     */
    protected $url;
    protected $user;
    protected $password;
    protected $proxy;
    protected $verify = true;

    protected $debugLevel = 0;

    /**
     * @var array
     */
    protected $logs = [];

    /**
     * @param array $config
     * @return self
     */
    public function setConfig(array $config)
    {
        $this->config = $config;

        return $this;
    }

    /**
     * @param int $debugLevel
     * @return self
     */
    public function setDebugLevel($debugLevel)
    {
        $this->debugLevel = $debugLevel;

        return $this;
    }

    /**
     * @return \stdClass
     */
    public function version()
    {
        $uri = 'version/current';

        $response = $this->sendRequest($uri);
        if ($response->getStatusCode() != 200) {
            throw CallException::unexpectedResponse($uri, $response);
        }

        $json = json_decode($response->getBody());
        if ($json === null) {
            // NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
            throw CallException::invalidJSON($uri);
        }

        return $json;
    }

    /**
     * @return array [DateTime, string] le log associé pour l'affichage
     */
    public function getLogs()
    {
        return $this->logs;
    }

    /**
     * @param string $uri
     * @return \stdClass
     */
    public function get($uri)
    {
        try {
            $response = $this->sendRequest($uri);
        } catch (\Exception $e) {
            throw CallException::error($uri, $e);
        }
        if ($response->getStatusCode() !== Response::STATUS_CODE_200) {
            throw CallException::unexpectedResponse($uri, $response);
        }

        $json = json_decode($response->getBody());
        if ($json === null) {
            // NULL is returned if the json cannot be decoded or if the encoded data is deeper than the recursion limit.
            throw CallException::invalidJSON($uri);
        }

        return $json;
    }

    /**
     * @throws \Assert\AssertionFailedException
     */
    private function loadConfig()
    {
        Assertion::keyIsset($this->config, 'url');
        Assertion::keyIsset($this->config, 'user');
        Assertion::keyIsset($this->config, 'password');

        $this->url = $this->config['url'];
        $this->user = $this->config['user'];
        $this->password = $this->config['password'];

        if (array_key_exists('proxy', $this->config)) {
            $this->proxy = $this->config['proxy'];
        }
        if (array_key_exists('verify', $this->config)) {
            $this->verify = $this->config['verify'];
        }
    }

    /**
     * Appel du Web Service d'import de données.
     *
     * @param string $uri : la "page" du Web Service à interroger
     * @return Response la réponse du Web Service
     *
     * RMQ le client est configuré en utilisant les propriétés du FetcherService
     */
    private function sendRequest($uri)
    {
        try {
            $this->loadConfig();
        } catch (AssertionFailedException $e) {
            throw CallException::badConfig($e);
        }

        $options = [
            'base_uri' => $this->url,
            'headers'  => [
                'Accept' => 'application/json',
            ],
            'auth'     => [$this->user, $this->password],
        ];

        if ($this->proxy !== null) {
            $options['proxy'] = $this->proxy;
        } else {
            $options['proxy'] = ['no' => 'localhost'];
        }

        if ($this->verify !== null) {
            $options['verify'] = $this->verify;
        }

        $client = new Client($options);
        try {
            $response = $client->request('GET', $uri);
        } catch (ClientException $e) {
            throw CallException::clientError($e);
        } catch (ServerException $e) {
            throw CallException::serverError($e);
        } catch (RequestException $e) {
            throw CallException::networkError($e);
        } catch (GuzzleException $e) {
            throw CallException::error($uri, $e);
        }

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