class DefaultFetcher

Same name and namespace in other branches
  1. 8.9.x core/modules/aggregator/src/Plugin/aggregator/fetcher/DefaultFetcher.php \Drupal\aggregator\Plugin\aggregator\fetcher\DefaultFetcher

Defines a default fetcher implementation.

Uses the http_client service to download the feed.

Plugin annotation


@AggregatorFetcher(
  id = "aggregator",
  title = @Translation("Default fetcher"),
  description = @Translation("Downloads data from a URL using Drupal's HTTP request handler.")
)

Hierarchy

Expanded class hierarchy of DefaultFetcher

1 file declares its use of DefaultFetcher
TestFetcher.php in core/modules/aggregator/tests/modules/aggregator_test/src/Plugin/aggregator/fetcher/TestFetcher.php

File

core/modules/aggregator/src/Plugin/aggregator/fetcher/DefaultFetcher.php, line 31

Namespace

Drupal\aggregator\Plugin\aggregator\fetcher
View source
class DefaultFetcher implements FetcherInterface, ContainerFactoryPluginInterface {
    use StringTranslationTrait;
    
    /**
     * The HTTP client to fetch the feed data with.
     *
     * @var \Drupal\Core\Http\ClientFactory
     */
    protected $httpClientFactory;
    
    /**
     * A logger instance.
     *
     * @var \Psr\Log\LoggerInterface
     */
    protected $logger;
    
    /**
     * The messenger.
     *
     * @var \Drupal\Core\Messenger\MessengerInterface
     */
    protected $messenger;
    
    /**
     * Constructs a DefaultFetcher object.
     *
     * @param \Drupal\Core\Http\ClientFactory $http_client_factory
     *   A Guzzle client object.
     * @param \Psr\Log\LoggerInterface $logger
     *   A logger instance.
     * @param \Drupal\Core\Messenger\MessengerInterface $messenger
     *   The messenger.
     */
    public function __construct(ClientFactory $http_client_factory, LoggerInterface $logger, MessengerInterface $messenger) {
        $this->httpClientFactory = $http_client_factory;
        $this->logger = $logger;
        $this->messenger = $messenger;
    }
    
    /**
     * {@inheritdoc}
     */
    public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
        return new static($container->get('http_client_factory'), $container->get('logger.factory')
            ->get('aggregator'), $container->get('messenger'));
    }
    
    /**
     * {@inheritdoc}
     */
    public function fetch(FeedInterface $feed) {
        $request = new Request('GET', $feed->getUrl());
        $feed->source_string = FALSE;
        // Generate conditional GET headers.
        if ($feed->getEtag()) {
            $request = $request->withAddedHeader('If-None-Match', $feed->getEtag());
        }
        if ($feed->getLastModified()) {
            $request = $request->withAddedHeader('If-Modified-Since', gmdate(DateTimePlus::RFC7231, $feed->getLastModified()));
        }
        try {
            
            /** @var \Psr\Http\Message\UriInterface $actual_uri */
            $actual_uri = NULL;
            $response = $this->httpClientFactory
                ->fromOptions([
                'allow_redirects' => [
                    'on_redirect' => function (RequestInterface $request, ResponseInterface $response, UriInterface $uri) use (&$actual_uri) {
                        $actual_uri = (string) $uri;
                    },
                ],
            ])
                ->send($request);
            // In case of a 304 Not Modified, there is no new content, so return
            // FALSE.
            if ($response->getStatusCode() == 304) {
                return FALSE;
            }
            $feed->source_string = (string) $response->getBody();
            if ($response->hasHeader('ETag')) {
                $feed->setEtag($response->getHeaderLine('ETag'));
            }
            if ($response->hasHeader('Last-Modified')) {
                $feed->setLastModified(strtotime($response->getHeaderLine('Last-Modified')));
            }
            $feed->http_headers = $response->getHeaders();
            // Update the feed URL in case of a 301 redirect.
            if ($actual_uri && $actual_uri !== $feed->getUrl()) {
                $feed->setUrl($actual_uri);
            }
            return TRUE;
        } catch (TransferException $e) {
            $this->logger
                ->warning('The feed from %site seems to be broken because of error "%error".', [
                '%site' => $feed->label(),
                '%error' => $e->getMessage(),
            ]);
            $this->messenger
                ->addWarning($this->t('The feed from %site seems to be broken because of error "%error".', [
                '%site' => $feed->label(),
                '%error' => $e->getMessage(),
            ]));
            return FALSE;
        }
    }

}

Members

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
DefaultFetcher::$httpClientFactory protected property The HTTP client to fetch the feed data with.
DefaultFetcher::$logger protected property A logger instance.
DefaultFetcher::$messenger protected property The messenger.
DefaultFetcher::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
DefaultFetcher::fetch public function Downloads feed data. Overrides FetcherInterface::fetch 1
DefaultFetcher::__construct public function Constructs a DefaultFetcher object.
StringTranslationTrait::$stringTranslation protected property The string translation service. 3
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.