From 9bd22d9f770e379f3434d26b85edb61b004ea464 Mon Sep 17 00:00:00 2001 From: shibafu Date: Wed, 13 Jun 2018 01:00:11 +0900 Subject: [PATCH] =?UTF-8?q?OGPResolver=E3=81=A7Twitter=20Cards=E3=81=AE?= =?UTF-8?q?=E8=A7=A3=E6=9E=90=E3=82=82=E8=A1=8C=E3=81=88=E3=82=8B=E3=82=88?= =?UTF-8?q?=E3=81=86=E3=81=AB=E3=81=97=E3=81=9F=20(#9)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/MetadataResolver/OGPResolver.php | 40 ++++++++++++---------------- 1 file changed, 17 insertions(+), 23 deletions(-) diff --git a/app/MetadataResolver/OGPResolver.php b/app/MetadataResolver/OGPResolver.php index 0475d7d..43d1543 100644 --- a/app/MetadataResolver/OGPResolver.php +++ b/app/MetadataResolver/OGPResolver.php @@ -23,30 +23,24 @@ class OGPResolver implements Resolver $metadata = new Metadata(); - $titleNode = $xpath->query('//meta[@*="og:title"]'); - foreach ($titleNode as $node) { - if (!empty($node->getAttribute('content'))) { - $metadata->title = $node->getAttribute('content'); - break; - } - } - - $descriptionNode = $xpath->query('//meta[@*="og:description"]'); - foreach ($descriptionNode as $node) { - if (!empty($node->getAttribute('content'))) { - $metadata->description = $node->getAttribute('content'); - break; - } - } - - $imageNode = $xpath->query('//meta[@*="og:image"]'); - foreach ($imageNode as $node) { - if (!empty($node->getAttribute('content'))) { - $metadata->image = $node->getAttribute('content'); - break; - } - } + $metadata->title = $this->findContent($xpath, '//meta[@*="og:title"]', '//meta[@*="twitter:title"]'); + $metadata->description = $this->findContent($xpath, '//meta[@*="og:description"]', '//meta[@*="twitter:description"]'); + $metadata->image = $this->findContent($xpath, '//meta[@*="og:image"]', '//meta[@*="twitter:image"]'); return $metadata; } + + private function findContent(\DOMXPath $xpath, string ...$expressions) + { + foreach ($expressions as $expression) { + $nodes = $xpath->query($expression); + foreach ($nodes as $node) { + $content = $node->getAttribute('content'); + if (!empty($content)) { + return $content; + } + } + } + return ''; + } } \ No newline at end of file