From 0455c10ae0ffc045d32bc8c4683c60bd001ac923 Mon Sep 17 00:00:00 2001 From: Taylor Otwell Date: Thu, 22 Mar 2012 15:02:06 -0500 Subject: [PATCH] Added "for else" support to Blade. --- laravel/blade.php | 65 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 65 insertions(+) diff --git a/laravel/blade.php b/laravel/blade.php index 015af686..ae5c4c84 100644 --- a/laravel/blade.php +++ b/laravel/blade.php @@ -9,6 +9,9 @@ class Blade { */ protected static $compilers = array( 'echos', + 'forelse', + 'empty', + 'endforelse', 'structure_openings', 'structure_closings', 'else', @@ -93,6 +96,68 @@ protected static function compile_echos($value) return preg_replace('/\{\{(.+?)\}\}/', '', $value); } + /** + * Rewrites Blade "for else" statements into valid PHP. + * + * @param string $value + * @return string + */ + protected static function compile_forelse($value) + { + preg_match_all('/(\s*)@forelse(\s*\(.*\))(\s*)/', $value, $matches); + + // First we'll loop through all of the "@forelse" lines. We need to + // wrap each loop in an "if/else" statement that checks the count + // of the variable being iterated against. + if (isset($matches[0])) + { + foreach ($matches[0] as $forelse) + { + preg_match('/\$[^\s]*/', $forelse, $variable); + + // Once we have extracted the variable being looped against, we cab + // prepend an "if" statmeent to the start of the loop that checks + // that the count of the variable is greater than zero. + $if = " 0): ?>"; + + $search = '/(\s*)@forelse(\s*\(.*\))/'; + + $replace = '$1'.$if.''; + + $blade = preg_replace($search, $replace, $forelse); + + // Finally, once we have the check prepended to the loop, we will + // replace all instances of this "forelse" structure in the + // content of the view being compiled to Blade syntax. + $value = str_replace($forelse, $blade, $value); + } + } + + return $value; + } + + /** + * Rewrites Blade "empty" statements into valid PHP. + * + * @param string $value + * @return string + */ + protected static function compile_empty($value) + { + return str_replace('@empty', '', $value); + } + + /** + * Rewrites Blade "forelse" endings into valid PHP. + * + * @param string $value + * @return string + */ + protected static function compile_endforelse($value) + { + return str_replace('@endforelse', '', $value); + } + /** * Rewrites Blade structure openings into PHP structure openings. *