ArticleService.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. $subscribe = auth()->user()->subscribe;
  12. $subUrl = route('sub', $subscribe->code);
  13. self::$valuables = [
  14. '{{siteName}}' => $siteName,
  15. '{{urlEncodeSiteName}}' => urlencode($siteName),
  16. '{{urlEncodeSiteUrl}}' => urlencode($siteUrl),
  17. '{{siteUrl}}' => $siteUrl,
  18. '{{subUrl}}' => $subUrl,
  19. '{{urlEncodeSubUrl}}' => urlencode($subUrl),
  20. '{{base64SubUrl}}' => base64url_encode($subUrl),
  21. ];
  22. }
  23. public function getContent(): string
  24. {
  25. $content = $this->article->content;
  26. $this->formatAccessible($content);
  27. $this->formatValuables($content);
  28. return $content;
  29. }
  30. private function formatAccessible(string &$body): void
  31. {
  32. $noAccess = ! (new UserService)->isActivePaying();
  33. $mode1Start = '<!--access_mode_1 start-->';
  34. $mode1End = '<!--access_mode_1 end-->';
  35. $mode2Start = '<!--access_mode_2 start-->';
  36. $mode2End = '<!--access_mode_2 end-->';
  37. $mode2Else = '<!--access_mode_2 else-->';
  38. if ($noAccess) {
  39. while (($accessArea = $this->getInBetween($body, $mode1Start, $mode1End)) !== '') {
  40. $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>';
  41. $body = strtr($body, [$accessArea => $replacement]);
  42. }
  43. }
  44. while (($accessArea = $this->getInBetween($body, $mode2Start, $mode2End)) !== '') {
  45. $hasAccessArea = $this->getInBetween($accessArea, $mode2Start, $mode2Else, true);
  46. $noAccessArea = $this->getInBetween($accessArea, $mode2Else, $mode2End, true);
  47. $body = strtr($body, [$accessArea => $noAccess ? $noAccessArea : $hasAccessArea]);
  48. }
  49. }
  50. private function getInBetween(string $input, string $start, string $end, bool $bodyOnly = false): string
  51. {
  52. $startPos = stripos($input, $start);
  53. $endPos = stripos($input, $end, $startPos ?: 0);
  54. if ($startPos === false || $endPos === false) {
  55. return '';
  56. }
  57. $substr = substr($input, $startPos + strlen($start), $endPos - strlen($input));
  58. return $bodyOnly ? $substr : $start.$substr.$end;
  59. }
  60. private function formatValuables(string &$body): void
  61. {
  62. $body = strtr($body, self::$valuables);
  63. }
  64. }