Completed
Pull Request — 1.2 (#12)
by David
07:52
created

AutoChainRenderer::initRenderersList()   A

Complexity

Conditions 5
Paths 9

Size

Total Lines 28

Duplication

Lines 10
Ratio 35.71 %

Importance

Changes 0
Metric Value
dl 10
loc 28
rs 9.1608
c 0
b 0
f 0
cc 5
nc 9
nop 0
1
<?php
2
/*
3
 * Copyright (c) 2013 David Negrier
4
 *
5
 * See the file LICENSE.txt for copying permission.
6
 */
7
8
namespace Mouf\Html\Renderer;
9
10
use Mouf\Utils\Cache\CacheInterface;
11
use Mouf\MoufManager;
12
13
/**
14
 * This class is a renderer that renders objects using other renderers.
15
 * This renderer will automatically detect the renderers to be included.
16
 * They must extend the ChainableRendererInterface interface.
17
 *
18
 * @author David Négrier <[email protected]>
19
 */
20
class AutoChainRenderer implements CanSetTemplateRendererInterface
21
{
22
23
    /**
24
     * @var ChainableRendererInterface
25
     */
26
    private $templateRenderer;
27
    /**
28
     * @var ChainableRendererInterface[]
29
     */
30
    private $packageRenderers = array();
31
    /**
32
     * @var ChainableRendererInterface[]
33
     */
34
    private $customRenderers = array();
35
36
    private $cacheService;
37
38
    private $initDone = false;
39
    /**
40
     * @var string
41
     */
42
    private $uniqueName;
43
44
    /**
45
     *
46
     * @param CacheInterface $cacheService This service is used to speed up the mapping between the object and the template.
47
     */
48
    public function __construct(CacheInterface $cacheService, string $uniqueName = 'autochain-renderer')
49
    {
50
        $this->cacheService = $cacheService;
51
        $this->uniqueName = $uniqueName;
52
    }
53
54
    /**
55
     * (non-PHPdoc)
56
     * @see \Mouf\Html\Renderer\RendererInterface::render()
57
     */
58
    public function render($object, $context = null)
59
    {
60
        $renderer = $this->getRenderer($object, $context);
61
        if ($renderer == null) {
62
            throw new \Exception("Renderer not found. Unable to find renderer for object of class '".get_class($object)."'. Path tested: ".$this->getRendererDebugMessage($object, $context));
63
        }
64
        $renderer->render($object, $context);
65
    }
66
67
    /**
68
     * Sets the renderer associated to the template.
69
     * There should be only one if these renderers.
70
     * It is the role of the template to subscribe to this renderer.
71
     *
72
     * @param RendererInterface $templateRenderer
73
     */
74
    public function setTemplateRenderer(RendererInterface $templateRenderer)
75
    {
76
        $this->templateRenderer = $templateRenderer;
0 ignored issues
show
Documentation Bug introduced by
$templateRenderer is of type object<Mouf\Html\Renderer\RendererInterface>, but the property $templateRenderer was declared to be of type object<Mouf\Html\Rendere...nableRendererInterface>. Are you sure that you always receive this specific sub-class here, or does it make sense to add an instanceof check?

Our type inference engine has found a suspicous assignment of a value to a property. This check raises an issue when a value that can be of a given class or a super-class is assigned to a property that is type hinted more strictly.

Either this assignment is in error or an instanceof check should be added for that assignment.

class Alien {}

class Dalek extends Alien {}

class Plot
{
    /** @var  Dalek */
    public $villain;
}

$alien = new Alien();
$plot = new Plot();
if ($alien instanceof Dalek) {
    $plot->villain = $alien;
}
Loading history...
77
    }
78
79
    private function getRenderer($object, $context = null)
80
    {
81
        $cacheKey = "chainRendererByClass_".$this->uniqueName."/".$this->templateRenderer->getUniqueName()."/".$this->getTemplateRendererInstanceName()."/".get_class($object)."/".$context;
0 ignored issues
show
Bug introduced by
The method getUniqueName() does not seem to exist on object<Mouf\Html\Rendere...nableRendererInterface>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
Bug introduced by
The method getTemplateRendererInstanceName() does not exist on Mouf\Html\Renderer\AutoChainRenderer. Did you maybe mean render()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
82
83
        $rendererSource = $this->cacheService->get($cacheKey);
84
        if ($rendererSource != null) {
85
            $source = $rendererSource['source'];
86
            $rendererIndex = $rendererSource['index'];
87
            switch ($source) {
88
                case 'customRenderers':
89
                    return $this->customRenderers[$rendererIndex];
90
                case 'templateRenderer':
91
                    return $this->templateRenderer;
92
                case 'packageRenderers':
93
                    return $this->packageRenderers[$rendererIndex];
94
                default:
95
                    throw new \RuntimeException('Unexpected renderer source: "'.$source.'"');
96
            }
97
        }
98
99
        $this->initRenderersList();
100
101
        $isCachable = true;
102
        $foundRenderer = null;
103
        $source = null;
104
        $rendererIndex = null;
105
106
        do {
107 View Code Duplication
            foreach ($this->customRenderers as $key => $renderer) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
108
                /* @var $renderer ChainableRendererInterface */
109
                $result = $renderer->canRender($object, $context);
110
                if ($result == ChainableRendererInterface::CAN_RENDER_OBJECT || $result == ChainableRendererInterface::CANNOT_RENDER_OBJECT) {
111
                    $isCachable = false;
112
                }
113
                if ($result == ChainableRendererInterface::CAN_RENDER_OBJECT || $result == ChainableRendererInterface::CAN_RENDER_CLASS) {
114
                    $foundRenderer = $renderer;
115
                    $source = 'customRenderers';
116
                    $rendererIndex = $key;
117
                    break 2;
118
                }
119
            }
120
121
            /* @var $renderer ChainableRendererInterface */
122
            if ($this->templateRenderer) {
123
                $result = $this->templateRenderer->canRender($object, $context);
124
                if ($result == ChainableRendererInterface::CAN_RENDER_OBJECT || $result == ChainableRendererInterface::CANNOT_RENDER_OBJECT) {
125
                    $isCachable = false;
126
                }
127
                if ($result == ChainableRendererInterface::CAN_RENDER_OBJECT || $result == ChainableRendererInterface::CAN_RENDER_CLASS) {
128
                    $foundRenderer = $this->templateRenderer;
129
                    $source = 'templateRenderer';
130
                    break;
131
                }
132
            }
133
134 View Code Duplication
            foreach ($this->packageRenderers as $key => $renderer) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
135
                /* @var $renderer ChainableRendererInterface */
136
                $result = $renderer->canRender($object, $context);
137
                if ($result == ChainableRendererInterface::CAN_RENDER_OBJECT || $result == ChainableRendererInterface::CANNOT_RENDER_OBJECT) {
138
                    $isCachable = false;
139
                }
140
                if ($result == ChainableRendererInterface::CAN_RENDER_OBJECT || $result == ChainableRendererInterface::CAN_RENDER_CLASS) {
141
                    $foundRenderer = $renderer;
142
                    $source = 'packageRenderers';
143
                    $rendererIndex = $key;
144
                    break 2;
145
                }
146
            }
147
        } while (false);
148
149
        if ($isCachable && $foundRenderer) {
150
            $this->cacheService->set($cacheKey, [
151
                'source' => $source,
152
                'index' => $rendererIndex
153
            ]);
154
        }
155
156
        return $foundRenderer;
157
    }
158
159
    /**
160
     * Returns a string explaining the steps done to find the renderer.
161
     *
162
     * @param  object $object
163
     * @param  string $context
164
     * @return string
165
     */
166
    private function getRendererDebugMessage($object, $context = null)
167
    {
168
        $debugMessage = '';
169
170
        $this->initRenderersList();
171
172
        $isCachable = true;
0 ignored issues
show
Unused Code introduced by
$isCachable is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
173
        $foundRenderer = null;
0 ignored issues
show
Unused Code introduced by
$foundRenderer is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
174
175
        do {
176 View Code Duplication
            foreach ($this->customRenderers as $renderer) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
177
                /* @var $renderer ChainableRendererInterface */
178
179
                $debugMessage .= $renderer->debugCanRender($object, $context);
180
                $result = $renderer->canRender($object, $context);
181
                if ($result == ChainableRendererInterface::CAN_RENDER_OBJECT || $result == ChainableRendererInterface::CANNOT_RENDER_OBJECT) {
182
                    $isCachable = false;
0 ignored issues
show
Unused Code introduced by
$isCachable is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
183
                }
184
                if ($result == ChainableRendererInterface::CAN_RENDER_OBJECT || $result == ChainableRendererInterface::CAN_RENDER_CLASS) {
185
                    $foundRenderer = $renderer;
0 ignored issues
show
Unused Code introduced by
$foundRenderer is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
186
                    break 2;
187
                }
188
            }
189
190
            /* @var $renderer ChainableRendererInterface */
191
            if ($this->templateRenderer) {
192
                $debugMessage .= $this->templateRenderer->debugCanRender($object, $context);
193
                $result = $this->templateRenderer->canRender($object, $context);
194
                if ($result == ChainableRendererInterface::CAN_RENDER_OBJECT || $result == ChainableRendererInterface::CANNOT_RENDER_OBJECT) {
195
                    $isCachable = false;
0 ignored issues
show
Unused Code introduced by
$isCachable is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
196
                }
197
                if ($result == ChainableRendererInterface::CAN_RENDER_OBJECT || $result == ChainableRendererInterface::CAN_RENDER_CLASS) {
198
                    $foundRenderer = $this->templateRenderer;
0 ignored issues
show
Unused Code introduced by
$foundRenderer is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
199
                    break;
200
                }
201
            }
202
203 View Code Duplication
            foreach ($this->packageRenderers as $renderer) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
204
                /* @var $renderer ChainableRendererInterface */
205
206
                $debugMessage .= $renderer->debugCanRender($object, $context);
207
                $result = $renderer->canRender($object, $context);
208
                if ($result == ChainableRendererInterface::CAN_RENDER_OBJECT || $result == ChainableRendererInterface::CANNOT_RENDER_OBJECT) {
209
                    $isCachable = false;
0 ignored issues
show
Unused Code introduced by
$isCachable is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
210
                }
211
                if ($result == ChainableRendererInterface::CAN_RENDER_OBJECT || $result == ChainableRendererInterface::CAN_RENDER_CLASS) {
212
                    $foundRenderer = $renderer;
0 ignored issues
show
Unused Code introduced by
$foundRenderer is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
213
                    break 2;
214
                }
215
            }
216
217
        } while (false);
218
		
219
		return $debugMessage;
220
	}
221
	
222
	/**
223
	 * Initializes the renderers list (from cache if available)
224
	 */
225
	private function initRenderersList() {
226
        if (!$this->initDone) {
227
            $moufManager = MoufManager::getMoufManager();
228
            // TODO: suboptimal. findInstanceName is not efficient.
229
            $instanceName = $this->getInstanceName();
0 ignored issues
show
Bug introduced by
The method getInstanceName() does not seem to exist on object<Mouf\Html\Renderer\AutoChainRenderer>.

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
230
            $renderersList = $this->cacheService->get("chainRenderer_" . $instanceName);
231
            if ($renderersList === null) {
232
                $renderersList = $this->queryRenderersList();
233
                $this->cacheService->set("chainRenderer_" . $instanceName, $renderersList);
234
            }
235
236 View Code Duplication
            if (isset($renderersList[ChainableRendererInterface::TYPE_CUSTOM])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
237
                $this->customRenderers = array_map(function ($name) use ($moufManager) {
238
                    return $moufManager->getInstance($name);
239
                }, $renderersList[ChainableRendererInterface::TYPE_CUSTOM]);
240
            }
241
242 View Code Duplication
            if (isset($renderersList[ChainableRendererInterface::TYPE_PACKAGE])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
243
                $this->packageRenderers = array_map(function ($name) use ($moufManager) {
244
                    return $moufManager->getInstance($name);
245
                }, $renderersList[ChainableRendererInterface::TYPE_PACKAGE]);
246
            }
247
248
            // Note: We ignore template renderers on purpose.
249
250
            $this->initDone = true;
251
        }
252
	}
253
	
254
	/**
255
	 * Returns an orderered list of renderers instance name to apply, separated by "type".
256
	 * 
257
	 * @return array<string, string[]>
0 ignored issues
show
Documentation introduced by
The doc-type array<string, could not be parsed: Expected ">" at position 5, but found "end of type". (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
258
	 */
259
	private function queryRenderersList() {
260
		$moufManager = MoufManager::getMoufManager();
261
		$renderersNames = $moufManager->findInstances('Mouf\\Html\\Renderer\\ChainableRendererInterface');
262
		
263
		foreach ($renderersNames as $name) {
264
			$renderers[$name] = $moufManager->getInstance($name);
0 ignored issues
show
Coding Style Comprehensibility introduced by
$renderers was never initialized. Although not strictly required by PHP, it is generally a good practice to add $renderers = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
265
		}
266
		
267
		$renderersByType = array();
268
		foreach ($renderers as $name => $renderer) {
0 ignored issues
show
Bug introduced by
The variable $renderers does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
269
			/* @var $renderer ChainableRendererInterface */
270
			$renderersByType[$renderer->getRendererType()][] = $name;
0 ignored issues
show
Bug introduced by
The method getRendererType() does not exist on Mouf\Html\Renderer\ChainableRendererInterface. Did you maybe mean render()?

This check marks calls to methods that do not seem to exist on an object.

This is most likely the result of a method being renamed without all references to it being renamed likewise.

Loading history...
271
		}
272
		
273
		// Now, let's sort the renderers by priority (highest first).
274
		$renderersByType = array_map(function(array $innerArray) use ($renderers) {
0 ignored issues
show
Bug introduced by
The variable $renderers does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
275
			usort($innerArray, function($name1, $name2) use ($renderers) {
276
				$item1 = $renderers[$name1];
277
				$item2 = $renderers[$name2];
278
				return $item2->getPriority() - $item1->getPriority();
279
			});
280
			return $innerArray;
281
		}, $renderersByType);
282
		
283
		return $renderersByType;
284
	}
285
}
286