[TYPO3-mvc] adding / multiplying / math operation view helper
Tim Schoch | GSTALTIG
tim.schoch at gstaltig.ch
Mon Feb 7 23:48:37 CET 2011
I made myself a little calc ViewHelper. Maybe it helps you. But as always... provided without warranty
<?php
/* *
* COPYRIGHT NOTICE *
* *
* (c) 2010 Tim Schoch <tim at gstaltig.ch> *
* GSTALTIG GMBH *
* All rights reserved *
* *
* This script is part of the TYPO3 project. The TYPO3 project is *
* free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published *
* by the Free Software Foundation; either version 2 of the License, *
* or (at your option) any later version. *
* *
* The GNU General Public License can be found at *
* http://www.gnu.org/copyleft/gpl.html. *
* *
* This script is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* This copyright notice MUST APPEAR in all copies of the script! *
* */
/**
* calculate strings
*
* @author Tim Schoch
* @see http://www.website55.com/php-mysql/2010/04/how-to-calculate-strings-with-php.html
* @package Gstbase
* @version $Id$
* @license GNU Public License, version 2
* http://opensource.org/licenses/gpl-license.php
*/
class Tx_Gstbase_ViewHelpers_CalcViewHelper extends Tx_Fluid_Core_ViewHelper_AbstractViewHelper {
/**
* calculate with strings
* eg: "2 + 4 * 6 / 8" will result in 5
* @param string the operation
* @return float the calculated result
*/
public function render( $value = NULL )
{
if ( NULL === $value ) {
$value = $this->renderChildren();
}
// trim white spaces
$mathString = trim( $value );
// remove any non-numbers chars; exception for math operators and 'x'
$mathString = preg_replace( '[^0-9\+-\*x\/\(\) ]', '', $mathString );
// replace x with *
$mathString = str_replace( 'x', '*', $mathString );
// compute
$compute = create_function("", "return (" . $mathString . ");" );
return 0 + $compute();
}
}
?>
More information about the TYPO3-project-typo3v4mvc
mailing list