| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace Metricool\Traits; |
| 6 |
|
| 7 |
use Metricool\Bootstrap\App; |
| 8 |
use Metricool\Support\Helpers\Storages\EnvironmentConfig; |
| 9 |
|
| 10 |
trait HasViews |
| 11 |
{ |
| 12 |
/** |
| 13 |
* Method for returning the desired view as a string |
| 14 |
* @throws \LogicException |
| 15 |
*/ |
| 16 |
public function view(string $path, array $variables = [], string $extension = 'php'): string |
| 17 |
{ |
| 18 |
$basePath = App::getInstance()->get(EnvironmentConfig::class)->getString('plugin.view_path'); |
| 19 |
$filePath = realpath($basePath . $path . '.' . $extension); |
| 20 |
|
| 21 |
// Someone is doing something dirty |
| 22 |
if (!$filePath || strpos($filePath, $basePath) !== 0) { |
| 23 |
throw new \LogicException('Given path is not valid: ' . esc_html($filePath)); |
| 24 |
} |
| 25 |
|
| 26 |
if (!file_exists($filePath) || !is_readable($filePath)) { |
| 27 |
return ''; |
| 28 |
} |
| 29 |
|
| 30 |
extract($variables); |
| 31 |
|
| 32 |
ob_start(); |
| 33 |
require $filePath; |
| 34 |
return ob_get_clean(); |
| 35 |
} |
| 36 |
|
| 37 |
/** |
| 38 |
* Method for outputting the desired view. |
| 39 |
* @internal we can ignore the phpcs error because we validate in {@see view} |
| 40 |
* that the executed path is in our plugin. And we escape all variables |
| 41 |
* in our views, so we have full control. |
| 42 |
*/ |
| 43 |
public function render(string $path, array $variables = [], string $extension = 'php'): void |
| 44 |
{ |
| 45 |
// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped |
| 46 |
echo $this->view($path, $variables, $extension); |
| 47 |
} |
| 48 |
} |
| 49 |
|