ArticleService.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. if ($noAccess) {
  34. while ($this->getInBetween($body, '<!--access_mode_1 start-->', '<!--access_mode_1 end-->', true) !== '') {
  35. $accessArea = $this->getInBetween($body, '<!--access_mode_1 start-->', '<!--access_mode_1 end-->');
  36. if ($accessArea) {
  37. $body = strtr($body,
  38. [$accessArea => '<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>']);
  39. }
  40. }
  41. }
  42. while ($this->getInBetween($body, '<!--access_mode_2 start-->', '<!--access_mode_2 end-->', true) !== '') {
  43. $accessArea = $this->getInBetween($body, '<!--access_mode_2 start-->', '<!--access_mode_2 end-->');
  44. $hasAccessArea = $this->getInBetween($accessArea, '<!--access_mode_2 start-->', '<!--access_mode_2 else-->', true);
  45. $noAccessArea = $this->getInBetween($accessArea, '<!--access_mode_2 else-->', '<!--access_mode_2 end-->', true);
  46. $body = strtr($body, [$accessArea => $accessArea && $noAccess ? $noAccessArea : $hasAccessArea]);
  47. }
  48. }
  49. private function getInBetween(string $input, string $start, string $end, bool $bodyOnly = false): string
  50. {
  51. $substr = substr($input, strpos($input, $start) + strlen($start), strpos($input, $end) - strlen($input));
  52. return $bodyOnly ? $substr : $start.$substr.$end;
  53. }
  54. private function formatValuables(string &$body): void
  55. {
  56. $body = strtr($body, self::$valuables);
  57. }
  58. }