File SitemapService.php
has 323 lines of code (exceeds 250 allowed). Consider refactoring. Open
<?php
namespace studioespresso\seofields\services;
use Craft;
The class SitemapService has an overall complexity of 57 which is very high. The configured complexity threshold is 50. Open
class SitemapService extends Component
{
public const SITEMAP_CACHE_KEY = 'seofields_cache_sitemaps';
public function shouldRenderBySiteId(Site $site)
- Exclude checks
Method _addElementsToSitemap
has 49 lines of code (exceeds 25 allowed). Consider refactoring. Open
private function _addElementsToSitemap($entries, $settings)
{
$data = [];
$data[] = '<?xml version="1.0" encoding="UTF-8"?>';
$data[] = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xhtml="http://www.w3.org/1999/xhtml" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9">';
Method getSitemapData
has 44 lines of code (exceeds 25 allowed). Consider refactoring. Open
public function getSitemapData($siteId, $type, $sectionId)
{
$settings = $this->getSettingsBySiteId($siteId);
$data = [];
switch ($type) {
Function _addElementsToSitemap
has a Cognitive Complexity of 14 (exceeds 5 allowed). Consider refactoring. Open
private function _addElementsToSitemap($entries, $settings)
{
$data = [];
$data[] = '<?xml version="1.0" encoding="UTF-8"?>';
$data[] = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xhtml="http://www.w3.org/1999/xhtml" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9">';
- Read upRead up
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Method getSitemapIndex
has 34 lines of code (exceeds 25 allowed). Consider refactoring. Open
public function getSitemapIndex($data)
{
$currentSite = Craft::$app->getSites()->getCurrentSite();
$cacheDependency = new TagDependency([
'tags' => [
Method shouldRenderBySiteId
has 28 lines of code (exceeds 25 allowed). Consider refactoring. Open
public function shouldRenderBySiteId(Site $site)
{
$data = SeoFields::$plugin->defaultsService->getRecordForSiteId($site->id);
$sitemapSettings = Json::decode($data->sitemap);
if (!$sitemapSettings) {
Function shouldRenderBySiteId
has a Cognitive Complexity of 7 (exceeds 5 allowed). Consider refactoring. Open
public function shouldRenderBySiteId(Site $site)
{
$data = SeoFields::$plugin->defaultsService->getRecordForSiteId($site->id);
$sitemapSettings = Json::decode($data->sitemap);
if (!$sitemapSettings) {
- Read upRead up
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Function getSitemapData
has a Cognitive Complexity of 6 (exceeds 5 allowed). Consider refactoring. Open
public function getSitemapData($siteId, $type, $sectionId)
{
$settings = $this->getSettingsBySiteId($siteId);
$data = [];
switch ($type) {
- Read upRead up
Cognitive Complexity
Cognitive Complexity is a measure of how difficult a unit of code is to intuitively understand. Unlike Cyclomatic Complexity, which determines how difficult your code will be to test, Cognitive Complexity tells you how difficult your code will be to read and comprehend.
A method's cognitive complexity is based on a few simple rules:
- Code is not considered more complex when it uses shorthand that the language provides for collapsing multiple statements into one
- Code is considered more complex for each "break in the linear flow of the code"
- Code is considered more complex when "flow breaking structures are nested"
Further reading
Refactor this function to reduce its Cognitive Complexity from 16 to the 15 allowed. Open
private function _addElementsToSitemap($entries, $settings)
- Read upRead up
- Exclude checks
Cognitive Complexity is a measure of how hard the control flow of a function is to understand. Functions with high Cognitive Complexity will be difficult to maintain.
See
The class SitemapService has a coupling between objects value of 14. Consider to reduce the number of dependencies under 13. Open
class SitemapService extends Component
{
public const SITEMAP_CACHE_KEY = 'seofields_cache_sitemaps';
public function shouldRenderBySiteId(Site $site)
- Read upRead up
- Exclude checks
CouplingBetweenObjects
Since: 1.1.0
A class with too many dependencies has negative impacts on several quality aspects of a class. This includes quality criteria like stability, maintainability and understandability
Example
class Foo {
/**
* @var \foo\bar\X
*/
private $x = null;
/**
* @var \foo\bar\Y
*/
private $y = null;
/**
* @var \foo\bar\Z
*/
private $z = null;
public function setFoo(\Foo $foo) {}
public function setBar(\Bar $bar) {}
public function setBaz(\Baz $baz) {}
/**
* @return \SplObjectStorage
* @throws \OutOfRangeException
* @throws \InvalidArgumentException
* @throws \ErrorException
*/
public function process(\Iterator $it) {}
// ...
}
Source https://phpmd.org/rules/design.html#couplingbetweenobjects
Avoid using static access to class '\yii\caching\TagDependency' in method 'clearCaches'. Open
TagDependency::invalidate(
Craft::$app->getCache(),
$tags
);
- Read upRead up
- Exclude checks
StaticAccess
Since: 1.4.0
Static access causes unexchangeable dependencies to other classes and leads to hard to test code. Avoid using static access at all costs and instead inject dependencies through the constructor. The only case when static access is acceptable is when used for factory methods.
Example
class Foo
{
public function bar()
{
Bar::baz();
}
}
Source https://phpmd.org/rules/cleancode.html#staticaccess
Avoid using static access to class '\craft\helpers\UrlHelper' in method '_addItemToIndex'. Open
$data[] = UrlHelper::siteUrl(htmlentities('/sitemap_' . $site->id . '_' . $elementName . '_' . $type->id . '_' . strtolower($type->handle) . '.xml'), null, null, $site->id);
- Read upRead up
- Exclude checks
StaticAccess
Since: 1.4.0
Static access causes unexchangeable dependencies to other classes and leads to hard to test code. Avoid using static access at all costs and instead inject dependencies through the constructor. The only case when static access is acceptable is when used for factory methods.
Example
class Foo
{
public function bar()
{
Bar::baz();
}
}
Source https://phpmd.org/rules/cleancode.html#staticaccess
Avoid using static access to class '\craft\helpers\Db' in method '_addElementsToSitemap'. Open
Db::parseParam("JSON_EXTRACT(c.$field, '$.allowIndexing')", ":empty:"),
- Read upRead up
- Exclude checks
StaticAccess
Since: 1.4.0
Static access causes unexchangeable dependencies to other classes and leads to hard to test code. Avoid using static access at all costs and instead inject dependencies through the constructor. The only case when static access is acceptable is when used for factory methods.
Example
class Foo
{
public function bar()
{
Bar::baz();
}
}
Source https://phpmd.org/rules/cleancode.html#staticaccess
Avoid using static access to class '\craft\helpers\UrlHelper' in method '_addElementsToSitemap'. Open
$url = UrlHelper::siteUrl($site['uri'], null, null, $site['siteId']);
- Read upRead up
- Exclude checks
StaticAccess
Since: 1.4.0
Static access causes unexchangeable dependencies to other classes and leads to hard to test code. Avoid using static access at all costs and instead inject dependencies through the constructor. The only case when static access is acceptable is when used for factory methods.
Example
class Foo
{
public function bar()
{
Bar::baz();
}
}
Source https://phpmd.org/rules/cleancode.html#staticaccess
The method _shouldRenderProducts uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
return false;
}
- Read upRead up
- Exclude checks
ElseExpression
Since: 1.4.0
An if expression with an else branch is basically not necessary. You can rewrite the conditions in a way that the else clause is not necessary and the code becomes simpler to read. To achieve this, use early return statements, though you may need to split the code it several smaller methods. For very simple assignments you could also use the ternary operations.
Example
class Foo
{
public function bar($flag)
{
if ($flag) {
// one branch
} else {
// another branch
}
}
}
Source https://phpmd.org/rules/cleancode.html#elseexpression
Avoid using static access to class '\craft\helpers\Json' in method 'shouldRenderBySiteId'. Open
$sitemapSettings = Json::decode($data->sitemap);
- Read upRead up
- Exclude checks
StaticAccess
Since: 1.4.0
Static access causes unexchangeable dependencies to other classes and leads to hard to test code. Avoid using static access at all costs and instead inject dependencies through the constructor. The only case when static access is acceptable is when used for factory methods.
Example
class Foo
{
public function bar()
{
Bar::baz();
}
}
Source https://phpmd.org/rules/cleancode.html#staticaccess
Avoid using static access to class '\craft\elements\Entry' in method '_addSectionsToIndex'. Open
$entry = Entry::findOne(['sectionId' => $id, 'orderBy' => 'dateUpdated DESC']);
- Read upRead up
- Exclude checks
StaticAccess
Since: 1.4.0
Static access causes unexchangeable dependencies to other classes and leads to hard to test code. Avoid using static access at all costs and instead inject dependencies through the constructor. The only case when static access is acceptable is when used for factory methods.
Example
class Foo
{
public function bar()
{
Bar::baz();
}
}
Source https://phpmd.org/rules/cleancode.html#staticaccess
The method getSitemapIndex uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
$duration = 1;
}
- Read upRead up
- Exclude checks
ElseExpression
Since: 1.4.0
An if expression with an else branch is basically not necessary. You can rewrite the conditions in a way that the else clause is not necessary and the code becomes simpler to read. To achieve this, use early return statements, though you may need to split the code it several smaller methods. For very simple assignments you could also use the ternary operations.
Example
class Foo
{
public function bar($flag)
{
if ($flag) {
// one branch
} else {
// another branch
}
}
}
Source https://phpmd.org/rules/cleancode.html#elseexpression
The method _shouldRenderCategories uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
return false;
}
- Read upRead up
- Exclude checks
ElseExpression
Since: 1.4.0
An if expression with an else branch is basically not necessary. You can rewrite the conditions in a way that the else clause is not necessary and the code becomes simpler to read. To achieve this, use early return statements, though you may need to split the code it several smaller methods. For very simple assignments you could also use the ternary operations.
Example
class Foo
{
public function bar($flag)
{
if ($flag) {
// one branch
} else {
// another branch
}
}
}
Source https://phpmd.org/rules/cleancode.html#elseexpression
Avoid using static access to class '\craft\commerce\elements\Product' in method 'getSitemapData'. Open
$data = Product::findAll([
'siteId' => $siteId,
'typeId' => $sectionId,
'orderBy' => 'dateUpdated DESC',
]);
- Read upRead up
- Exclude checks
StaticAccess
Since: 1.4.0
Static access causes unexchangeable dependencies to other classes and leads to hard to test code. Avoid using static access at all costs and instead inject dependencies through the constructor. The only case when static access is acceptable is when used for factory methods.
Example
class Foo
{
public function bar()
{
Bar::baz();
}
}
Source https://phpmd.org/rules/cleancode.html#staticaccess
Avoid using static access to class '\craft\helpers\Db' in method '_addElementsToSitemap'. Open
Db::parseParam("JSON_EXTRACT(c.$field, '$.allowIndexing')", "yes"),
- Read upRead up
- Exclude checks
StaticAccess
Since: 1.4.0
Static access causes unexchangeable dependencies to other classes and leads to hard to test code. Avoid using static access at all costs and instead inject dependencies through the constructor. The only case when static access is acceptable is when used for factory methods.
Example
class Foo
{
public function bar()
{
Bar::baz();
}
}
Source https://phpmd.org/rules/cleancode.html#staticaccess
Avoid using static access to class '\craft\elements\Category' in method '_addCategoriesToIndex'. Open
$entry = Category::findOne(['groupId' => $type->id, 'orderBy' => 'dateUpdated DESC']);
- Read upRead up
- Exclude checks
StaticAccess
Since: 1.4.0
Static access causes unexchangeable dependencies to other classes and leads to hard to test code. Avoid using static access at all costs and instead inject dependencies through the constructor. The only case when static access is acceptable is when used for factory methods.
Example
class Foo
{
public function bar()
{
Bar::baz();
}
}
Source https://phpmd.org/rules/cleancode.html#staticaccess
The method shouldRenderBySiteId uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
return false;
}
- Read upRead up
- Exclude checks
ElseExpression
Since: 1.4.0
An if expression with an else branch is basically not necessary. You can rewrite the conditions in a way that the else clause is not necessary and the code becomes simpler to read. To achieve this, use early return statements, though you may need to split the code it several smaller methods. For very simple assignments you could also use the ternary operations.
Example
class Foo
{
public function bar($flag)
{
if ($flag) {
// one branch
} else {
// another branch
}
}
}
Source https://phpmd.org/rules/cleancode.html#elseexpression
Avoid using static access to class '\craft\commerce\elements\Product' in method '_addProductsToIndex'. Open
$entry = Product::findOne(['typeId' => $type->id, 'orderBy' => 'dateUpdated DESC']);
- Read upRead up
- Exclude checks
StaticAccess
Since: 1.4.0
Static access causes unexchangeable dependencies to other classes and leads to hard to test code. Avoid using static access at all costs and instead inject dependencies through the constructor. The only case when static access is acceptable is when used for factory methods.
Example
class Foo
{
public function bar()
{
Bar::baz();
}
}
Source https://phpmd.org/rules/cleancode.html#staticaccess
Avoid using static access to class '\craft\elements\Category' in method 'getSitemapData'. Open
$data = Category::findAll([
'siteId' => $siteId,
'groupId' => $sectionId,
'orderBy' => 'dateUpdated DESC',
]);
- Read upRead up
- Exclude checks
StaticAccess
Since: 1.4.0
Static access causes unexchangeable dependencies to other classes and leads to hard to test code. Avoid using static access at all costs and instead inject dependencies through the constructor. The only case when static access is acceptable is when used for factory methods.
Example
class Foo
{
public function bar()
{
Bar::baz();
}
}
Source https://phpmd.org/rules/cleancode.html#staticaccess
Avoid using static access to class '\craft\elements\Entry' in method 'getSitemapData'. Open
$data = Entry::findAll([
'siteId' => $siteId,
'sectionId' => $sectionId,
'orderBy' => 'dateUpdated DESC',
]);
- Read upRead up
- Exclude checks
StaticAccess
Since: 1.4.0
Static access causes unexchangeable dependencies to other classes and leads to hard to test code. Avoid using static access at all costs and instead inject dependencies through the constructor. The only case when static access is acceptable is when used for factory methods.
Example
class Foo
{
public function bar()
{
Bar::baz();
}
}
Source https://phpmd.org/rules/cleancode.html#staticaccess
Avoid using static access to class '\craft\helpers\Json' in method 'getSettingsBySiteId'. Open
return Json::decodeIfJson($settings->sitemap);
- Read upRead up
- Exclude checks
StaticAccess
Since: 1.4.0
Static access causes unexchangeable dependencies to other classes and leads to hard to test code. Avoid using static access at all costs and instead inject dependencies through the constructor. The only case when static access is acceptable is when used for factory methods.
Example
class Foo
{
public function bar()
{
Bar::baz();
}
}
Source https://phpmd.org/rules/cleancode.html#staticaccess
The method getSitemapData uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
$data = $this->_addElementsToSitemap($data, $settings[$type][$sectionId]);
}
- Read upRead up
- Exclude checks
ElseExpression
Since: 1.4.0
An if expression with an else branch is basically not necessary. You can rewrite the conditions in a way that the else clause is not necessary and the code becomes simpler to read. To achieve this, use early return statements, though you may need to split the code it several smaller methods. For very simple assignments you could also use the ternary operations.
Example
class Foo
{
public function bar($flag)
{
if ($flag) {
// one branch
} else {
// another branch
}
}
}
Source https://phpmd.org/rules/cleancode.html#elseexpression
The method _shouldRenderEntries uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Open
} else {
return false;
}
- Read upRead up
- Exclude checks
ElseExpression
Since: 1.4.0
An if expression with an else branch is basically not necessary. You can rewrite the conditions in a way that the else clause is not necessary and the code becomes simpler to read. To achieve this, use early return statements, though you may need to split the code it several smaller methods. For very simple assignments you could also use the ternary operations.
Example
class Foo
{
public function bar($flag)
{
if ($flag) {
// one branch
} else {
// another branch
}
}
}
Source https://phpmd.org/rules/cleancode.html#elseexpression
Define a constant instead of duplicating this literal "dateUpdated DESC" 6 times. Open
'orderBy' => 'dateUpdated DESC',
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
function run() { prepare('action1'); // Non-Compliant - 'action1' is duplicated 3 times execute('action1'); release('action1'); }
Compliant Solution
ACTION_1 = 'action1'; function run() { prepare(ACTION_1); execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Define a constant instead of duplicating this literal "category" 4 times. Open
if (isset($sitemapSettings['category'])) {
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
function run() { prepare('action1'); // Non-Compliant - 'action1' is duplicated 3 times execute('action1'); release('action1'); }
Compliant Solution
ACTION_1 = 'action1'; function run() { prepare(ACTION_1); execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Define a constant instead of duplicating this literal "sections" 3 times. Open
'sections' => $shouldRenderSections,
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
function run() { prepare('action1'); // Non-Compliant - 'action1' is duplicated 3 times execute('action1'); release('action1'); }
Compliant Solution
ACTION_1 = 'action1'; function run() { prepare(ACTION_1); execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Define a constant instead of duplicating this literal "siteId" 5 times. Open
'siteId' => $siteId,
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
function run() { prepare('action1'); // Non-Compliant - 'action1' is duplicated 3 times execute('action1'); release('action1'); }
Compliant Solution
ACTION_1 = 'action1'; function run() { prepare(ACTION_1); execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Add a "case default" clause to this "switch" statement. Open
switch ($type) {
- Read upRead up
- Exclude checks
The requirement for a final case default
clause is defensive programming. The clause should either take appropriate action, or contain
a suitable comment as to why no action is taken. Even when the switch
covers all current values of an enum
, a default case
should still be used because there is no guarantee that the enum
won't be extended.
Noncompliant Code Example
switch ($param) { //missing default clause case 0: do_something(); break; case 1: do_something_else(); break; } switch ($param) { default: // default clause should be the last one error(); break; case 0: do_something(); break; case 1: do_something_else(); break; }
Compliant Solution
switch ($param) { case 0: do_something(); break; case 1: do_something_else(); break; default: error(); break; }
See
- MISRA C:2004, 15.0 - The MISRA C switch syntax shall be used.
- MISRA C:2004, 15.3 - The final clause of a switch statement shall be the default clause
- MISRA C++:2008, 6-4-3 - A switch statement shall be a well-formed switch statement.
- MISRA C++:2008, 6-4-6 - The final clause of a switch statement shall be the default-clause
- MISRA C:2012, 16.1 - All switch statements shall be well-formed
- MISRA C:2012, 16.4 - Every switch statement shall have a default label
- MISRA C:2012, 16.5 - A default label shall appear as either the first or the last switch label of a switch statement
- MITRE, CWE-478 - Missing Default Case in Switch Statement
- CERT, MSC01-C. - Strive for logical completeness
- CERT, MSC01-CPP. - Strive for logical completeness
Define a constant instead of duplicating this literal "orderBy" 6 times. Open
'orderBy' => 'dateUpdated DESC',
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
function run() { prepare('action1'); // Non-Compliant - 'action1' is duplicated 3 times execute('action1'); release('action1'); }
Compliant Solution
ACTION_1 = 'action1'; function run() { prepare(ACTION_1); execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Define a constant instead of duplicating this literal "product" 4 times. Open
if (isset($sitemapSettings['product'])) {
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
function run() { prepare('action1'); // Non-Compliant - 'action1' is duplicated 3 times execute('action1'); release('action1'); }
Compliant Solution
ACTION_1 = 'action1'; function run() { prepare(ACTION_1); execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Define a constant instead of duplicating this literal "enabled" 3 times. Open
if (isset($sitemapSettings['entry'][$sectionId]['enabled'])) {
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
function run() { prepare('action1'); // Non-Compliant - 'action1' is duplicated 3 times execute('action1'); release('action1'); }
Compliant Solution
ACTION_1 = 'action1'; function run() { prepare(ACTION_1); execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Define a constant instead of duplicating this literal "entry" 5 times. Open
if (isset($sitemapSettings['entry'])) {
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
function run() { prepare('action1'); // Non-Compliant - 'action1' is duplicated 3 times execute('action1'); release('action1'); }
Compliant Solution
ACTION_1 = 'action1'; function run() { prepare(ACTION_1); execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Define a constant instead of duplicating this literal "categories" 3 times. Open
'categories' => $shouldRenderCategories,
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
function run() { prepare('action1'); // Non-Compliant - 'action1' is duplicated 3 times execute('action1'); release('action1'); }
Compliant Solution
ACTION_1 = 'action1'; function run() { prepare(ACTION_1); execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Define a constant instead of duplicating this literal "products" 3 times. Open
'products' => $shouldRenderProducts,
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
function run() { prepare('action1'); // Non-Compliant - 'action1' is duplicated 3 times execute('action1'); release('action1'); }
Compliant Solution
ACTION_1 = 'action1'; function run() { prepare(ACTION_1); execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Define a constant instead of duplicating this literal "_index_site" 3 times. Open
self::SITEMAP_CACHE_KEY . '_index_site' . $currentSite->id,
- Read upRead up
- Exclude checks
Duplicated string literals make the process of refactoring error-prone, since you must be sure to update all occurrences.
On the other hand, constants can be referenced from many places, but only need to be updated in a single place.
Noncompliant Code Example
With the default threshold of 3:
function run() { prepare('action1'); // Non-Compliant - 'action1' is duplicated 3 times execute('action1'); release('action1'); }
Compliant Solution
ACTION_1 = 'action1'; function run() { prepare(ACTION_1); execute(ACTION_1); release(ACTION_1); }
Exceptions
To prevent generating some false-positives, literals having less than 5 characters are excluded.
Avoid unused local variables such as '$settings'. Open
foreach ($productTypes as $id => $settings) {
- Read upRead up
- Exclude checks
UnusedLocalVariable
Since: 0.2
Detects when a local variable is declared and/or assigned, but not used.
Example
class Foo {
public function doSomething()
{
$i = 5; // Unused
}
}
Source https://phpmd.org/rules/unusedcode.html#unusedlocalvariable
Avoid unused local variables such as '$settings'. Open
foreach ($groups as $id => $settings) {
- Read upRead up
- Exclude checks
UnusedLocalVariable
Since: 0.2
Detects when a local variable is declared and/or assigned, but not used.
Example
class Foo {
public function doSomething()
{
$i = 5; // Unused
}
}
Source https://phpmd.org/rules/unusedcode.html#unusedlocalvariable
Avoid unused local variables such as '$settings'. Open
foreach ($sections as $id => $settings) {
- Read upRead up
- Exclude checks
UnusedLocalVariable
Since: 0.2
Detects when a local variable is declared and/or assigned, but not used.
Example
class Foo {
public function doSomething()
{
$i = 5; // Unused
}
}
Source https://phpmd.org/rules/unusedcode.html#unusedlocalvariable
Reference to static property app
from undeclared class \Craft
Open
$section = Craft::$app->getSections()->getSectionById($sectionId);
- Exclude checks
Variable $xml
was undeclared, but array fields are being added to it. Open
$xml[] = '<?xml version="1.0" encoding="UTF-8"?>';
- Exclude checks
Call to method invalidate
from undeclared class \yii\caching\TagDependency
Open
TagDependency::invalidate(
- Exclude checks
Reference to instance property siteId
from undeclared class \craft\base\Element
Open
self::SITEMAP_CACHE_KEY . "_" . $element->siteId . "_" . $id,
- Exclude checks
Call to method getInstance
from undeclared class \studioespresso\seofields\SeoFields
Open
$handle = SeoFields::getInstance()->getSettings()->fieldHandle;
- Exclude checks
Reference to static property app
from undeclared class \Craft
Open
$currentSite = Craft::$app->getSites()->getCurrentSite();
- Exclude checks
Call to method findAll
from undeclared class \craft\elements\Category
Open
$data = Category::findAll([
- Exclude checks
Call to method findAll
from undeclared class \craft\elements\Entry
Open
$data = Entry::findAll([
- Exclude checks
Reference to static property app
from undeclared class \Craft
Open
Craft::$app->getCache(),
- Exclude checks
Call to method parseParam
from undeclared class \craft\helpers\Db
Open
Db::parseParam("JSON_EXTRACT(c.$field, '$.allowIndexing')", ":empty:"),
- Exclude checks
Reference to static property app
from undeclared class \Craft
Open
$type = Craft::$app->getCategories()->getGroupById($id);
- Exclude checks
Call to method getInstance
from undeclared class \craft\commerce\Plugin
Open
$type = Commerce::getInstance()->productTypes->getProductTypeById($id);
- Exclude checks
Reference to static property app
from undeclared class \Craft
Invalid
$site = Craft::$app->getSites()->getCurrentSite();
- Exclude checks
Call to method getProductTypeSites
from undeclared class \craft\commerce\services\ProductTypes
Open
foreach ($productTypeService->getProductTypeSites($productType) as $productTypeSite) {
- Exclude checks
Call to method __construct
from undeclared class \craft\commerce\services\ProductTypes
Open
$productTypeService = new ProductTypes();
- Exclude checks
Class extends undeclared class \craft\base\Component
Open
class SitemapService extends Component
- Exclude checks
Reference to static property app
from undeclared class \Craft
Open
$section = Craft::$app->getSections()->getSectionById($element->sectionId);
- Exclude checks
Call to method select
from undeclared class \craft\db\Query
Open
(new Query())->select(['elements_sites.siteId', 'uri', 'language'])
- Exclude checks
Call to method parseParam
from undeclared class \craft\helpers\Db
Open
Db::parseParam("JSON_EXTRACT(c.$field, '$.allowIndexing')", "yes"),
- Exclude checks
Reference to static property plugin
from undeclared class \studioespresso\seofields\SeoFields
Open
$data = SeoFields::$plugin->defaultsService->getRecordForSiteId($site->id);
- Exclude checks
Call to method decode
from undeclared class \craft\helpers\Json
Open
$sitemapSettings = Json::decode($data->sitemap);
- Exclude checks
Reference to static property plugin
from undeclared class \studioespresso\seofields\SeoFields
Open
$settings = SeoFields::$plugin->defaultsService->getDataBySiteId($siteId);
- Exclude checks
Reference to static property app
from undeclared class \Craft
Open
$groupSites = Craft::$app->getCategories()->getGroupById($group)->siteSettings;
- Exclude checks
Call to method decodeIfJson
from undeclared class \craft\helpers\Json
Invalid
return Json::decodeIfJson($settings->sitemap);
- Exclude checks
Reference to static property app
from undeclared class \Craft
Invalid
$site = Craft::$app->getSites()->getCurrentSite();
- Exclude checks
Reference to static property app
from undeclared class \Craft
Open
if (!Craft::$app->getConfig()->general->devMode) {
- Exclude checks
Call to method __construct
from undeclared class \craft\db\Query
Open
(new Query())->select(['elements_sites.siteId', 'uri', 'language'])
- Exclude checks
Reference to static property app
from undeclared class \Craft
Open
$seoField = Craft::$app->getFields()->getFieldByHandle($handle);
- Exclude checks
Call to method siteUrl
from undeclared class \craft\helpers\UrlHelper
Open
$url = UrlHelper::siteUrl($site['uri'], null, null, $site['siteId']);
- Exclude checks
Call to method findOne
from undeclared class \craft\elements\Entry
Open
$entry = Entry::findOne(['sectionId' => $id, 'orderBy' => 'dateUpdated DESC']);
- Exclude checks
Reference to instance property id
from undeclared class \craft\models\Site
Open
$data = SeoFields::$plugin->defaultsService->getRecordForSiteId($site->id);
- Exclude checks
Call to method __construct
from undeclared class \yii\caching\TagDependency
Open
$cacheDependency = new TagDependency([
- Exclude checks
Reference to static property app
from undeclared class \Craft
Open
if (!Craft::$app->getConfig()->general->devMode) {
- Exclude checks
Call to method findOne
from undeclared class \craft\elements\Category
Open
$entry = Category::findOne(['groupId' => $type->id, 'orderBy' => 'dateUpdated DESC']);
- Exclude checks
Call to method siteUrl
from undeclared class \craft\helpers\UrlHelper
Open
$data[] = UrlHelper::siteUrl(htmlentities('/sitemap_' . $site->id . '_' . $elementName . '_' . $type->id . '_' . strtolower($type->handle) . '.xml'), null, null, $site->id);
- Exclude checks
Parameter $site
has undeclared type \craft\models\Site
Open
public function shouldRenderBySiteId(Site $site)
- Exclude checks
Reference to instance property siteId
from undeclared class \craft\base\Element
Open
self::SITEMAP_CACHE_KEY . '_index_site' . $element->siteId,
- Exclude checks
Reference to static property app
from undeclared class \Craft
Open
$currentSite = Craft::$app->getSites()->getCurrentSite();
- Exclude checks
Reference to static property app
from undeclared class \Craft
Invalid
$type = Craft::$app->getSections()->getSectionById($id);
- Exclude checks
Call to method findAll
from undeclared class \craft\commerce\elements\Product
Open
$data = Product::findAll([
- Exclude checks
Call to method findOne
from undeclared class \craft\commerce\elements\Product
Open
$entry = Product::findOne(['typeId' => $type->id, 'orderBy' => 'dateUpdated DESC']);
- Exclude checks
Reference to static property app
from undeclared class \Craft
Open
$data = Craft::$app->getCache()->getOrSet(
- Exclude checks
Call to method __construct
from undeclared class \yii\caching\TagDependency
Open
$cacheDependency = new TagDependency([
- Exclude checks
Reference to static property app
from undeclared class \Craft
Open
$xml = Craft::$app->getCache()->getOrSet(
- Exclude checks
Parameter $element
has undeclared type \craft\base\Element
Open
public function clearCacheForElement(Element $element)
- Exclude checks
Reference to instance property sectionId
from undeclared class \craft\base\Element
Open
$section = Craft::$app->getSections()->getSectionById($element->sectionId);
- Exclude checks
Reference to static property app
from undeclared class \Craft
Invalid
$site = Craft::$app->getSites()->getCurrentSite();
- Exclude checks
Remove the code after this "return". Open
return false;
- Read upRead up
- Exclude checks
Jump statements (return
, break
, continue
, and goto
) and throw
expressions move
control flow out of the current code block. Typically, any statements in a block that come after a jump or throw
are simply wasted
keystrokes lying in wait to confuse the unwary.
Rarely, as illustrated below, code after a jump or throw
is reachable. However, such code is difficult to understand, and should be
refactored.
Noncompliant Code Example
function fun($a) { $i = 10; return $i + $a; $i++; // this is never executed } function foo($a) { if ($a == 5) { goto error; } else { // do the job } return; error: printf("don't use 5"); // this is reachable but unreadable }
Compliant Solution
function fun($a) { $i = 10; return $i + $a; } function foo($a) { if ($a == 5) { handleError(); } else { // do the job } return; }
See
- MISRA C:2004, 14.1 - There shall be no unreachable code
- MISRA C++:2008, 0-1-1 - A project shall not contain unreachable code
- MISRA C++:2008, 0-1-9 - There shall be no dead code
- MISRA C:2012, 2.1 - A project shall not contain unreachable code
- MISRA C:2012, 2.2 - There shall be no dead code
- MITRE, CWE-561 - Dead Code
- CERT, MSC56-J. - Detect and remove superfluous code and values
- CERT, MSC12-C. - Detect and remove code that has no effect or is never executed
- CERT, MSC07-CPP. - Detect and remove dead code
Avoid excessively long variable names like $shouldRenderCategories. Keep variable name length under 20. Open
$shouldRenderCategories = array_filter($sitemapSettings['category'], function($group) use ($sitemapSettings) {
- Read upRead up
- Exclude checks
LongVariable
Since: 0.2
Detects when a field, formal or local variable is declared with a long name.
Example
class Something {
protected $reallyLongIntName = -3; // VIOLATION - Field
public static function main( array $interestingArgumentsList[] ) { // VIOLATION - Formal
$otherReallyLongName = -5; // VIOLATION - Local
for ($interestingIntIndex = 0; // VIOLATION - For
$interestingIntIndex < 10;
$interestingIntIndex++ ) {
}
}
}
Source https://phpmd.org/rules/naming.html#longvariable
Avoid excessively long variable names like $shouldRenderCategories. Keep variable name length under 20. Open
$shouldRenderCategories = false;
- Read upRead up
- Exclude checks
LongVariable
Since: 0.2
Detects when a field, formal or local variable is declared with a long name.
Example
class Something {
protected $reallyLongIntName = -3; // VIOLATION - Field
public static function main( array $interestingArgumentsList[] ) { // VIOLATION - Formal
$otherReallyLongName = -5; // VIOLATION - Local
for ($interestingIntIndex = 0; // VIOLATION - For
$interestingIntIndex < 10;
$interestingIntIndex++ ) {
}
}
}
Source https://phpmd.org/rules/naming.html#longvariable
Avoid variables with short names like $id. Configured minimum length is 3. Open
$id = $section->id;
- Read upRead up
- Exclude checks
ShortVariable
Since: 0.2
Detects when a field, local, or parameter has a very short name.
Example
class Something {
private $q = 15; // VIOLATION - Field
public static function main( array $as ) { // VIOLATION - Formal
$r = 20 + $this->q; // VIOLATION - Local
for (int $i = 0; $i < 10; $i++) { // Not a Violation (inside FOR)
$r += $this->q;
}
}
}
Source https://phpmd.org/rules/naming.html#shortvariable
Method name "_shouldRenderEntries" should not be prefixed with an underscore to indicate visibility Open
private function _shouldRenderEntries($sitemapSettings)
- Exclude checks
Method name "_addElementsToSitemap" should not be prefixed with an underscore to indicate visibility Open
private function _addElementsToSitemap($entries, $settings)
- Exclude checks
Method name "_addSectionsToIndex" should not be prefixed with an underscore to indicate visibility Open
private function _addSectionsToIndex($sections, $site)
- Exclude checks
Expected 1 space after FUNCTION keyword; 0 found Open
$shouldRenderSections = array_filter($sitemapSettings['entry'], function($sectionId) use ($sitemapSettings) {
- Exclude checks
Method name "_addCategoriesToIndex" should not be prefixed with an underscore to indicate visibility Open
private function _addCategoriesToIndex($groups, $site)
- Exclude checks
Expected 1 space after FUNCTION keyword; 0 found Open
$sites = array_filter($siteEntries, function($item) use ($currentSite) {
- Exclude checks
Method name "_shouldRenderProducts" should not be prefixed with an underscore to indicate visibility Open
private function _shouldRenderProducts($sitemapSettings)
- Exclude checks
Expected 1 space after FUNCTION keyword; 0 found Open
function() use ($data, $type, $settings, $sectionId) {
- Exclude checks
Method name "_addItemToIndex" should not be prefixed with an underscore to indicate visibility Open
private function _addItemToIndex($site, $type, $entry)
- Exclude checks
Method name "_shouldRenderCategories" should not be prefixed with an underscore to indicate visibility Open
private function _shouldRenderCategories($sitemapSettings)
- Exclude checks
Expected 1 space after FUNCTION keyword; 0 found Open
function() use ($data, $currentSite) {
- Exclude checks
Method name "_addProductsToIndex" should not be prefixed with an underscore to indicate visibility Open
private function _addProductsToIndex($productTypes, $site)
- Exclude checks
Expected 1 space after FUNCTION keyword; 0 found Open
$shouldRenderCategories = array_filter($sitemapSettings['category'], function($group) use ($sitemapSettings) {
- Exclude checks
Expected 1 space after FUNCTION keyword; 0 found Open
$shouldRenderProducts = array_filter($sitemapSettings['product'], function($productType) use ($sitemapSettings) {
- Exclude checks
Line exceeds 120 characters; contains 243 characters Open
$data[] = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xhtml="http://www.w3.org/1999/xhtml" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9">';
- Exclude checks
Line exceeds 120 characters; contains 121 characters Open
$shouldRenderProducts = array_filter($sitemapSettings['product'], function($productType) use ($sitemapSettings) {
- Exclude checks
Line exceeds 120 characters; contains 181 characters Open
$data[] = UrlHelper::siteUrl(htmlentities('/sitemap_' . $site->id . '_' . $elementName . '_' . $type->id . '_' . strtolower($type->handle) . '.xml'), null, null, $site->id);
- Exclude checks
Line indented incorrectly; expected at least 16 spaces, found 12 Open
$data = Product::findAll([
- Exclude checks
The method _shouldRenderCategories is not named in camelCase. Open
private function _shouldRenderCategories($sitemapSettings)
{
$shouldRenderCategories = array_filter($sitemapSettings['category'], function($group) use ($sitemapSettings) {
if (isset($sitemapSettings['category'][$group]['enabled'])) {
$site = Craft::$app->getSites()->getCurrentSite();
- Read upRead up
- Exclude checks
CamelCaseMethodName
Since: 0.2
It is considered best practice to use the camelCase notation to name methods.
Example
class ClassName {
public function get_name() {
}
}
Source
The method _addSectionsToIndex is not named in camelCase. Open
private function _addSectionsToIndex($sections, $site)
{
$data = [];
foreach ($sections as $id => $settings) {
$type = Craft::$app->getSections()->getSectionById($id);
- Read upRead up
- Exclude checks
CamelCaseMethodName
Since: 0.2
It is considered best practice to use the camelCase notation to name methods.
Example
class ClassName {
public function get_name() {
}
}
Source
The method _shouldRenderEntries is not named in camelCase. Open
private function _shouldRenderEntries($sitemapSettings)
{
$shouldRenderSections = array_filter($sitemapSettings['entry'], function($sectionId) use ($sitemapSettings) {
$section = Craft::$app->getSections()->getSectionById($sectionId);
if (!$section) {
- Read upRead up
- Exclude checks
CamelCaseMethodName
Since: 0.2
It is considered best practice to use the camelCase notation to name methods.
Example
class ClassName {
public function get_name() {
}
}
Source
The method _shouldRenderProducts is not named in camelCase. Open
private function _shouldRenderProducts($sitemapSettings)
{
if (!class_exists('craft\commerce\models\ProductTypeSite')) {
return false;
}
- Read upRead up
- Exclude checks
CamelCaseMethodName
Since: 0.2
It is considered best practice to use the camelCase notation to name methods.
Example
class ClassName {
public function get_name() {
}
}
Source
The method _addElementsToSitemap is not named in camelCase. Open
private function _addElementsToSitemap($entries, $settings)
{
$data = [];
$data[] = '<?xml version="1.0" encoding="UTF-8"?>';
$data[] = '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xhtml="http://www.w3.org/1999/xhtml" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9">';
- Read upRead up
- Exclude checks
CamelCaseMethodName
Since: 0.2
It is considered best practice to use the camelCase notation to name methods.
Example
class ClassName {
public function get_name() {
}
}
Source
The method _addProductsToIndex is not named in camelCase. Open
private function _addProductsToIndex($productTypes, $site)
{
$data = [];
foreach ($productTypes as $id => $settings) {
/** @phpstan-ignore-next-line */
- Read upRead up
- Exclude checks
CamelCaseMethodName
Since: 0.2
It is considered best practice to use the camelCase notation to name methods.
Example
class ClassName {
public function get_name() {
}
}
Source
The method _addCategoriesToIndex is not named in camelCase. Open
private function _addCategoriesToIndex($groups, $site)
{
$data = [];
foreach ($groups as $id => $settings) {
$type = Craft::$app->getCategories()->getGroupById($id);
- Read upRead up
- Exclude checks
CamelCaseMethodName
Since: 0.2
It is considered best practice to use the camelCase notation to name methods.
Example
class ClassName {
public function get_name() {
}
}
Source
The method _addItemToIndex is not named in camelCase. Open
private function _addItemToIndex($site, $type, $entry)
{
$data = [];
$class = explode('\\', get_class($entry));
$elementName = strtolower(end($class));
- Read upRead up
- Exclude checks
CamelCaseMethodName
Since: 0.2
It is considered best practice to use the camelCase notation to name methods.
Example
class ClassName {
public function get_name() {
}
}