ArticleService.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 = str_replace($mode1Start.$accessArea.$mode1End, $replacement, $body);
  42. }
  43. }
  44. while (($accessArea = $this->getInBetween($body, $mode2Start, $mode2End)) !== '') {
  45. $hasAccessArea = $this->getInBetween($accessArea, '', $mode2Else);
  46. $noAccessArea = $this->getInBetween($accessArea, $mode2Else, '');
  47. $body = strtr($body, [$mode2Start.$accessArea.$mode2End => $noAccess ? $noAccessArea : $hasAccessArea]);
  48. }
  49. }
  50. private function getInBetween(string $input, string $start, string $end): string
  51. {
  52. $startPos = stripos($input, $start);
  53. $endPos = stripos($input, $end, $startPos !== false ? $startPos + strlen($start) : 0);
  54. if ($startPos === false || $endPos === false) {
  55. return '';
  56. }
  57. return substr($input, $startPos + strlen($start), $endPos - ($startPos + strlen($start)));
  58. }
  59. private function formatValuables(string &$body): void
  60. {
  61. $body = strtr($body, self::$valuables);
  62. }
  63. }