You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 satır
2.2KB

  1. <?php
  2. namespace common\components;
  3. use common\helpers\Password;
  4. use common\logic\Producer\Producer\Model\Producer;
  5. use GuzzleHttp\Client;
  6. use yii\base\ErrorException;
  7. class AlwaysdataClient
  8. {
  9. public function initRedirections(Producer $producer)
  10. {
  11. $this->createProducerSiteShortUrlRedirection($producer);
  12. $this->createProducerEmailRedirection($producer);
  13. }
  14. public function createProducerEmailRedirection(Producer $producer)
  15. {
  16. return $this->post('mailbox',[
  17. 'domain' => \Yii::$app->parameterBag->get('alwaysdataDomainOpendistribId'),
  18. 'name' => $producer->slug,
  19. 'password' => Password::generate(13),
  20. 'redirect_enabled' => true,
  21. 'redirect_to' => $producer->contact_email
  22. ]);
  23. }
  24. public function createProducerSiteShortUrlRedirection(Producer $producer)
  25. {
  26. return $this->post('site', [
  27. 'addresses' => [$producer->slug.'.opendistrib.net'],
  28. 'type' => 'redirect',
  29. 'url' => 'https://producteurs.opendistrib.net/'.$producer->slug,
  30. 'redirect_type' => 'PERMANENT',
  31. 'annotation' => 'Opendistrib / '.$producer->name
  32. ]);
  33. }
  34. private function post(string $resource, array $data)
  35. {
  36. $client = $this->getClient($resource);
  37. return $client->request('POST', '', [
  38. 'body' => json_encode($data)
  39. ]);
  40. }
  41. private function getClient(string $resource)
  42. {
  43. $this->checkConfiguration();
  44. return new Client([
  45. 'base_uri' => \Yii::$app->parameterBag->get('alwaysdataApiUrl').$resource.'/',
  46. 'auth' => [\Yii::$app->parameterBag->get('alwaysdataApiKey').' account='.\Yii::$app->parameterBag->get('alwaysdataAccount'), ''],
  47. ]);
  48. }
  49. private function checkConfiguration()
  50. {
  51. if(!\Yii::$app->parameterBag->has('alwaysdataApiUrl')
  52. || !\Yii::$app->parameterBag->has('alwaysdataAccount')
  53. || !\Yii::$app->parameterBag->has('alwaysdataApiKey')
  54. || !\Yii::$app->parameterBag->has('alwaysdataDomainOpendistribId')) {
  55. throw new ErrorException('Configuration API Alwaysdata absente ou incomplète dans params-local.php');
  56. }
  57. }
  58. }