ArticleService.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace App\Services;
  3. use App\Models\Article;
  4. class ArticleService
  5. {
  6. private static array $valuables;
  7. public function __construct(private readonly Article $article)
  8. {
  9. $siteName = sysConfig('website_name');
  10. $siteUrl = sysConfig('website_url');
  11. $subUrl = auth()->user()?->sub_url;
  12. self::$valuables = [
  13. '{{siteName}}' => $siteName,
  14. '{{urlEncodeSiteName}}' => urlencode($siteName),
  15. '{{urlEncodeSiteUrl}}' => urlencode($siteUrl),
  16. '{{siteUrl}}' => $siteUrl,
  17. '{{subUrl}}' => $subUrl,
  18. '{{urlEncodeSubUrl}}' => urlencode($subUrl),
  19. '{{base64SubUrl}}' => base64url_encode($subUrl),
  20. ];
  21. }
  22. public function getContent(): string
  23. {
  24. $content = $this->article->content;
  25. $this->formatAccessible($content);
  26. $this->formatValuables($content);
  27. return $content;
  28. }
  29. private function formatAccessible(string &$body): void
  30. {
  31. $noAccess = ! (new UserService)->isActivePaying();
  32. $mode1Start = '<!--access_mode_1 start-->';
  33. $mode1End = '<!--access_mode_1 end-->';
  34. $mode2Start = '<!--access_mode_2 start-->';
  35. $mode2End = '<!--access_mode_2 end-->';
  36. $mode2Else = '<!--access_mode_2 else-->';
  37. if ($noAccess) {
  38. while (($accessArea = $this->getInBetween($body, $mode1Start, $mode1End)) !== '') {
  39. $replacement = '<div class="user-no-access"><i class="icon wb-lock" aria-hidden="true"></i>'.__('You must have a valid subscription to view the content in this area!').'</div>';
  40. $body = strtr($body, [$accessArea => $replacement]);
  41. }
  42. }
  43. while (($accessArea = $this->getInBetween($body, $mode2Start, $mode2End)) !== '') {
  44. $hasAccessArea = $this->getInBetween($accessArea, $mode2Start, $mode2Else, true);
  45. $noAccessArea = $this->getInBetween($accessArea, $mode2Else, $mode2End, true);
  46. $body = strtr($body, [$accessArea => $noAccess ? $noAccessArea : $hasAccessArea]);
  47. }
  48. }
  49. private function getInBetween(string $input, string $start, string $end, bool $bodyOnly = false): string
  50. {
  51. $startPos = stripos($input, $start);
  52. $endPos = stripos($input, $end, $startPos ?: 0);
  53. if ($startPos === false || $endPos === false) {
  54. return '';
  55. }
  56. $substr = substr($input, $startPos + strlen($start), $endPos - strlen($input));
  57. return $bodyOnly ? $substr : $start.$substr.$end;
  58. }
  59. private function formatValuables(string &$body): void
  60. {
  61. $body = strtr($body, self::$valuables);
  62. }
  63. }