| 1 |
<?php |
| 2 |
|
| 3 |
declare(strict_types=1); |
| 4 |
|
| 5 |
namespace UserAccessManager\Controller; |
| 6 |
|
| 7 |
use Exception; |
| 8 |
use UserAccessManager\Config\WordpressConfig; |
| 9 |
use UserAccessManager\Wrapper\Php; |
| 10 |
|
| 11 |
trait BaseControllerTrait |
| 12 |
{ |
| 13 |
abstract protected function getPhp(): Php; |
| 14 |
abstract protected function getWordpressConfig(): WordpressConfig; |
| 15 |
protected ?string $template = null; |
| 16 |
|
| 17 |
public function getRequestUrl(): string |
| 18 |
{ |
| 19 |
return htmlentities($_SERVER['REQUEST_URI']); |
| 20 |
} |
| 21 |
|
| 22 |
private function sanitizeValue(mixed $value): mixed |
| 23 |
{ |
| 24 |
if (is_object($value) === true) { |
| 25 |
return $value; |
| 26 |
} elseif (is_array($value) === true) { |
| 27 |
$newValue = []; |
| 28 |
|
| 29 |
foreach ($value as $key => $arrayValue) { |
| 30 |
$sanitizedKey = $this->sanitizeValue($key); |
| 31 |
$newValue[$sanitizedKey] = $this->sanitizeValue($arrayValue); |
| 32 |
} |
| 33 |
|
| 34 |
$value = $newValue; |
| 35 |
} elseif (is_string($value) === true) { |
| 36 |
$value = preg_replace('/[\\\\]+(["|\'])/', '$1', $value); |
| 37 |
$value = stripslashes($value); |
| 38 |
$value = htmlspecialchars($value); |
| 39 |
} |
| 40 |
|
| 41 |
return $value; |
| 42 |
} |
| 43 |
|
| 44 |
public function getRequestParameter(string $name, mixed $default = null): mixed |
| 45 |
{ |
| 46 |
$return = (isset($_POST[$name]) === true) ? $this->sanitizeValue($_POST[$name]) : null; |
| 47 |
|
| 48 |
if ($return === null) { |
| 49 |
$return = (isset($_GET[$name]) === true) ? $this->sanitizeValue($_GET[$name]) : $default; |
| 50 |
} |
| 51 |
|
| 52 |
return $return; |
| 53 |
} |
| 54 |
|
| 55 |
protected function getIncludeContents(string $fileName): string |
| 56 |
{ |
| 57 |
$contents = ''; |
| 58 |
$realPath = rtrim($this->getWordpressConfig()->getRealPath(), DIRECTORY_SEPARATOR); |
| 59 |
$path = [$realPath, 'src', 'View']; |
| 60 |
$path = implode(DIRECTORY_SEPARATOR, $path).DIRECTORY_SEPARATOR; |
| 61 |
$fileWithPath = $path.$fileName; |
| 62 |
|
| 63 |
if (is_file($fileWithPath) === true) { |
| 64 |
try { |
| 65 |
ob_start(); |
| 66 |
$this->getPhp()->includeFile($this, $fileWithPath); |
| 67 |
$contents = ob_get_contents(); |
| 68 |
ob_end_clean(); |
| 69 |
} catch (Exception $exception) { |
| 70 |
$contents = "Error on including content '$fileWithPath': {$exception->getMessage()}"; |
| 71 |
ob_end_clean(); |
| 72 |
} |
| 73 |
} |
| 74 |
|
| 75 |
return $contents; |
| 76 |
} |
| 77 |
|
| 78 |
public function render(): void |
| 79 |
{ |
| 80 |
if ($this->template !== null) { |
| 81 |
echo $this->getIncludeContents($this->template); |
| 82 |
} |
| 83 |
} |
| 84 |
} |
| 85 |
|