3 namespace Drupal\migrate_plus\Plugin\migrate_plus\data_fetcher;
5 use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
6 use Drupal\migrate\MigrateException;
7 use Drupal\migrate_plus\DataFetcherPluginBase;
8 use GuzzleHttp\Exception\RequestException;
11 * Retrieve data over an HTTP connection for migration.
15 * title = @Translation("HTTP")
18 class Http extends DataFetcherPluginBase implements ContainerFactoryPluginInterface {
23 * @var \GuzzleHttp\Client
25 protected $httpClient;
28 * The request headers.
32 protected $headers = [];
35 * The data retrieval client.
37 * @var \Drupal\migrate_plus\AuthenticationPluginInterface
39 protected $authenticationPlugin;
44 public function __construct(array $configuration, $plugin_id, $plugin_definition) {
45 parent::__construct($configuration, $plugin_id, $plugin_definition);
46 $this->httpClient = \Drupal::httpClient();
50 * Returns the initialized authentication plugin.
52 * @return \Drupal\migrate_plus\AuthenticationPluginInterface
53 * The authentication plugin.
55 public function getAuthenticationPlugin() {
56 if (!isset($this->authenticationPlugin)) {
57 $this->authenticationPlugin = \Drupal::service('plugin.manager.migrate_plus.authentication')->createInstance($this->configuration['authentication']['plugin'], $this->configuration['authentication']);
59 return $this->authenticationPlugin;
65 public function setRequestHeaders(array $headers) {
66 $this->headers = $headers;
72 public function getRequestHeaders() {
73 return !empty($this->headers) ? $this->headers : [];
79 public function getResponse($url) {
81 $options = ['headers' => $this->getRequestHeaders()];
82 if (!empty($this->configuration['authentication'])) {
83 $options = array_merge($options, $this->getAuthenticationPlugin()->getAuthenticationOptions());
85 $response = $this->httpClient->get($url, $options);
86 if (empty($response)) {
87 throw new MigrateException('No response at ' . $url . '.');
90 catch (RequestException $e) {
91 throw new MigrateException('Error message: ' . $e->getMessage() . ' at ' . $url .'.');
99 public function getResponseContent($url) {
100 $response = $this->getResponse($url);
101 return $response->getBody();