Skip to content

Commit b2d87d5

Browse files
committed
Retrieve page titles from external urls.
1 parent 38578bb commit b2d87d5

File tree

2 files changed

+51
-1
lines changed

2 files changed

+51
-1
lines changed

Diff for: src/Plugin/GraphQL/Fields/ExampleRoute.php

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
3+
namespace Drupal\graphql_example\Plugin\GraphQL\Fields;
4+
5+
use Drupal\Component\Utility\UrlHelper;
6+
use Drupal\Core\Url;
7+
use Youshido\GraphQL\Execution\ResolveInfo;
8+
use Drupal\graphql_core\Plugin\GraphQL\Fields\Route;
9+
10+
/**
11+
* Retrieve a url object based on an internal path or external url.
12+
*
13+
* @GraphQLField(
14+
* id = "example_url_route",
15+
* name = "route",
16+
* type = "Url",
17+
* nullable = true,
18+
* arguments = {
19+
* "path" = "String"
20+
* },
21+
* weight = 1
22+
* )
23+
*/
24+
class ExampleRoute extends Route {
25+
26+
/**
27+
* {@inheritdoc}
28+
*/
29+
public function resolveValues($value, array $args, ResolveInfo $info) {
30+
if (UrlHelper::isExternal($args['path'])) {
31+
yield Url::fromUri($args['path']);
32+
}
33+
else {
34+
foreach (parent::resolveValues($value, $args, $info) as $item) {
35+
yield $item;
36+
}
37+
}
38+
}
39+
40+
}

Diff for: src/Plugin/GraphQL/Fields/PageTitle.php

+11-1
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,20 @@ class PageTitle extends FieldPluginBase {
2828
*/
2929
protected function resolveValues($value, array $args, ResolveInfo $info) {
3030
if ($value instanceof Url) {
31-
if ($route = \Drupal::service('router.route_provider')->getRouteByName($value->getRouteName())) {
31+
if ($value->isRouted() && $route = \Drupal::service('router.route_provider')->getRouteByName($value->getRouteName())) {
3232
$request = Request::create($value->toString());
3333
yield \Drupal::service('title_resolver')->getTitle($request, $route);
3434
}
35+
else {
36+
$content = (string) \Drupal::httpClient()
37+
->get($value->toString())
38+
->getBody();
39+
$doc = new \DOMDocument();
40+
$doc->loadHTML($content);
41+
$xpath = new \DOMXPath($doc);
42+
$title = $xpath->query('//title')->item(0)->textContent;
43+
yield (string) $title;
44+
}
3545
}
3646
}
3747

0 commit comments

Comments
 (0)