| 1 |
<?php |
| 2 |
|
| 3 |
|
| 4 |
namespace Tamara\Wp\Plugin\Services; |
| 5 |
|
| 6 |
|
| 7 |
use Tamara\Wp\Plugin\Traits\ConfigTrait; |
| 8 |
use Tamara\Wp\Plugin\Traits\ServiceTrait; |
| 9 |
|
| 10 |
class ViewService |
| 11 |
{ |
| 12 |
use ConfigTrait; |
| 13 |
use ServiceTrait; |
| 14 |
|
| 15 |
public $basePath; |
| 16 |
public $baseUrl; |
| 17 |
|
| 18 |
/** |
| 19 |
* @inheritDoc |
| 20 |
*/ |
| 21 |
public function init() |
| 22 |
{ |
| 23 |
$this->basePath = $this->getContainer()->basePath; |
| 24 |
$this->baseUrl = $this->getContainer()->baseUrl; |
| 25 |
} |
| 26 |
|
| 27 |
/** |
| 28 |
* @param $viewFilePath |
| 29 |
* @param array $params |
| 30 |
* |
| 31 |
* @return string|void|null |
| 32 |
*/ |
| 33 |
public function render($viewFilePath, $params = []) |
| 34 |
{ |
| 35 |
global $wp_query; |
| 36 |
|
| 37 |
$extension = '.php'; |
| 38 |
// phpcs:ignore WordPress.PHP.DontExtract.extract_extract |
| 39 |
$wp_query->query_vars['viewParams'] = $params; |
| 40 |
|
| 41 |
if (strpos($viewFilePath, '/') === 1) { |
| 42 |
$templateFile = $viewFilePath.$extension; |
| 43 |
} else { |
| 44 |
$templateFile = locate_template($viewFilePath.$extension, false, false); |
| 45 |
if (empty($templateFile) && file_exists($this->basePath.DIRECTORY_SEPARATOR.$viewFilePath.$extension)) { |
| 46 |
$templateFile = $this->basePath.DIRECTORY_SEPARATOR.$viewFilePath.$extension; |
| 47 |
} |
| 48 |
} |
| 49 |
|
| 50 |
if (!empty($templateFile)) { |
| 51 |
ob_start(); |
| 52 |
load_template($templateFile, false); |
| 53 |
$renderedContent = ob_get_clean(); |
| 54 |
|
| 55 |
return is_string($renderedContent) ? $renderedContent : ''; |
| 56 |
} |
| 57 |
|
| 58 |
$errorMessage = sprintf( |
| 59 |
"View file not working: %s.\nTrace: %s", |
| 60 |
$viewFilePath.$extension, |
| 61 |
print_r(debug_backtrace(), true) |
| 62 |
); |
| 63 |
// phpcs:ignore WordPress.XSS.EscapeOutput.OutputNotEscaped |
| 64 |
trigger_error($errorMessage, E_USER_WARNING); |
| 65 |
|
| 66 |
return ''; |
| 67 |
} |
| 68 |
} |
| 69 |
|