Conditions | 8 |
Paths | 80 |
Total Lines | 56 |
Code Lines | 33 |
Lines | 0 |
Ratio | 0 % |
Changes | 2 | ||
Bugs | 0 | Features | 0 |
Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.
For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.
Commonly applied refactorings include:
If many parameters/temporary variables are present:
1 | <?php |
||
53 | public static function renderPluginTemplate(string $templatePath, array $params = []): Markup |
||
54 | { |
||
55 | $exception = null; |
||
56 | $htmlText = ''; |
||
57 | // Stash the old template mode, and set it Control Panel template mode |
||
58 | $oldMode = Craft::$app->view->getTemplateMode(); |
||
59 | // Look for a frontend template to render first |
||
60 | try { |
||
61 | Craft::$app->view->setTemplateMode(View::TEMPLATE_MODE_SITE); |
||
62 | } catch (Exception $exception) { |
||
63 | Craft::error($exception->getMessage(), __METHOD__); |
||
64 | } |
||
65 | |||
66 | // Render the template with our vars passed in |
||
67 | try { |
||
68 | $htmlText = Craft::$app->view->renderTemplate('recipe/' . $templatePath, $params); |
||
69 | $templateRendered = true; |
||
70 | } catch (\Exception $exception) { |
||
71 | $templateRendered = false; |
||
72 | } |
||
73 | |||
74 | // If no frontend template was found, try our built-in template |
||
75 | if (!$templateRendered) { |
||
76 | try { |
||
77 | Craft::$app->view->setTemplateMode(View::TEMPLATE_MODE_CP); |
||
78 | } catch (Exception $exception) { |
||
79 | Craft::error($exception->getMessage(), __METHOD__); |
||
80 | } |
||
81 | |||
82 | // Render the template with our vars passed in |
||
83 | try { |
||
84 | $htmlText = Craft::$app->view->renderTemplate('recipe/' . $templatePath, $params); |
||
85 | $templateRendered = true; |
||
86 | } catch (\Exception $exception) { |
||
87 | $templateRendered = false; |
||
88 | } |
||
89 | } |
||
90 | |||
91 | // Only if the template didn't render at all should we log an error |
||
92 | if (!$templateRendered) { |
||
93 | $htmlText = Craft::t( |
||
94 | 'recipe', |
||
95 | 'Error rendering `{template}` -> {error}', |
||
96 | ['template' => $templatePath, 'error' => $exception->getMessage()] |
||
97 | ); |
||
98 | Craft::error($htmlText, __METHOD__); |
||
99 | } |
||
100 | |||
101 | // Restore the old template mode |
||
102 | try { |
||
103 | Craft::$app->view->setTemplateMode($oldMode); |
||
104 | } catch (Exception $exception) { |
||
105 | Craft::error($exception->getMessage(), __METHOD__); |
||
106 | } |
||
107 | |||
108 | return Template::raw($htmlText); |
||
109 | } |
||
111 |