| 1 |
<?php |
| 2 |
|
| 3 |
namespace Give\Framework\Views; |
| 4 |
|
| 5 |
use InvalidArgumentException; |
| 6 |
|
| 7 |
/** |
| 8 |
* Helper class responsible for loading views. |
| 9 |
*/ |
| 10 |
class View |
| 11 |
{ |
| 12 |
/** |
| 13 |
* Default domain |
| 14 |
*/ |
| 15 |
const DEFAULT_DOMAIN = 'FormBuilder'; |
| 16 |
|
| 17 |
/** |
| 18 |
* @since 3.0.0 |
| 19 |
* |
| 20 |
* @param array $templateParams Arguments for template. |
| 21 |
* @param bool $echo |
| 22 |
* |
| 23 |
* @param string $view Template name |
| 24 |
* When using multiple domains within this plugin, the domain directory can be set by using "." in the template name. |
| 25 |
* String before the "." character is domain directory, and everything after is the template file path |
| 26 |
* Example usage: View::render( 'DomainName.templateName' ); |
| 27 |
* This will try to load src/DomainName/resources/view/templateName.php file |
| 28 |
* |
| 29 |
* @return string|void |
| 30 |
* @throws InvalidArgumentException if template file not exist |
| 31 |
* |
| 32 |
*/ |
| 33 |
public static function load($view, $templateParams = [], $echo = false) |
| 34 |
{ |
| 35 |
// Get domain and file path |
| 36 |
list ($domain, $file) = static::getPaths($view); |
| 37 |
$template = GIVE_PLUGIN_DIR . "src/{$domain}/resources/views/{$file}.php"; |
| 38 |
|
| 39 |
if ( ! file_exists($template)) { |
| 40 |
throw new InvalidArgumentException("View template file {$template} does not exist"); |
| 41 |
} |
| 42 |
|
| 43 |
ob_start(); |
| 44 |
extract($templateParams); |
| 45 |
include $template; |
| 46 |
$content = ob_get_clean(); |
| 47 |
|
| 48 |
if ( ! $echo) { |
| 49 |
return $content; |
| 50 |
} |
| 51 |
|
| 52 |
echo $content; |
| 53 |
} |
| 54 |
|
| 55 |
/** |
| 56 |
* @since 3.0.0 |
| 57 |
* |
| 58 |
* @param array $vars |
| 59 |
* |
| 60 |
* @param string $view |
| 61 |
*/ |
| 62 |
public static function render($view, $vars = []) |
| 63 |
{ |
| 64 |
static::load($view, $vars, true); |
| 65 |
} |
| 66 |
|
| 67 |
/** |
| 68 |
* Get domain and template file path |
| 69 |
* |
| 70 |
* @since 3.0.0 |
| 71 |
* |
| 72 |
* @param string $path |
| 73 |
* |
| 74 |
* @return array |
| 75 |
*/ |
| 76 |
private static function getPaths($path) |
| 77 |
{ |
| 78 |
// Check for . delimiter |
| 79 |
if (false === strpos($path, '.')) { |
| 80 |
return [ |
| 81 |
self::DEFAULT_DOMAIN, |
| 82 |
$path, |
| 83 |
]; |
| 84 |
} |
| 85 |
|
| 86 |
return explode('.', $path, 2); |
| 87 |
} |
| 88 |
} |