src/Blog.php line 37

Open in your IDE?
  1. <?php
  2. namespace App;
  3. use Psr\Log\LoggerAwareInterface;
  4. use Psr\Log\LoggerAwareTrait;
  5. use Symfony\Contracts\Cache\CacheInterface;
  6. use Symfony\Contracts\Cache\ItemInterface;
  7. use Symfony\Contracts\HttpClient\Exception\HttpExceptionInterface;
  8. use Symfony\Contracts\HttpClient\HttpClientInterface;
  9. class Blog implements LoggerAwareInterface
  10. {
  11.     use LoggerAwareTrait;
  12.     private CacheInterface $cache;
  13.     private string $hubSpotKey;
  14.     private HttpClientInterface $httpClient;
  15.     private array $posts;
  16.     private array $authors;
  17.     private array $tags;
  18.     public function __construct(CacheInterface $cachestring $hubSpotKeyHttpClientInterface $httpClient)
  19.     {
  20.         $this->cache $cache;
  21.         $this->hubSpotKey $hubSpotKey;
  22.         $this->httpClient $httpClient;
  23.     }
  24.     /**
  25.      * This busts the cached blog data and reloads everything.
  26.      * WARNING: This will be slow and should not be called
  27.      * unless intentional.
  28.      */
  29.     public function bustCache(): void
  30.     {
  31.         $this->getAuthors(true);
  32.         $this->getTags(true);
  33.         $this->getAllPosts(true);
  34.     }
  35.     public function getAuthor(string $slug): ?array
  36.     {
  37.         foreach ($this->getAuthors() as $author) {
  38.             if ($author['slug'] == $slug) {
  39.                 return $author;
  40.             }
  41.         }
  42.         return null;
  43.     }
  44.     public function getTag(string $slug): ?array
  45.     {
  46.         foreach ($this->getTags() as $tag) {
  47.             if ($tag['slug'] == $slug) {
  48.                 return $tag;
  49.             }
  50.         }
  51.         return null;
  52.     }
  53.     public function getPosts(int $perPage 3int $page 1string $tag ''string $author ''): array
  54.     {
  55.         $offset = ($page 1) * $perPage;
  56.         $posts $this->getAllPosts();
  57.         if ($tag) {
  58.             $postsFiltered = [];
  59.             foreach ($posts as $post) {
  60.                 foreach ($post['tags'] as $tag2) {
  61.                     if ($tag2['slug'] == $tag) {
  62.                         $postsFiltered[] = $post;
  63.                         break;
  64.                     }
  65.                 }
  66.             }
  67.             $posts $postsFiltered;
  68.         }
  69.         if ($author) {
  70.             $postsFiltered = [];
  71.             foreach ($posts as $post) {
  72.                 if ($post['author']['slug'] == $author) {
  73.                     $postsFiltered[] = $post;
  74.                 }
  75.             }
  76.             $posts $postsFiltered;
  77.         }
  78.         if ($perPage 0) {
  79.             return $posts;
  80.         }
  81.         return array_slice($posts$offset$perPage);
  82.     }
  83.     public function hasMorePosts(int $perPageint $page, ?string $tag '', ?string $author ''): bool
  84.     {
  85.         $posts $this->getPosts(-11$tag$author);
  86.         return $perPage $page count($posts);
  87.     }
  88.     public function getPost(string $id): ?array
  89.     {
  90.         $posts $this->getAllPosts();
  91.         foreach ($posts as $post) {
  92.             if ($post['slug'] == $id) {
  93.                 return $post;
  94.             }
  95.         }
  96.         return null;
  97.     }
  98.     public function getPrevious(string $id): ?array
  99.     {
  100.         $found false;
  101.         foreach ($this->getAllPosts() as $post) {
  102.             if ($post['slug'] == $id) {
  103.                 $found true;
  104.             } elseif ($found) {
  105.                 return $post;
  106.             }
  107.         }
  108.         return null;
  109.     }
  110.     public function getNext(string $id): ?array
  111.     {
  112.         $previous null;
  113.         foreach ($this->getAllPosts() as $post) {
  114.             if ($post['slug'] == $id) {
  115.                 return $previous;
  116.             }
  117.             $previous $post;
  118.         }
  119.         return null;
  120.     }
  121.     public function getAuthors(bool $bustCache false): array
  122.     {
  123.         if (!isset($this->authors)) {
  124.             $beta $bustCache INF null;
  125.             $this->authors $this->cache->get('blog_authors', function (ItemInterface $item) {
  126.                 $item->expiresAfter(86400); // cache for 1 day
  127.                 return $this->loadBlogAuthors();
  128.             }, $beta);
  129.         }
  130.         return $this->authors;
  131.     }
  132.     private function getAuthorById(int $id): array
  133.     {
  134.         $authors $this->getAuthors();
  135.         foreach ($authors as $author) {
  136.             if ($author['id'] == $id) {
  137.                 return $author;
  138.             }
  139.         }
  140.         return $authors[0];
  141.     }
  142.     private function loadBlogAuthors(?string $after null): array
  143.     {
  144.         try {
  145.             $response $this->httpClient->request('GET''https://api.hubapi.com/cms/v3/blogs/authors', [
  146.                 'query' => [
  147.                     'hapikey' => $this->hubSpotKey,
  148.                     'after' => $after,
  149.                 ],
  150.             ]);
  151.             $result json_decode($response->getContent(), true);
  152.         } catch (HttpExceptionInterface $e) {
  153.             $this->logger->error('Could not load blog posts from HubSpot', ['exception' => $e]);
  154.             throw $e;
  155.         }
  156.         $authors $result['results'];
  157.         foreach ($authors as &$author) {
  158.             $author['slug'] = $this->slugify($author['name']);
  159.         }
  160.         // load all pages of data
  161.         if (isset($result['paging']['next'])) {
  162.             $authors array_merge(
  163.                 $result['results'],
  164.                 $this->loadBlogAuthors($result['paging']['next']['after'])
  165.             );
  166.         }
  167.         return $authors;
  168.     }
  169.     public function getAllPosts(bool $bustCache false): array
  170.     {
  171.         if (!isset($this->posts)) {
  172.             $beta $bustCache INF null;
  173.             $this->posts $this->cache->get('blog_posts', function (ItemInterface $item) {
  174.                 $item->expiresAfter(86400); // cache for 1 day
  175.                 return $this->loadBlogPosts();
  176.             }, $beta);
  177.         }
  178.         return $this->posts;
  179.     }
  180.     private function loadBlogPosts(?string $after null): array
  181.     {
  182.         try {
  183.             $response $this->httpClient->request('GET''https://api.hubapi.com/cms/v3/blogs/posts', [
  184.                 'query' => [
  185.                     'hapikey' => $this->hubSpotKey,
  186.                     'after' => $after,
  187.                 ],
  188.             ]);
  189.             $result json_decode($response->getContent(), true);
  190.         } catch (HttpExceptionInterface $e) {
  191.             $this->logger->error('Could not load blog posts from HubSpot', ['exception' => $e]);
  192.             throw $e;
  193.         }
  194.         $posts = [];
  195.         foreach ($result['results'] as $post) {
  196.             // Remove draft and archived posts
  197.             if ('PUBLISHED' != $post['currentState']) {
  198.                 continue;
  199.             }
  200.             // determine the author
  201.             $post['author'] = $this->getAuthorById($post['blogAuthorId']);
  202.             // determine the primary tag
  203.             $post['tags'] = [];
  204.             foreach ($post['tagIds'] as $tagId) {
  205.                 $post['tags'][] = $this->getTagById($tagId);
  206.             }
  207.             $post['tag'] = count($post['tags']) > $post['tags'][0] : null;
  208.             // strip not allowed characters from slug
  209.             $post['slug'] = $this->slugify($post['slug']);
  210.             $posts[] = $post;
  211.         }
  212.         // load all pages of data
  213.         if (isset($result['paging']['next'])) {
  214.             $posts array_merge(
  215.                 $posts,
  216.                 $this->loadBlogPosts($result['paging']['next']['after'])
  217.             );
  218.         }
  219.         // sort by date
  220.         usort($posts, [$this'sortPost']);
  221.         return $posts;
  222.     }
  223.     public function getTags(bool $bustCache false): array
  224.     {
  225.         if (!isset($this->tags)) {
  226.             $beta $bustCache INF null;
  227.             $this->tags $this->cache->get('blog_tags', function (ItemInterface $item) {
  228.                 $item->expiresAfter(86400); // cache for 1 day
  229.                 return $this->loadBlogTags();
  230.             }, $beta);
  231.         }
  232.         return $this->tags;
  233.     }
  234.     private function getTagById(int $id): ?array
  235.     {
  236.         foreach ($this->getTags() as $tagDetail) {
  237.             if ($tagDetail['id'] == $id) {
  238.                 return $tagDetail;
  239.             }
  240.         }
  241.         return null;
  242.     }
  243.     private function loadBlogTags(?string $after null): array
  244.     {
  245.         try {
  246.             $response $this->httpClient->request('GET''https://api.hubapi.com/cms/v3/blogs/tags', [
  247.                 'query' => [
  248.                     'hapikey' => $this->hubSpotKey,
  249.                     'after' => $after,
  250.                 ],
  251.             ]);
  252.             $result json_decode($response->getContent(), true);
  253.         } catch (HttpExceptionInterface $e) {
  254.             $this->logger->error('Could not load blog posts from HubSpot', ['exception' => $e]);
  255.             throw $e;
  256.         }
  257.         $tags $result['results'];
  258.         foreach ($tags as &$tag) {
  259.             $tag['slug'] = $this->slugify($tag['name']);
  260.         }
  261.         // load all pages of data
  262.         if (isset($result['paging']['next'])) {
  263.             $tags array_merge(
  264.                 $tags,
  265.                 $this->loadBlogTags($result['paging']['next']['after'])
  266.             );
  267.         }
  268.         // sort by name
  269.         usort($tags, [$this'sortTag']);
  270.         return $tags;
  271.     }
  272.     /**
  273.      * Sorts two blog posts in reverse date order.
  274.      */
  275.     public function sortPost(array $a, array $b): int
  276.     {
  277.         return $b['publishDate'] <=> $a['publishDate'];
  278.     }
  279.     /**
  280.      * Sorts two blog tags in alphabetical order.
  281.      */
  282.     public function sortTag(array $a, array $b): int
  283.     {
  284.         return $a['name'] <=> $b['name'];
  285.     }
  286.     private function slugify(string $input): string
  287.     {
  288.         $slug strtolower(str_replace(' ''-'$input));
  289.         return preg_replace('/[^0-9a-zA-Z\-]/'''$slug);
  290.     }
  291. }