Created
December 24, 2018 16:14
-
-
Save laras126/1330e7ef4d0058de6bd1ec02f874ace0 to your computer and use it in GitHub Desktop.
Possible Twig to PHP parsing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function render_component( $component, $data ) { | |
$twig_file = CHILD_THEME_PATH . '/assets/src/components/c-' . $component . '/c-' . $component . '.twig'; | |
$template_path = CHILD_THEME_PATH . '/template-parts/components/c-' . $component . '.php'; | |
// This file writing / string manipulation should likely be part of a different program, not the render_component function. | |
if ( file_exists( $twig_file ) && 0 === validate_file( $twig_file ) ) { | |
$twig_markup = PMC::render_template( $twig_file, [] ); | |
// Get matches for {{ name }} | |
// https://regex101.com/r/ACN0rE/1 | |
$full_pattern = '/({{\s*)(\w*)(\s*}})/'; | |
preg_match_all( $full_pattern, $twig_markup, $matches ); | |
$count = 0; | |
$replacements = []; | |
foreach ( $matches[0] as $key => $match ) { | |
$variable_name = $matches[2][$count]; | |
$is_class = strpos( $match, 'class'); | |
$is_url = strpos( $match, 'url'); | |
$is_text = strpos( $match, 'text'); | |
// Add support for more variable types here. | |
if ( ! empty( $is_url ) ) { | |
$replacements[$count] = '<?php echo esc_url( $' . $variable_name . ' ); ?>'; | |
} | |
if ( ! empty( $is_class ) ) { | |
$replacements[$count] = '<?php echo esc_attr( $' . $variable_name . ' ); ?>'; | |
} | |
if ( ! empty( $is_text ) ) { | |
$replacements[$count] = '<?php echo esc_html( $' . $variable_name . ' ); ?>'; | |
} | |
$count++; | |
} | |
$php_markup = "<?php\n// This is a generated file. Refer to the file located at $twig_file for adjusting this markup.\n?>\n"; | |
$php_markup .= str_replace( $matches[0], $replacements, $twig_markup ); | |
$handle = fopen( $template_path, 'w' ); | |
fwrite( $handle, $php_markup ); | |
} else { | |
echo 'no file here huh'; | |
} | |
PMC::render_template( $template_path, $data, true ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment