TYPO3 CMS  TYPO3_7-6
RendererRegistry.php
Go to the documentation of this file.
1 <?php
3 
4 /*
5  * This file is part of the TYPO3 CMS project.
6  *
7  * It is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU General Public License, either version 2
9  * of the License, or any later version.
10  *
11  * For the full copyright and license information, please read the
12  * LICENSE.txt file that was distributed with this source code.
13  *
14  * The TYPO3 project - inspiring people to share!
15  */
16 
19 
24 {
30  protected $classNames = [];
31 
37  protected $instances = null;
38 
44  public static function getInstance()
45  {
46  return GeneralUtility::makeInstance(\TYPO3\CMS\Core\Resource\Rendering\RendererRegistry::class);
47  }
48 
55  public function registerRendererClass($className)
56  {
57  if (!class_exists($className)) {
58  throw new \InvalidArgumentException('The class "' . $className . '" you are trying to register is not available', 1411840171);
59  } elseif (!in_array(\TYPO3\CMS\Core\Resource\Rendering\FileRendererInterface::class, class_implements($className), true)) {
60  throw new \InvalidArgumentException('The renderer needs to implement the FileRendererInterface', 1411840172);
61  } else {
62  $this->classNames[] = $className;
63  }
64  }
65 
71  public function getRendererInstances()
72  {
73  if ($this->instances === null) {
74  $this->instances = [];
75 
76  // As the result is in reverse order we need to reverse
77  // the array before processing to keep the items with same
78  // priority in the same order as they were added to the registry.
79  $classNames = array_reverse($this->classNames);
80  foreach ($classNames as $className) {
82  $object = $this->createRendererInstance($className);
83  $this->instances[] = $object;
84  }
85 
86  if (count($this->instances) > 1) {
87  usort($this->instances, [$this, 'compareRendererPriority']);
88  }
89  }
90  return $this->instances;
91  }
92 
99  protected function createRendererInstance($className)
100  {
101  return GeneralUtility::makeInstance($className);
102  }
103 
114  protected function compareRendererPriority(FileRendererInterface $rendererA, FileRendererInterface $rendererB)
115  {
116  return $rendererB->getPriority() - $rendererA->getPriority();
117  }
118 
125  public function getRenderer(FileInterface $file)
126  {
127  $matchingFileRenderer = null;
128 
130  foreach ($this->getRendererInstances() as $fileRenderer) {
131  if ($fileRenderer->canRender($file)) {
132  $matchingFileRenderer = $fileRenderer;
133  break;
134  }
135  }
136  return $matchingFileRenderer;
137  }
138 }
compareRendererPriority(FileRendererInterface $rendererA, FileRendererInterface $rendererB)