Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions sources/AppBundle/Controller/Website/Talks/ShowAction.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@
use AppBundle\Event\Model\Repository\EventRepository;
use AppBundle\Event\Model\Repository\SpeakerRepository;
use AppBundle\Event\Model\Repository\TalkRepository;
use AppBundle\Event\Talk\VideoObjectJsonLd;
use AppBundle\Joindin\JoindinComments;
use AppBundle\Subtitles\Parser;
use AppBundle\Twig\ViewRenderer;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

final class ShowAction extends AbstractController
{
Expand All @@ -23,6 +25,7 @@ public function __construct(
private readonly SpeakerRepository $speakerRepository,
private readonly PlanningRepository $planningRepository,
private readonly EventRepository $eventRepository,
private readonly VideoObjectJsonLd $videoObjectJsonLd,
) {}

public function __invoke(int $id, string $slug): Response
Expand Down Expand Up @@ -50,6 +53,7 @@ public function __invoke(int $id, string $slug): Response
'speakers' => $speakers,
'comments' => $comments,
'transcript' => $parsedContent,
'video_object' => $this->videoObjectJsonLd->getData($talk, $planning->start, $parsedContent, $this->generateUrl('talks_show', ['id' => $talk->getId(), 'slug' => $talk->getSlug()], UrlGeneratorInterface::ABSOLUTE_URL)),
]);
}
}
74 changes: 74 additions & 0 deletions sources/AppBundle/Event/Talk/VideoObjectJsonLd.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
<?php

declare(strict_types=1);

namespace AppBundle\Event\Talk;

use AppBundle\Event\Model\Talk;

/**
* Données structurées schema.org VideoObject de la page d'un talk.
*
* @see https://developers.google.com/search/docs/appearance/structured-data/video
*/
final readonly class VideoObjectJsonLd
{
/**
* Options d'encodage à utiliser pour insérer le JSON dans un <script> :
* JSON_HEX_TAG encode < et >, si bien qu'un texte contenant « </script> » ne peut pas fermer la balise.
*/
public const int JSON_FLAGS = JSON_HEX_TAG | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_INVALID_UTF8_SUBSTITUTE;

/**
* @param array<array{text: mixed}> $transcript les phrases renvoyées par AppBundle\Subtitles\Parser
* @param string $url URL absolue de la page du talk
*
* @return array<string, string>|null null quand le talk n'a pas de vidéo ou pas de date de créneau
*/
public function getData(Talk $talk, ?\DateTimeInterface $start, array $transcript, string $url): ?array
{
if (!$talk->hasYoutubeId() || null === $start) {
return null;
}

$youtubeId = (string) $talk->getYoutubeId();

$data = [
'@context' => 'https://schema.org',
'@type' => 'VideoObject',
'name' => $talk->getTitle(),
];

// description est obligatoire pour Google : sans résumé, on reprend le titre.
$description = $this->toPlainText((string) $talk->getDescription());
$data['description'] = '' !== $description ? $description : $talk->getTitle();

$data += [
'thumbnailUrl' => sprintf('https://img.youtube.com/vi/%s/hqdefault.jpg', $youtubeId),
'uploadDate' => $start->format(\DateTimeInterface::ATOM),
'embedUrl' => sprintf('https://www.youtube.com/embed/%s', $youtubeId),
'url' => $url,
];

if (null !== $talk->getLanguageCode()) {
$data['inLanguage'] = $talk->getLanguageCode();
}

$transcriptText = $this->toPlainText(implode(' ', array_map(
static fn(array $cue): string => is_string($cue['text']) ? $cue['text'] : '',
$transcript,
)));
if ('' !== $transcriptText) {
$data['transcript'] = $transcriptText;
}

return $data;
}

private function toPlainText(string $html): string
{
$text = html_entity_decode(strip_tags($html), ENT_QUOTES | ENT_HTML5, 'UTF-8');

return trim((string) preg_replace('/\s+/u', ' ', $text));
}
}
15 changes: 3 additions & 12 deletions templates/site/talks/show.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -17,23 +17,14 @@
{% if talk.hasYoutubeId %}
<meta property="og:image" content="https://img.youtube.com/vi/{{ talk.getYoutubeId }}/hqdefault.jpg" />
<meta property="og:type" content="video.other" />
<script type="application/ld+json">
{{ {
'@context': 'https://schema.org',
'@type': 'VideoObject',
name: talk.title,
description: talk.description|striptags|trim,
thumbnailUrl: ['https://img.youtube.com/vi/' ~ talk.youtubeId ~ '/hqdefault.jpg'],
uploadDate: (event.dateEnd ?? event.dateStart)|date('c'),
embedUrl: 'https://www.youtube.com/embed/' ~ talk.youtubeId,
url: url('talks_show', {id: talk.id, slug: talk.slug}),
}|json_encode|raw }}
</script>
{% else %}
<meta property="og:type" content="article" />
{% endif %}
<meta property="og:description" content="{{ talk.description|striptags|raw }}" />
<meta property="og:site_name" content="AFUP" />
{% if video_object %}
<script type="application/ld+json">{{ video_object|json_encode(constant('AppBundle\\Event\\Talk\\VideoObjectJsonLd::JSON_FLAGS'))|raw }}</script>
{% endif %}
{% endblock %}

{% block content %}
Expand Down
66 changes: 66 additions & 0 deletions tests/behat/bootstrap/FeatureContext.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Behat\Behat\Context\Context;
use Behat\Behat\Hook\Scope\BeforeScenarioScope;
use Behat\Gherkin\Node\PyStringNode;
use Behat\Gherkin\Node\TableNode;
use Behat\Hook\AfterScenario;
use Behat\Hook\BeforeScenario;
use Behat\Mink\Driver\BrowserKitDriver;
Expand Down Expand Up @@ -351,4 +352,69 @@ public function openMenu(string $text): void

$node->click();
}

#[Then('the JSON-LD :type should have the following properties:')]
public function assertJsonLdHasProperties(string $type, TableNode $expectedProperties): void
{
$data = $this->findJsonLd($type);

if (null === $data) {
throw new ExpectationException(sprintf('No JSON-LD of type "%s" found', $type), $this->minkContext->getSession()->getDriver());
}

foreach ($expectedProperties->getRowsHash() as $property => $expectedValue) {
$actualValue = $data[$property] ?? null;
if (!is_scalar($actualValue) || (string) $actualValue !== $expectedValue) {
throw new ExpectationException(
sprintf('JSON-LD "%s" property "%s" is %s, "%s" expected', $type, $property, json_encode($actualValue, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), $expectedValue),
$this->minkContext->getSession()->getDriver(),
);
}
}
}

#[Then('the JSON-LD :type property :property should match :regex')]
public function assertJsonLdPropertyMatches(string $type, string $property, string $regex): void
{
$actualValue = $this->findJsonLd($type)[$property] ?? null;

if (!is_string($actualValue) || !preg_match($regex, $actualValue)) {
throw new ExpectationException(
sprintf('JSON-LD "%s" property "%s" is %s, it does not match "%s"', $type, $property, json_encode($actualValue, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), $regex),
$this->minkContext->getSession()->getDriver(),
);
}
}

#[Then('the response should not contain a JSON-LD :type')]
public function assertNoJsonLd(string $type): void
{
if (null !== $this->findJsonLd($type)) {
throw new ExpectationException(sprintf('A JSON-LD of type "%s" was found', $type), $this->minkContext->getSession()->getDriver());
}
}

/**
* Décode chaque <script type="application/ld+json"> de la page : un JSON invalide, ou deux JSON-LD
* du même type (par exemple un bloc en double après un merge), font échouer le step.
*
* @return array<string, mixed>|null
*/
private function findJsonLd(string $type): ?array
{
$scripts = $this->minkContext->getSession()->getPage()->findAll('css', 'script[type="application/ld+json"]');

$found = null;
foreach ($scripts as $script) {
$data = json_decode($script->getHtml(), true, flags: JSON_THROW_ON_ERROR);
if (is_array($data) && ($data['@type'] ?? null) === $type) {
if (null !== $found) {
throw new ExpectationException(sprintf('Several JSON-LD of type "%s" found', $type), $this->minkContext->getSession()->getDriver());
}
$found = $data;
}
}

return $found;
}
}
21 changes: 21 additions & 0 deletions tests/behat/features/PublicSite/Talks.feature
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,24 @@ Feature: Site Public - Talks
When I go to "/talks/?q=&hPP=7&idx=afup_talks&p=0&fR[event.title][0]=AFUP Day 2019 Lyon&fR[speakers.label][0]=Un Speaker"
Then I should see "Les vidéos de Un Speaker"
And the response should contain "<link rel=\"canonical\" href=\"https://apachephptest:80/talks/?fR%5Bspeakers.label%5D%5B0%5D=Un%20Speaker\" />"

@reloadDbWithTestData
Scenario: Données structurées VideoObject sur la page d'un talk avec vidéo
When I go to "/talks/1-jouons-tous-ensemble-a-un-petit-jeu"
Then the response status code should be 200
And the JSON-LD "VideoObject" should have the following properties:
| @context | https://schema.org |
| name | Jouons tous ensemble à un petit jeu |
| description | Hey ! Tu as participé au quiz du #SuperApéroPHP ? Tu te demandes : mais comment ont-ils fait ? Ne cherche pas plus loin, je te propose de nous retrouver pour un petit jeu et de découvrir ensemble l'envers du décor ! Au programme : une session interactive avec Laravel / Laravel Echo / Redis et Socket.IO. |
| thumbnailUrl | https://img.youtube.com/vi/MseSkWbhxV8/hqdefault.jpg |
| embedUrl | https://www.youtube.com/embed/MseSkWbhxV8 |
| inLanguage | fr |
| transcript | Merci. Merci. Bonjour, bonjour à toutes et à tous. |
And the JSON-LD "VideoObject" property "uploadDate" should match "/^\d{4}-\d{2}-\d{2}T09:00:00\+0[12]:00$/"
And the JSON-LD "VideoObject" property "url" should match "#^https://[^/]+/talks/1-jouons-tous-ensemble-a-un-petit-jeu$#"

@reloadDbWithTestData
Scenario: Pas de VideoObject sur la page d'un talk sans vidéo
When I go to "/talks/6-revolutionons-php"
Then the response status code should be 200
And the response should not contain a JSON-LD "VideoObject"
110 changes: 110 additions & 0 deletions tests/unit/AppBundle/Event/Talk/VideoObjectJsonLdTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
<?php

declare(strict_types=1);

namespace AppBundle\Tests\Event\Talk;

use AppBundle\Event\Model\Talk;
use AppBundle\Event\Talk\VideoObjectJsonLd;
use PHPUnit\Framework\TestCase;

final class VideoObjectJsonLdTest extends TestCase
{
private const string URL = 'https://afup.org/talks/42-rest-ou-graphql';

public function testGetData(): void
{
$talk = new Talk();
$talk->setTitle('REST ou GraphQL ?');
$talk->setAbstract("<p>GraphQL est une alternative aux architectures REST pour la r&eacute;alisation d&rsquo;API.</p>\n<p>Second paragraphe.</p>");
$talk->setYoutubeId('QhAToFl_Omo');
$talk->setLanguageCode(Talk::LANGUAGE_CODE_EN);

$start = new \DateTime('2019-05-16 09:30:00', new \DateTimeZone('Europe/Paris'));

$data = new VideoObjectJsonLd()->getData($talk, $start, [
['start' => 28.0, 'text' => 'Merci.'],
['start' => 31.0, 'text' => '<i>Bonjour</i> à toutes et à tous.'],
], self::URL);

self::assertSame([
'@context' => 'https://schema.org',
'@type' => 'VideoObject',
'name' => 'REST ou GraphQL ?',
'description' => 'GraphQL est une alternative aux architectures REST pour la réalisation d’API. Second paragraphe.',
'thumbnailUrl' => 'https://img.youtube.com/vi/QhAToFl_Omo/hqdefault.jpg',
'uploadDate' => '2019-05-16T09:30:00+02:00',
'embedUrl' => 'https://www.youtube.com/embed/QhAToFl_Omo',
'url' => self::URL,
'inLanguage' => 'en',
'transcript' => 'Merci. Bonjour à toutes et à tous.',
], $data);
}

public function testGetDataWithoutTranscript(): void
{
$talk = new Talk();
$talk->setTitle('Un talk');
$talk->setAbstract('Un résumé');
$talk->setYoutubeId('abc');

$data = new VideoObjectJsonLd()->getData($talk, new \DateTime(), [], self::URL);

self::assertIsArray($data);
self::assertArrayNotHasKey('transcript', $data);
self::assertSame('fr', $data['inLanguage']);
}

public function testGetDataWithoutVideo(): void
{
$talk = new Talk();
$talk->setTitle('Un talk');

self::assertNull(new VideoObjectJsonLd()->getData($talk, new \DateTime(), [], self::URL));

$talk->setYoutubeId('');
self::assertNull(new VideoObjectJsonLd()->getData($talk, new \DateTime(), [], self::URL));
}

public function testGetDataWithoutPlanningStart(): void
{
$talk = new Talk();
$talk->setTitle('Un talk');
$talk->setYoutubeId('abc');

self::assertNull(new VideoObjectJsonLd()->getData($talk, null, [], self::URL));
}

public function testEncodedDataCannotCloseTheScriptTag(): void
{
$talk = new Talk();
$talk->setTitle('Titre </script><script>alert(1)</script>');
$talk->setAbstract('Résumé &lt;/script&gt; échappé en HTML');
$talk->setYoutubeId('abc');

$data = new VideoObjectJsonLd()->getData($talk, new \DateTime(), [
['start' => 0.0, 'text' => 'Texte &lt;/script&gt;'],
], self::URL);
self::assertIsArray($data);

$json = json_encode($data, VideoObjectJsonLd::JSON_FLAGS);

self::assertIsString($json);
self::assertStringNotContainsStringIgnoringCase('</script', $json);
self::assertStringNotContainsString('<', $json);
self::assertSame($data, json_decode($json, true));
}

public function testDescriptionFallsBackToTheTitleWhenTheAbstractIsEmpty(): void
{
$talk = new Talk();
$talk->setTitle('Un talk sans résumé');
$talk->setAbstract('<p> </p>');
$talk->setYoutubeId('abc');

$data = new VideoObjectJsonLd()->getData($talk, new \DateTime(), [], self::URL);

self::assertIsArray($data);
self::assertSame('Un talk sans résumé', $data['description']);
}
}
Loading