/Classes/ViewHelpers/Format/AgeViewHelper.php
PHP | 93 lines | 39 code | 8 blank | 46 comment | 3 complexity | 693ebbf1ddf19d6697cb757c580e4c18 MD5 | raw file
- <?php
- namespace TYPO3\BccVoting\ViewHelpers\Format;
- /* *
- * This script belongs to the FLOW3 package "BccVoting". *
- * *
- * It is free software; you can redistribute it and/or modify it under *
- * the terms of the GNU Lesser General Public License, either version 3 *
- * of the License, or (at your option) any later version. *
- * *
- * The TYPO3 project - inspiring people to share! *
- * */
- /**
- * Renders the age of a DateTime object
- *
- * = Examples =
- *
- * <code>
- * <f:format.age>{invoice.date}</f:format.age>
- * </code>
- * <output>
- * 3 days
- * (depending on the invoice date)
- * </output>
- *
- * <code title="inline syntax>
- * {invoice.date -> f:format.age()}
- * </code>
- * <output>
- * -1 year
- * (depending on the invoice date)
- * </output>
- *
- * @api
- */
- class AgeViewHelper extends \TYPO3\Fluid\Core\ViewHelper\AbstractViewHelper {
- /**
- * @var array
- */
- protected $labels = array(
- 'y' => array('year', 'years'),
- 'm' => array('month', 'months'),
- 'd' => array('day', 'days'),
- 'h' => array('hour', 'hours'),
- 'i' => array('minute', 'minutes'),
- 's' => array('second', 'seconds')
- );
- /**
- * Renders the output of this view helper
- *
- * @return string Identity
- * @api
- */
- public function render() {
- $date = $this->renderChildren();
- if (!$date instanceof \DateTime) {
- throw new \TYPO3\Fluid\Exception('f:format.age expects a DateTime object, ' . \gettype($date) . ' given.', 1286531071);
- }
- return $this->formatDateDifference($date);
- }
- /**
- * @param \DateTime $startDate
- * @param \DateTime $endDate
- * @return string
- */
- protected function formatDateDifference(\DateTime $startDate, \DateTime $endDate = NULL) {
- if($endDate === NULL) {
- $endDate = new \DateTime();
- }
- $dateInterval = $endDate->diff($startDate);
- $doPlural = function($nb,$str){return $nb>1?$str.'s':$str;}; // adds plurals
- $format = '';
- foreach($this->labels as $formatKey => $label) {
- if ($dateInterval->$formatKey === 0) {
- continue;
- }
- $format .= '%' . $formatKey . ' ';
- $format .= $dateInterval->$formatKey > 1 ? $label[1] : $label[0];
- $format .= ' ';
- break;
- }
- $format = '%r' . rtrim($format);
- return $dateInterval->format($format);
- }
- }
- ?>