|
| 1 | +<?php declare(strict_types = 1); |
| 2 | + |
| 3 | +namespace Utilitte\Components\Rating; |
| 4 | + |
| 5 | +use Nette\Application\UI\Control; |
| 6 | +use Nette\Security\User; |
| 7 | +use Utilitte\Components\Rating\Model\RatingModelInterface; |
| 8 | +use Utilitte\Components\Rating\ValueObject\Rating; |
| 9 | +use Utilitte\Components\Utility\TControl; |
| 10 | + |
| 11 | +final class RatingComponent extends Control |
| 12 | +{ |
| 13 | + |
| 14 | + use TControl; |
| 15 | + |
| 16 | + /** @var callable[] */ |
| 17 | + private array $onVoted = []; |
| 18 | + |
| 19 | + private bool $set = false; |
| 20 | + |
| 21 | + private int $increase = 0; |
| 22 | + |
| 23 | + public function __construct( |
| 24 | + private RatingModelInterface $model, |
| 25 | + private Rating $rating, |
| 26 | + private User $user, |
| 27 | + ) |
| 28 | + { |
| 29 | + } |
| 30 | + |
| 31 | + public function addIncrease(int $amount): self |
| 32 | + { |
| 33 | + $this->increase += $amount; |
| 34 | + |
| 35 | + return $this; |
| 36 | + } |
| 37 | + |
| 38 | + public function onVoted(callable $callback): void |
| 39 | + { |
| 40 | + $this->onVoted[] = $callback; |
| 41 | + } |
| 42 | + |
| 43 | + public function render(): void |
| 44 | + { |
| 45 | + $template = $this->getTemplate(); |
| 46 | + $template->setFile($this->getFile(__DIR__ . '/templates/rating.latte')); |
| 47 | + |
| 48 | + if (!$this->set) { |
| 49 | + $template->rating = $this->rating->getRating() + $this->increase; |
| 50 | + $template->voted = $this->rating->getVoted(); |
| 51 | + } |
| 52 | + |
| 53 | + $template->increase = $this->increase; |
| 54 | + $template->canVote = $this->rating->canVote(); |
| 55 | + |
| 56 | + $template->render(); |
| 57 | + } |
| 58 | + |
| 59 | + public function handleVote(int $value): void |
| 60 | + { |
| 61 | + $ajax = $this->getPresenter()->isAjax(); |
| 62 | + if (!$this->model->isVoteValueValid($value)) { |
| 63 | + if ($ajax) { |
| 64 | + return; |
| 65 | + } |
| 66 | + |
| 67 | + $this->redirect('this'); |
| 68 | + } |
| 69 | + |
| 70 | + $result = $this->model->vote($this->rating->getSource(), $value); |
| 71 | + |
| 72 | + foreach ($this->onVoted as $callback) { |
| 73 | + $callback(); |
| 74 | + } |
| 75 | + |
| 76 | + if ($ajax) { |
| 77 | + $template = $this->getTemplate(); |
| 78 | + $template->rating = $this->rating->getRating() + $result->getDifference() + $this->increase; |
| 79 | + $template->voted = $result->getVoted(); |
| 80 | + |
| 81 | + $this->set = true; |
| 82 | + |
| 83 | + $this->redrawControl(); |
| 84 | + } else { |
| 85 | + $this->redirect('this'); |
| 86 | + } |
| 87 | + } |
| 88 | + |
| 89 | +} |
0 commit comments