ConfigEntityProvider.php in oEmbed 8
File
src/Provider/ConfigEntityProvider.php
View source
<?php
namespace Drupal\oembed\Provider;
use Bangpound\oEmbed\Provider\ProviderInterface;
use Bangpound\oEmbed\Provider\StandardProvider;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\oembed\Entity\Provider;
use Psr\Http\Message\RequestInterface;
class ConfigEntityProvider implements ProviderInterface {
protected $providerStorage;
protected $providers = [];
public function __construct(EntityManagerInterface $entityManager) {
$this->providerStorage = $entityManager
->getStorage('oembed_provider');
}
public function request($url, array $params = array()) {
if (empty($this->providers)) {
$this
->loadProviders();
}
$schemes = self::getSchemes($this->providers);
$regexes = array_map(array(
'Drupal\\oembed\\Provider\\ConfigEntityProvider',
'schemeToRegex',
), $schemes);
$match = array_filter($regexes, function ($regex) use ($url) {
return (bool) preg_match($regex, $url);
});
$providerName = key($match);
$providerEntity = $this->providers[$providerName];
$provider = new StandardProvider($providerEntity
->getEndpoint(), $providerEntity
->getScheme(), array(), array(
'format' => 'json',
));
return $provider
->request($url, $params);
}
public function supports($url, array $params = array()) {
if (empty($this->providers)) {
$this
->loadProviders();
}
$schemes = array_merge(...array_values(self::getSchemes($this->providers)));
$regex = self::schemeToRegex($schemes);
return (bool) preg_match($regex, $url);
}
private function loadProviders() {
$this->providers = $this->providerStorage
->loadByProperties([
'status' => true,
]);
}
private static function getSchemes($providers) {
return array_map(function (Provider $provider) {
return $provider
->getScheme();
}, $providers);
}
private static function schemeToRegex($schemes, $capture_subpatterns = FALSE) {
$patterns = array_map(function ($scheme) use ($capture_subpatterns) {
return str_replace('\\*', $capture_subpatterns ? '(.*)' : '.*', preg_quote($scheme, '#'));
}, $schemes);
return '#' . implode('|', $patterns) . '#i';
}
}