src/Twig/JsonLdExtension.php line 257

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. /*
  4.  * Copyright (C) Office National de Publication et de Communication - All Rights Reserved
  5.  *
  6.  * Unauthorized copying of this file, via any medium is strictly prohibited by law
  7.  * This file is proprietary and confidential
  8.  */
  9. namespace App\Twig;
  10. use stdClass;
  11. use App\Entity\Video;
  12. use Twig\Environment;
  13. use Twig\TwigFunction;
  14. use App\Entity\Actualite;
  15. use App\Service\PathBuilder;
  16. use App\Entity\Etablissement;
  17. use App\Entity\DiaporamaPhoto;
  18. use App\Entity\DonneeComplementaire;
  19. use Symfony\Component\Asset\Package;
  20. use Twig\Extension\AbstractExtension;
  21. use App\Twig\DonneeComplementaireExtension;
  22. use Symfony\Component\Routing\RouterInterface;
  23. use \Liip\ImagineBundle\Imagine\Cache\CacheManager;
  24. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  25. use Symfony\Component\Asset\VersionStrategy\EmptyVersionStrategy;
  26. final class JsonLdExtension extends AbstractExtension
  27. {
  28.     /** @var RouterInterface */
  29.     private $router;
  30.     /** @var PathBuilder */
  31.     private $pathBuilder;
  32.     /** @var CacheManager */
  33.     private $imagineCacheManager;
  34.     /** @var Environment */
  35.     private $twig;
  36.     public function __construct(RouterInterface $routerPathBuilder $pathBuilderCacheManager $imagineCacheManagerEnvironment $twig)
  37.     {
  38.         $this->router $router;
  39.         $this->pathBuilder $pathBuilder;
  40.         $this->imagineCacheManager $imagineCacheManager;
  41.         $this->twig $twig;
  42.     }
  43.     public function getFunctions()
  44.     {
  45.         return [
  46.             new TwigFunction('jsonLdActualite', [$this'actualite']),
  47.             new TwigFunction('jsonLdEtablissement', [$this'etablissement']),
  48.             new TwigFunction('jsonLdDiplomes', [$this'diplomes']),
  49.             new TwigFunction('jsonLdOnpc', [$this'onpc']),
  50.             new TwigFunction('jsonLdWebsite', [$this'website']),
  51.             new TwigFunction('jsonLdVideo', [$this'video']),
  52.             new TwigFunction('jsonLdDiapo', [$this'diapo']),
  53.             new TwigFunction('jsonLdFaq', [$this'generateFaqJsonLd']),
  54.         ];
  55.     }
  56.     public function actualite(Actualite $actualite): stdClass
  57.     {
  58.         $etablissement $actualite->getEtablissement();
  59.         $logoUrl $this->imagineCacheManager->getBrowserPath('/images/jouve/logo-fiche/' $etablissement->getLogoFiche(), 'etab_fiche_logo');
  60.         $imageUrl $actualite->getUrlImage();
  61.         return (object) array_filter([
  62.             '@context' => 'https://schema.org/',
  63.             '@type' => 'NewsArticle',
  64.             // 'url' => $this->pathBuilder->buildFiche($etablissement),
  65.             // 'author' => $etablissement->getDenomination(),
  66.             'headline' => $actualite->getTitre(),
  67.             'datePublished' => $actualite->getDatePublication()->format('c'),
  68.             'dateModified' => $actualite->getDateActualisation()->format('c'),
  69.             'description' => $actualite->getResume(),
  70.             'publisher' => $etablissement ? (object) array_filter([
  71.                 '@type' => 'Organization',
  72.                 'name' => $etablissement->getDenomination(),
  73.                 'logo' => $logoUrl ? (object) [
  74.                         '@type' => 'ImageObject',
  75.                         'url' => $logoUrl,
  76.                     ] : null,
  77.                 'url' => $etablissement->getUrl(),
  78.             ]) : null,
  79.             'image' => $imageUrl ? (object) [
  80.                     '@type' => 'ImageObject',
  81.                     'url' => $imageUrl,
  82.                 ] : null,
  83.             ]);
  84.     }
  85.     public function etablissement(Etablissement $etablissement$noLogoPath): stdClass
  86.     {
  87.         $ville $etablissement->getVille();
  88.         return (object) [
  89.             '@context' => 'http://schema.org/',
  90.             '@type' => 'School',
  91.             'name' => $etablissement->getDenomination(),
  92.             'legalName' => $etablissement->getDenomination(),
  93.             'url' => $etablissement->getUrl() ?? $this->router->generate('homepage', [], UrlGeneratorInterface::ABSOLUTE_URL).'fiche/'.$etablissement->getId(),
  94.             /*'sameAs' => // Ajouter réseau sociaux */
  95.             'logo' => null !== $etablissement->getLogoFiche()
  96.                     ? $this->imagineCacheManager->getBrowserPath('/images/jouve/logo-fiche/' $etablissement->getLogoFiche(), 'etab_fiche_logo')
  97.                     : $this->router->generate('homepage', [], UrlGeneratorInterface::ABSOLUTE_URL).$noLogoPath ,
  98.             'email' => $etablissement->getEmailPrincipal(),
  99.             'faxNumber' => $etablissement->getFax(),
  100.             'telephone' => $etablissement->getTelephonePrincipal(),
  101.             'address' => (object) [
  102.                 '@type' => 'PostalAddress',
  103.                 'addressCountry' => 'France',
  104.                 'addressLocality' => $ville $ville->getLibelle() : null,
  105.                 'postalCode' => $etablissement->getCodePostal(),
  106.                 'streetAddress' => $etablissement->getAdresse1().' '.$etablissement->getAdresse2().' '.$etablissement->getAdresse3(),
  107.                 'email' => $etablissement->getEmailPrincipal(),
  108.                 'faxNumber' => $etablissement->getFax(),
  109.                 'telephone' => $etablissement->getTelephonePrincipal(),
  110.                 'name' => $etablissement->getDenomination(),
  111.             ],
  112.             'location' => (object) [
  113.                 '@type' => 'Place',
  114.                 'geo' => (object) [
  115.                     '@type' => 'GeoCoordinates',
  116.                     'latitude' => $etablissement->getLatitude(),
  117.                     'longitude' => $etablissement->getLongitude(),
  118.                 ],
  119.             ],
  120.         ];
  121.     }
  122.     public function diplomes($lesFormations$donneeComplementaire$etablissement) {
  123.         // Regrouper les diplomes par formations 
  124.         try {
  125.             $niveauxFormation = [
  126.                 "-CAP-" => "Niveau CAP",
  127.                 "-BACP-" => "Niveau BAC Pro",
  128.                 "-BAC2-" => "Niveau Bac+2",
  129.                 "-PREPA-" => "Classes Prépas",
  130.                 "-BAC3-" => "Niveau Bac+3",
  131.                 "-BAC45-" => "Niveau Bac+4/5",
  132.                 "-ING-" => "Diplômes d'ingénieurs",
  133.                 "-FPC-" => "Formation Professionnelle Continue",
  134.                 "-BACTECH-" => "Bac Techno (Agricole)",
  135.                 "-DIPCOMP-" => "Diplômes complémentaires"
  136.             ];
  137.             $formations = array();
  138.             foreach ($niveauxFormation as $idFormation => $libFormation) {
  139.                 foreach ($lesFormations as $ItemsInsertion) {
  140.                     if (stristr($ItemsInsertion->getIdentifiant(), $idFormation)) {
  141.                         // Données compléentaires : 
  142.                         $dcTexte DonneeComplementaireExtension::donneeComplementaireStatic($donneeComplementaire$ItemsInsertion->getIdentifiant(), 'texte' );
  143.                         $formations[$libFormation][] = $ItemsInsertion->getLibelle() . "#" $ItemsInsertion->getLibelleSpecifique() . "#" $dcTexte;
  144.                     }
  145.                 } 
  146.             }
  147.             // Construire l'object json
  148.             $courseJsonld = [];
  149.             foreach ($formations as $niveau => $formationsNiveau) {
  150.                 $course = [
  151.                     '@context' => 'http://schema.org/',
  152.                     "@type" => "Course",
  153.                     "name" => $niveau,
  154.                     "description" => $niveau,
  155.                     "hasCourseInstance" => [
  156.                         "@type" => "CourseInstance",
  157.                         "courseMode" => "onsite",
  158.                         "name" => $niveau,
  159.                         "courseWorkload" => "PT30H" // "PT" indique que c'est une durée. "30H" signifie 30 heures.
  160.                     ],
  161.                     "offers" => [
  162.                         "@type" => "Offer",
  163.                         "price" => "0.00",
  164.                         "priceCurrency" => "EUR",
  165.                         "category" => "Education"
  166.                     ],
  167.                     "provider" => [
  168.                         "@type" => "Organization",
  169.                         "name" => $etablissement->getDenomination(),
  170.                         "url" => $etablissement->getUrl() ?? $this->router->generate('homepage', [], UrlGeneratorInterface::ABSOLUTE_URL).'fiche/'.$etablissement->getId()
  171.                     ],
  172.                     "educationalCredentialAwarded" => []
  173.                 ];
  174.                 
  175.                 foreach ($formationsNiveau as $formation) {
  176.                     list($libelle$libelleSpecifique$complement) = explode("#"$formation);
  177.                     $course["educationalCredentialAwarded"][] = [
  178.                         '@context' => 'http://schema.org/',
  179.                         "@type" => "EducationalOccupationalCredential",
  180.                         "name" => $libelle,
  181.                         "alternateName" => $libelleSpecifique ?? null,
  182.                         "description" => $complement ?? null,
  183.                         "educationalLevel" => str_replace("Niveau """$niveau)
  184.                     ];
  185.                 }
  186.                 
  187.                 $courseJsonld[] = $course;
  188.             }
  189.         } catch (\Exception $e) {
  190.             $courseJsonld null;
  191.         }
  192.         return  json_encode($courseJsonldJSON_UNESCAPED_UNICODE);
  193.     }
  194.     public function onpc(): stdClass
  195.     {
  196.         return (object) [
  197.             '@context' => 'http://schema.org/',
  198.             '@type' => 'Organization',
  199.             'name' => 'Office National de Publication et de Communication',
  200.             'alternateName' => 'ONPC',
  201.             'url' => 'http://www.onpc.fr',
  202.             'logo' => (object) [
  203.                 '@type' => 'ImageObject',
  204.                 'url' => 'http://www.onpc.fr/onpc/mes-docs/uploads/2016/10/logo-SVG.svg',
  205.             ],
  206.         ];
  207.     }
  208.     public function website(): stdClass
  209.     {
  210.         return (object) [
  211.             '@context' => 'http://schema.org/',
  212.             '@type' => 'WebSite',
  213.             '@id' => '#website',
  214.             'name' => "L'annuaire officiel de l'enseignement privé",
  215.             'about' => "L'annuaire officiel de l'enseignement privé: retrouvez toutes les informations sur les établissements privés catholiques et laïques de France. Ecole primaire, collèges privés, lycées privés, lycées technologiques, enseignement supérieur. Un outil de recherche indispensable pour l'orientation scolaire",
  216.             'url' => $this->router->generate('homepage', [], UrlGeneratorInterface::ABSOLUTE_URL),
  217.             'author' => $this->onpc(),
  218.             'potentialAction' => (object) [
  219.                 '@type' => 'SearchAction',
  220.                 'target' => $this->router->generate('homepage', [], UrlGeneratorInterface::ABSOLUTE_URL) . 'annuaire/{quoi}/{ou}'/*$this->pathBuilder->buildAnnuaire('{quoi}', '{ou}'),*/
  221.                 'query-input' => 'required name=quoi name=ou',
  222.             ],
  223.         ];
  224.     }
  225.     public function video(Video $video): stdClass
  226.     {
  227.         return (object) [
  228.             '@context' => 'http://schema.org/',
  229.             '@type' => 'VideoObject',
  230.             'name' => $video->getTitre(),
  231.             'url' => $video->getUrl(),
  232.             'description' => $video->getTexte() != null $video->getTexte() : $video->getEtablissements()[0]->getDenomination(),
  233.             'uploadDate' => $video->getDateCrea()->format('c'),
  234.             'thumbnailUrl' =>$this->router->generate('homepage', [], UrlGeneratorInterface::ABSOLUTE_URL).'storage/video/'.$video->getFileName()
  235.         ];
  236.     }
  237.     public function diapo(DiaporamaPhoto $diaporamaPhoto): stdClass
  238.     {
  239.         return (object) [
  240.             '@context' => 'http://schema.org/',
  241.             '@type' => 'ImageObject',
  242.             'name' => $diaporamaPhoto->getTitre(),
  243.             'url' => $this->router->generate('homepage', [], UrlGeneratorInterface::ABSOLUTE_URL).'storage/diaporama_photo/'.$diaporamaPhoto->getFileName(),
  244.             // 'url' => $this->imagineCacheManager->getBrowserPath('/images/jouve/photo/' . $diaporamaPhoto->getFileName(), 'etab_fiche')
  245.         ];
  246.     }
  247.     public function generateFaqJsonLd(array $faqs): ?string
  248.     {
  249.         if (count($faqs) == 0)
  250.             return null;
  251.         $data = [
  252.             "@context" => "https://schema.org",
  253.             "@type" => "FAQPage",
  254.             "mainEntity" => [],
  255.         ];
  256.         foreach ($faqs as $faq) {
  257.             $data['mainEntity'][] = [
  258.                 "@type" => "Question",
  259.                 "name" => $faq->getQuestion(),
  260.                 "acceptedAnswer" => [
  261.                     "@type" => "Answer",
  262.                     "text" => strip_tags($faq->getReponse()),
  263.                 ],
  264.             ];
  265.         }
  266.         // return json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
  267.         return json_encode($dataJSON_UNESCAPED_UNICODE);
  268.     }
  269. }