Skip to content

Instantly share code, notes, and snippets.

@christopherarter
Last active May 30, 2019 19:07
Show Gist options
  • Save christopherarter/f420dbefd58475908816aa42ecf971b9 to your computer and use it in GitHub Desktop.
Save christopherarter/f420dbefd58475908816aa42ecf971b9 to your computer and use it in GitHub Desktop.
TemplateEngine for Wordpress
<?php
/**
* Include any file and pass values to it.
*
* Written by Chris Arter
*/
class TemplateEngine {
/**
* Retrieves the template section and brings in inputs for template section to access
* @param String $path Path of template file. Can be full path or relative to theme root.
* @param Array $input This array will be available to the target template file
* @return markup Returns the markup with the combined input and template file.
*/
public static function get( String $path, $input = null, String $dataName = null ) {
// Format the string if it does not contain a forward slash.
$path = self::formatPath( $path );
if( $dataName ) {
${$dataName} = $input;
$input;
} else {
$input;
}
self::getMarkup( include($path) );
}
/**
* Checks if path has forward slash. Adds if it doesn't.
* @param String $string Path to be formatted
* @return String Formatted string
*/
protected static function forwardSlashCheck($string) {
if( ! $string[0] == '/'){
return '/'.$string;
}
return $string;
}
/**
* Checks if the string already contains a full path or not.
* @param String $path Path to be formatted
* @return String Formatted string
*/
protected static function fullPathCheck( $path ) {
if( strpos($path, get_stylesheet_directory()) ){
return $string;
} else {
return get_stylesheet_directory() . $path;
}
}
/**
* Runs the format sequence of backslash check and full path check
* @param String $path String to be formatted
* @return String Formatted String
*/
protected static function formatPath( $path ){
$string = self::forwardSlashCheck($path);
return self::fullPathCheck($string);
}
/**
* Inject markup
* @param html $input input being injected
* @return markup return the markup.
*/
protected static function getMarkup( $input ) {
ob_start();
$input;
$html = ob_get_clean();
echo $html;
}
/**
* Associates $input variable in get method with data name
* @param data $input Data to be associated
* @param String|null $dataName Name of the variable in the template section
* @return input Returns the input and associates with array.
*/
protected static function dataHandler( $input, String $dataName = null ){
if( $dataName ) {
${$dataName} = $input;
return $input;
} else {
return $input;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment