PageRenderTime 46ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/Classes/ViewHelpers/Format/AgeViewHelper.php

https://bitbucket.org/skorpi/typo3.voting
PHP | 93 lines | 39 code | 8 blank | 46 comment | 3 complexity | 693ebbf1ddf19d6697cb757c580e4c18 MD5 | raw file
  1. <?php
  2. namespace TYPO3\BccVoting\ViewHelpers\Format;
  3. /* *
  4. * This script belongs to the FLOW3 package "BccVoting". *
  5. * *
  6. * It is free software; you can redistribute it and/or modify it under *
  7. * the terms of the GNU Lesser General Public License, either version 3 *
  8. * of the License, or (at your option) any later version. *
  9. * *
  10. * The TYPO3 project - inspiring people to share! *
  11. * */
  12. /**
  13. * Renders the age of a DateTime object
  14. *
  15. * = Examples =
  16. *
  17. * <code>
  18. * <f:format.age>{invoice.date}</f:format.age>
  19. * </code>
  20. * <output>
  21. * 3 days
  22. * (depending on the invoice date)
  23. * </output>
  24. *
  25. * <code title="inline syntax>
  26. * {invoice.date -> f:format.age()}
  27. * </code>
  28. * <output>
  29. * -1 year
  30. * (depending on the invoice date)
  31. * </output>
  32. *
  33. * @api
  34. */
  35. class AgeViewHelper extends \TYPO3\Fluid\Core\ViewHelper\AbstractViewHelper {
  36. /**
  37. * @var array
  38. */
  39. protected $labels = array(
  40. 'y' => array('year', 'years'),
  41. 'm' => array('month', 'months'),
  42. 'd' => array('day', 'days'),
  43. 'h' => array('hour', 'hours'),
  44. 'i' => array('minute', 'minutes'),
  45. 's' => array('second', 'seconds')
  46. );
  47. /**
  48. * Renders the output of this view helper
  49. *
  50. * @return string Identity
  51. * @api
  52. */
  53. public function render() {
  54. $date = $this->renderChildren();
  55. if (!$date instanceof \DateTime) {
  56. throw new \TYPO3\Fluid\Exception('f:format.age expects a DateTime object, ' . \gettype($date) . ' given.', 1286531071);
  57. }
  58. return $this->formatDateDifference($date);
  59. }
  60. /**
  61. * @param \DateTime $startDate
  62. * @param \DateTime $endDate
  63. * @return string
  64. */
  65. protected function formatDateDifference(\DateTime $startDate, \DateTime $endDate = NULL) {
  66. if($endDate === NULL) {
  67. $endDate = new \DateTime();
  68. }
  69. $dateInterval = $endDate->diff($startDate);
  70. $doPlural = function($nb,$str){return $nb>1?$str.'s':$str;}; // adds plurals
  71. $format = '';
  72. foreach($this->labels as $formatKey => $label) {
  73. if ($dateInterval->$formatKey === 0) {
  74. continue;
  75. }
  76. $format .= '%' . $formatKey . ' ';
  77. $format .= $dateInterval->$formatKey > 1 ? $label[1] : $label[0];
  78. $format .= ' ';
  79. break;
  80. }
  81. $format = '%r' . rtrim($format);
  82. return $dateInterval->format($format);
  83. }
  84. }
  85. ?>