AbstractTemplateComponent.php
56 lines
| 1 | <?php |
| 2 | |
| 3 | // TODO PHP7.x; declare(strict_types=1); |
| 4 | // TODO PHP7.x; type-hints && return types |
| 5 | |
| 6 | namespace WPStaging\Framework\Component; |
| 7 | |
| 8 | use WPStaging\Framework\Adapter\WpAdapter; |
| 9 | use WPStaging\Framework\Security\AccessToken; |
| 10 | use WPStaging\Framework\Security\Capabilities; |
| 11 | use WPStaging\Framework\Security\Nonce; |
| 12 | use WPStaging\Framework\TemplateEngine\TemplateEngine; |
| 13 | |
| 14 | abstract class AbstractTemplateComponent |
| 15 | { |
| 16 | /** @var TemplateEngine */ |
| 17 | protected $templateEngine; |
| 18 | |
| 19 | private $accessToken; |
| 20 | private $nonce; |
| 21 | private $wpAdapter; |
| 22 | |
| 23 | public function __construct(TemplateEngine $templateEngine) |
| 24 | { |
| 25 | $this->templateEngine = $templateEngine; |
| 26 | |
| 27 | // Todo: Inject using DI |
| 28 | $this->accessToken = new AccessToken(); |
| 29 | $this->nonce = new Nonce(); |
| 30 | $this->wpAdapter = new WpAdapter(); |
| 31 | } |
| 32 | |
| 33 | /** |
| 34 | * @param string $path |
| 35 | * @param array $params |
| 36 | * |
| 37 | * @return string |
| 38 | */ |
| 39 | public function renderTemplate($path, array $params = []) |
| 40 | { |
| 41 | return $this->templateEngine->render($path, $params); |
| 42 | } |
| 43 | |
| 44 | /** |
| 45 | * @return bool Whether the current request should render this template. |
| 46 | */ |
| 47 | protected function canRenderAjax() |
| 48 | { |
| 49 | $isAjax = $this->wpAdapter->doingAjax(); |
| 50 | $hasToken = $this->accessToken->requestHasValidToken(); |
| 51 | $isAuthenticated = current_user_can((new Capabilities())->manageWPSTG()) && $this->nonce->requestHasValidNonce(Nonce::WPSTG_NONCE); |
| 52 | |
| 53 | return $isAjax && ($hasToken || $isAuthenticated); |
| 54 | } |
| 55 | } |
| 56 |