|
- <?php
-
- namespace common\components;
-
- use common\helpers\Password;
- use common\logic\Producer\Producer\Model\Producer;
- use GuzzleHttp\Client;
- use yii\base\ErrorException;
-
- class AlwaysdataClient
- {
- public function initRedirections(Producer $producer)
- {
- $this->createProducerSiteShortUrlRedirection($producer);
- $this->createProducerEmailRedirection($producer);
- }
-
- public function createProducerEmailRedirection(Producer $producer)
- {
- return $this->post('mailbox',[
- 'domain' => \Yii::$app->parameterBag->get('alwaysdataDomainOpendistribId'),
- 'name' => $producer->slug,
- 'password' => Password::generate(13),
- 'redirect_enabled' => true,
- 'redirect_to' => $producer->contact_email
- ]);
- }
-
- public function createProducerSiteShortUrlRedirection(Producer $producer)
- {
- return $this->post('site', [
- 'addresses' => [$producer->slug.'.opendistrib.net'],
- 'type' => 'redirect',
- 'url' => 'https://producteurs.opendistrib.net/'.$producer->slug,
- 'redirect_type' => 'PERMANENT',
- 'annotation' => 'Opendistrib / '.$producer->name
- ]);
- }
-
- private function post(string $resource, array $data)
- {
- $client = $this->getClient($resource);
-
- return $client->request('POST', '', [
- 'body' => json_encode($data)
- ]);
- }
-
- private function getClient(string $resource)
- {
- $this->checkConfiguration();
-
- return new Client([
- 'base_uri' => \Yii::$app->parameterBag->get('alwaysdataApiUrl').$resource.'/',
- 'auth' => [\Yii::$app->parameterBag->get('alwaysdataApiKey').' account='.\Yii::$app->parameterBag->get('alwaysdataAccount'), ''],
- ]);
- }
-
- private function checkConfiguration()
- {
- if(!\Yii::$app->parameterBag->has('alwaysdataApiUrl')
- || !\Yii::$app->parameterBag->has('alwaysdataAccount')
- || !\Yii::$app->parameterBag->has('alwaysdataApiKey')
- || !\Yii::$app->parameterBag->has('alwaysdataDomainOpendistribId')) {
-
- throw new ErrorException('Configuration API Alwaysdata absente ou incomplète dans params-local.php');
- }
- }
- }
|