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.
18 * data_fetcher_plugin: http
20 * Accept: application/json
21 * User-Agent: Internet Explorer 6
22 * Authorization-Key: secret
23 * Arbitrary-Header: foobarbaz
28 * title = @Translation("HTTP")
31 class Http extends DataFetcherPluginBase implements ContainerFactoryPluginInterface {
36 * @var \GuzzleHttp\Client
38 protected $httpClient;
41 * The request headers.
45 protected $headers = [];
48 * The data retrieval client.
50 * @var \Drupal\migrate_plus\AuthenticationPluginInterface
52 protected $authenticationPlugin;
57 public function __construct(array $configuration, $plugin_id, $plugin_definition) {
58 parent::__construct($configuration, $plugin_id, $plugin_definition);
59 $this->httpClient = \Drupal::httpClient();
61 // Ensure there is a 'headers' key in the configuration.
62 $configuration += ['headers' => []];
63 $this->setRequestHeaders($configuration['headers']);
67 * Returns the initialized authentication plugin.
69 * @return \Drupal\migrate_plus\AuthenticationPluginInterface
70 * The authentication plugin.
72 public function getAuthenticationPlugin() {
73 if (!isset($this->authenticationPlugin)) {
74 $this->authenticationPlugin = \Drupal::service('plugin.manager.migrate_plus.authentication')->createInstance($this->configuration['authentication']['plugin'], $this->configuration['authentication']);
76 return $this->authenticationPlugin;
82 public function setRequestHeaders(array $headers) {
83 $this->headers = $headers;
89 public function getRequestHeaders() {
90 return !empty($this->headers) ? $this->headers : [];
96 public function getResponse($url) {
98 $options = ['headers' => $this->getRequestHeaders()];
99 if (!empty($this->configuration['authentication'])) {
100 $options = array_merge($options, $this->getAuthenticationPlugin()->getAuthenticationOptions());
102 $response = $this->httpClient->get($url, $options);
103 if (empty($response)) {
104 throw new MigrateException('No response at ' . $url . '.');
107 catch (RequestException $e) {
108 throw new MigrateException('Error message: ' . $e->getMessage() . ' at ' . $url . '.');
116 public function getResponseContent($url) {
117 $response = $this->getResponse($url);
118 return $response->getBody();