File IntlDateTrait.php
has 462 lines of code (exceeds 250 allowed). Consider refactoring. Invalid
<?php
/**
* IntlDate is a trait for easy conversion date and time between multiple calendars.
*
Function guessDateTime
has a Cognitive Complexity of 20 (exceeds 5 allowed). Consider refactoring. Confirmed
public function guessDateTime($timestring)
{
$date_time = explode(' ', $timestring);
$date = explode('/', $date_time[0]);
- 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 guessDateTime
has 60 lines of code (exceeds 25 allowed). Consider refactoring. Confirmed
public function guessDateTime($timestring)
{
$date_time = explode(' ', $timestring);
$date = explode('/', $date_time[0]);
Method setIntlDateFormatter
has 6 arguments (exceeds 4 allowed). Consider refactoring. Confirmed
$locale = 'en_US',
$datetype = IntlDateFormatter::FULL,
$timetype = IntlDateFormatter::FULL,
$timezone = 'UTC',
$calendar = IntlDateFormatter::GREGORIAN,
Avoid too many return
statements within this method. Confirmed
return false;
Avoid too many return
statements within this method. Confirmed
return [$year, $month, $day, $hour, $minute, $second];
The method parseDateTime() has an NPath complexity of 8192. The configured NPath complexity threshold is 200. Confirmed
private function parseDateTime($datetimeArray)
{
$finalDatetimeArray = [];
if (!is_array($datetimeArray)) {
- Read upRead up
- Exclude checks
NPathComplexity
Since: 0.1
The NPath complexity of a method is the number of acyclic execution paths through that method. A threshold of 200 is generally considered the point where measures should be taken to reduce complexity.
Example
class Foo {
function bar() {
// lots of complicated code
}
}
Source https://phpmd.org/rules/codesize.html#npathcomplexity
The method parseDateTime() has a Cyclomatic Complexity of 14. The configured cyclomatic complexity threshold is 10. Confirmed
private function parseDateTime($datetimeArray)
{
$finalDatetimeArray = [];
if (!is_array($datetimeArray)) {
- Read upRead up
- Exclude checks
CyclomaticComplexity
Since: 0.1
Complexity is determined by the number of decision points in a method plus one for the method entry. The decision points are 'if', 'while', 'for', and 'case labels'. Generally, 1-4 is low complexity, 5-7 indicates moderate complexity, 8-10 is high complexity, and 11+ is very high complexity.
Example
// Cyclomatic Complexity = 11
class Foo {
1 public function example() {
2 if ($a == $b) {
3 if ($a1 == $b1) {
fiddle();
4 } elseif ($a2 == $b2) {
fiddle();
} else {
fiddle();
}
5 } elseif ($c == $d) {
6 while ($c == $d) {
fiddle();
}
7 } elseif ($e == $f) {
8 for ($n = 0; $n < $h; $n++) {
fiddle();
}
} else {
switch ($z) {
9 case 1:
fiddle();
break;
10 case 2:
fiddle();
break;
11 case 3:
fiddle();
break;
default:
fiddle();
break;
}
}
}
}
Source https://phpmd.org/rules/codesize.html#cyclomaticcomplexity
The method guessDateTime() has a Cyclomatic Complexity of 21. The configured cyclomatic complexity threshold is 10. Confirmed
public function guessDateTime($timestring)
{
$date_time = explode(' ', $timestring);
$date = explode('/', $date_time[0]);
- Read upRead up
- Exclude checks
CyclomaticComplexity
Since: 0.1
Complexity is determined by the number of decision points in a method plus one for the method entry. The decision points are 'if', 'while', 'for', and 'case labels'. Generally, 1-4 is low complexity, 5-7 indicates moderate complexity, 8-10 is high complexity, and 11+ is very high complexity.
Example
// Cyclomatic Complexity = 11
class Foo {
1 public function example() {
2 if ($a == $b) {
3 if ($a1 == $b1) {
fiddle();
4 } elseif ($a2 == $b2) {
fiddle();
} else {
fiddle();
}
5 } elseif ($c == $d) {
6 while ($c == $d) {
fiddle();
}
7 } elseif ($e == $f) {
8 for ($n = 0; $n < $h; $n++) {
fiddle();
}
} else {
switch ($z) {
9 case 1:
fiddle();
break;
10 case 2:
fiddle();
break;
11 case 3:
fiddle();
break;
default:
fiddle();
break;
}
}
}
}
Source https://phpmd.org/rules/codesize.html#cyclomaticcomplexity
Refactor this function to reduce its Cognitive Complexity from 19 to the 15 allowed. Confirmed
private function parseDateTime($datetimeArray)
- 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
Reduce the number of returns of this function 6, down to the maximum allowed 3. Confirmed
public function guessDateTime($timestring)
- Read upRead up
- Exclude checks
Having too many return statements in a function increases the function's essential complexity because the flow of execution is broken each time a return statement is encountered. This makes it harder to read and understand the logic of the function.
Noncompliant Code Example
With the default threshold of 3:
function myFunction(){ // Noncompliant as there are 4 return statements if (condition1) { return true; } else { if (condition2) { return false; } else { return true; } } return false; }
Avoid unused local variables such as '$utcDT'. Confirmed
$utcDT = gmdate('c', $timestamp);
- 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
Argument 6 (year)
is string
but \mktime()
takes int
Confirmed
$timestamp = mktime(date('H', $timestamp), date('i', $timestamp), date('s', $timestamp), date('n', $timestamp), date('j', $timestamp), date('Y', $timestamp));
- Exclude checks
Argument 4 (mon)
is string
but \mktime()
takes int
Confirmed
$timestamp = mktime(date('H', $timestamp), date('i', $timestamp), date('s', $timestamp), date('n', $timestamp), date('j', $timestamp), date('Y', $timestamp));
- Exclude checks
Call with 4 arg(s) to \meysampg\intldate\IntlDateTrait::to()
which only takes 3 arg(s) defined at /code/IntlDateTrait.php:138
Confirmed
$this->to($locale, self::$CAL_INDIAN, $timezone = 'UTC', $timezone);
- Exclude checks
Argument 1 (hour)
is string
but \mktime()
takes int
Confirmed
$timestamp = mktime(date('H', $timestamp), date('i', $timestamp), date('s', $timestamp), date('n', $timestamp), date('j', $timestamp), date('Y', $timestamp));
- Exclude checks
Argument 5 (day)
is string
but \mktime()
takes int
Confirmed
$timestamp = mktime(date('H', $timestamp), date('i', $timestamp), date('s', $timestamp), date('n', $timestamp), date('j', $timestamp), date('Y', $timestamp));
- Exclude checks
Argument 3 (calendar)
is null
but \meysampg\intldate\IntlDateTrait::from()
takes string
defined at /code/IntlDateTrait.php:111
Confirmed
$this->from($dateArray, 'en_US', null, $timezone);
- Exclude checks
This branch's code block is the same as the block for the branch on line 548. Open
} elseif ($hour > 24 || $hour < 0) {
return false;
} elseif ($minute > 60 || $minute < 0) {
- Read upRead up
- Exclude checks
Having two cases
in a switch
statement or two branches in an if
chain with the same implementation is at
best duplicate code, and at worst a coding error. If the same logic is truly needed for both instances, then in an if
chain they should
be combined, or for a switch
, one should fall through to the other.
Noncompliant Code Example
switch ($i) { case 1: doSomething(); break; case 2: doSomethingDifferent(); break; case 3: // Noncompliant; duplicates case 1's implementation doSomething(); break; default: doTheRest(); } if ($a >= 0 && $a < 10) { doTheThing(); else if ($a >= 10 && $a < 20) { doTheOtherThing(); } else if ($a >= 20 && $a < 50) { doTheThing(); // Noncompliant; duplicates first condition } else { doTheRest(); } if ($b == 0) { doOneMoreThing(); } else { doOneMoreThing(); // Noncompliant; duplicates then-branch } var b = a ? 12 > 4 : 4; // Noncompliant; always results in the same value
Compliant Solution
switch ($i) { case 1: case 3: doSomething(); break; case 2: doSomethingDifferent(); break; default: doTheRest(); } if (($a >= 0 && $a < 10) || ($a >= 20 && $a < 50)) { doTheThing(); else if ($a >= 10 && $a < 20) { doTheOtherThing(); } else { doTheRest(); } doOneMoreThing(); b = 4;
or
switch ($i) { case 1: doSomething(); break; case 2: doSomethingDifferent(); break; case 3: doThirdThing(); break; default: doTheRest(); } if ($a >= 0 && $a < 10) { doTheThing(); else if ($a >= 10 && $a < 20) { doTheOtherThing(); } else if ($a >= 20 && $a < 50) { doTheThirdThing(); } else { doTheRest(); } if ($b == 0) { doOneMoreThing(); } else { doTheRest(); } int b = a ? 12 > 4 : 8;
Exceptions
Blocks in an if
chain that contain a single line of code are ignored, as are blocks in a switch
statement that contain a
single line of code with or without a following break
.
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
Call with 7 arg(s) to \meysampg\intldate\IntlDateTrait::setIntlDateFormatter()
which only takes 6 arg(s) defined at /code/IntlDateTrait.php:635
Confirmed
$this->setIntlDateFormatter(
- Exclude checks
Argument 3 (sec)
is string
but \mktime()
takes int
Confirmed
$timestamp = mktime(date('H', $timestamp), date('i', $timestamp), date('s', $timestamp), date('n', $timestamp), date('j', $timestamp), date('Y', $timestamp));
- Exclude checks
Call with 7 arg(s) to \meysampg\intldate\IntlDateTrait::setIntlDateFormatter()
which only takes 6 arg(s) defined at /code/IntlDateTrait.php:635
Confirmed
$this->setIntlDateFormatter(
- Exclude checks
This branch's code block is the same as the block for the branch on line 548. Open
} elseif ($second > 60 || $second < 0) {
return false;
}
- Read upRead up
- Exclude checks
Having two cases
in a switch
statement or two branches in an if
chain with the same implementation is at
best duplicate code, and at worst a coding error. If the same logic is truly needed for both instances, then in an if
chain they should
be combined, or for a switch
, one should fall through to the other.
Noncompliant Code Example
switch ($i) { case 1: doSomething(); break; case 2: doSomethingDifferent(); break; case 3: // Noncompliant; duplicates case 1's implementation doSomething(); break; default: doTheRest(); } if ($a >= 0 && $a < 10) { doTheThing(); else if ($a >= 10 && $a < 20) { doTheOtherThing(); } else if ($a >= 20 && $a < 50) { doTheThing(); // Noncompliant; duplicates first condition } else { doTheRest(); } if ($b == 0) { doOneMoreThing(); } else { doOneMoreThing(); // Noncompliant; duplicates then-branch } var b = a ? 12 > 4 : 4; // Noncompliant; always results in the same value
Compliant Solution
switch ($i) { case 1: case 3: doSomething(); break; case 2: doSomethingDifferent(); break; default: doTheRest(); } if (($a >= 0 && $a < 10) || ($a >= 20 && $a < 50)) { doTheThing(); else if ($a >= 10 && $a < 20) { doTheOtherThing(); } else { doTheRest(); } doOneMoreThing(); b = 4;
or
switch ($i) { case 1: doSomething(); break; case 2: doSomethingDifferent(); break; case 3: doThirdThing(); break; default: doTheRest(); } if ($a >= 0 && $a < 10) { doTheThing(); else if ($a >= 10 && $a < 20) { doTheOtherThing(); } else if ($a >= 20 && $a < 50) { doTheThirdThing(); } else { doTheRest(); } if ($b == 0) { doOneMoreThing(); } else { doTheRest(); } int b = a ? 12 > 4 : 8;
Exceptions
Blocks in an if
chain that contain a single line of code are ignored, as are blocks in a switch
statement that contain a
single line of code with or without a following break
.
Call with 7 arg(s) to \meysampg\intldate\IntlDateTrait::setIntlDateFormatter()
which only takes 6 arg(s) defined at /code/IntlDateTrait.php:635
Confirmed
$this->setIntlDateFormatter(
- Exclude checks
This branch's code block is the same as the block for the branch on line 548. Open
} elseif ($minute > 60 || $minute < 0) {
return false;
} elseif ($second > 60 || $second < 0) {
- Read upRead up
- Exclude checks
Having two cases
in a switch
statement or two branches in an if
chain with the same implementation is at
best duplicate code, and at worst a coding error. If the same logic is truly needed for both instances, then in an if
chain they should
be combined, or for a switch
, one should fall through to the other.
Noncompliant Code Example
switch ($i) { case 1: doSomething(); break; case 2: doSomethingDifferent(); break; case 3: // Noncompliant; duplicates case 1's implementation doSomething(); break; default: doTheRest(); } if ($a >= 0 && $a < 10) { doTheThing(); else if ($a >= 10 && $a < 20) { doTheOtherThing(); } else if ($a >= 20 && $a < 50) { doTheThing(); // Noncompliant; duplicates first condition } else { doTheRest(); } if ($b == 0) { doOneMoreThing(); } else { doOneMoreThing(); // Noncompliant; duplicates then-branch } var b = a ? 12 > 4 : 4; // Noncompliant; always results in the same value
Compliant Solution
switch ($i) { case 1: case 3: doSomething(); break; case 2: doSomethingDifferent(); break; default: doTheRest(); } if (($a >= 0 && $a < 10) || ($a >= 20 && $a < 50)) { doTheThing(); else if ($a >= 10 && $a < 20) { doTheOtherThing(); } else { doTheRest(); } doOneMoreThing(); b = 4;
or
switch ($i) { case 1: doSomething(); break; case 2: doSomethingDifferent(); break; case 3: doThirdThing(); break; default: doTheRest(); } if ($a >= 0 && $a < 10) { doTheThing(); else if ($a >= 10 && $a < 20) { doTheOtherThing(); } else if ($a >= 20 && $a < 50) { doTheThirdThing(); } else { doTheRest(); } if ($b == 0) { doOneMoreThing(); } else { doTheRest(); } int b = a ? 12 > 4 : 8;
Exceptions
Blocks in an if
chain that contain a single line of code are ignored, as are blocks in a switch
statement that contain a
single line of code with or without a following break
.
Argument 2 (min)
is string
but \mktime()
takes int
Confirmed
$timestamp = mktime(date('H', $timestamp), date('i', $timestamp), date('s', $timestamp), date('n', $timestamp), date('j', $timestamp), date('Y', $timestamp));
- Exclude checks
Call with 7 arg(s) to \meysampg\intldate\IntlDateTrait::setIntlDateFormatter()
which only takes 6 arg(s) defined at /code/IntlDateTrait.php:635
Confirmed
$this->setIntlDateFormatter(
- Exclude checks
Avoid using static access to class '\IntlCalendar' in method 'setIntlCalendar'. Invalid
$this->_intlCalendar = IntlCalendar::createInstance(
$timezone,
$locale
);
- 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 to uses an else expression. Else clauses are basically not necessary and you can simplify the code by not using them. Confirmed
} else {
$this->setFinalCalendarType(IntlDateFormatter::TRADITIONAL);
}
- 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 "en_US" 16 times. Confirmed
$this->from($dateArray, 'en_US', null, $timezone);
- 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 and throw a dedicated exception instead of using a generic one. Open
throw new Exception('DateTime information must be an array in [year, month, day, hours, minutes, seconds] format.');
- Read upRead up
- Exclude checks
If you throw a general exception type, such as ErrorException, RuntimeException, or Exception in a library or framework, it forces consumers to catch all exceptions, including unknown exceptions that they do not know how to handle.
Instead, either throw a subtype that already exists in the Standard PHP Library, or create your own type that derives from Exception.
Noncompliant Code Example
throw new Exception(); // Noncompliant
Compliant Solution
throw new InvalidArgumentException(); // or throw new UnexpectedValueException();
See
- MITRE, CWE-397 - Declaration of Throws for Generic Exception
- CERT, ERR07-J. - Do not throw RuntimeException, Exception, or Throwable
Avoid using short method names like IntlDateTrait::to(). The configured minimum method name length is 3. Invalid
public function to(
$locale = 'en_US',
$calendar = null,
$timezone = 'UTC'
) {
- Read upRead up
- Exclude checks
ShortMethodName
Since: 0.2
Detects when very short method names are used.
Example
class ShortMethod {
public function a( $index ) { // Violation
}
}
Source https://phpmd.org/rules/naming.html#shortmethodname
Property name "$_toLocale" should not be prefixed with an underscore to indicate visibility Wontfix
private $_toLocale;
- Exclude checks
Property name "$_toCalendar" should not be prefixed with an underscore to indicate visibility Wontfix
private $_toCalendar;
- Exclude checks
Property name "$_fromCalendar" should not be prefixed with an underscore to indicate visibility Wontfix
private $_fromCalendar;
- Exclude checks
Property name "$_intlCalendar" should not be prefixed with an underscore to indicate visibility Wontfix
private $_intlCalendar;
- Exclude checks
Property name "$_intlDateFormatter" should not be prefixed with an underscore to indicate visibility Wontfix
private $_intlDateFormatter;
- Exclude checks
Property name "$_fromLocale" should not be prefixed with an underscore to indicate visibility Wontfix
private $_fromLocale;
- Exclude checks
Line exceeds 120 characters; contains 156 characters Open
$finalDatetimeArray[0] = isset($datetimeArray[0]) ? (int) $datetimeArray[0] : (isset($datetimeArray['year']) ? (int) $datetimeArray['year'] : 1970);
- Exclude checks
Line exceeds 120 characters; contains 159 characters Open
$finalDatetimeArray[1] = isset($datetimeArray[1]) ? (int) $datetimeArray[1] - 1 : (isset($datetimeArray['mon']) ? (int) $datetimeArray['mon'] - 1 : 0);
- Exclude checks
Line exceeds 120 characters; contains 152 characters Open
$this->getIntlCalendar()->set($datetimeArray[0], $datetimeArray[1], $datetimeArray[2], $datetimeArray[3], $datetimeArray[4], $datetimeArray[5]);
- Exclude checks
Line exceeds 120 characters; contains 155 characters Open
$finalDatetimeArray[3] = isset($datetimeArray[3]) ? (int) $datetimeArray[3] : (isset($datetimeArray['hours']) ? (int) $datetimeArray['hours'] : 0);
- Exclude checks
Line exceeds 120 characters; contains 159 characters Open
$finalDatetimeArray[4] = isset($datetimeArray[4]) ? (int) $datetimeArray[4] : (isset($datetimeArray['minutes']) ? (int) $datetimeArray['minutes'] : 0);
- Exclude checks
Line exceeds 120 characters; contains 153 characters Open
$finalDatetimeArray[2] = isset($datetimeArray[2]) ? (int) $datetimeArray[2] : (isset($datetimeArray['mday']) ? (int) $datetimeArray['mday'] : 1);
- Exclude checks
Line exceeds 120 characters; contains 166 characters Open
$timestamp = mktime(date('H', $timestamp), date('i', $timestamp), date('s', $timestamp), date('n', $timestamp), date('j', $timestamp), date('Y', $timestamp));
- Exclude checks
Line exceeds 120 characters; contains 159 characters Open
$finalDatetimeArray[5] = isset($datetimeArray[5]) ? (int) $datetimeArray[5] : (isset($datetimeArray['seconds']) ? (int) $datetimeArray['seconds'] : 0);
- Exclude checks
Line exceeds 120 characters; contains 128 characters Open
throw new Exception('DateTime information must be an array in [year, month, day, hours, minutes, seconds] format.');
- Exclude checks
The variable $date_time is not named in camelCase. Confirmed
public function guessDateTime($timestring)
{
$date_time = explode(' ', $timestring);
$date = explode('/', $date_time[0]);
- Read upRead up
- Exclude checks
CamelCaseVariableName
Since: 0.2
It is considered best practice to use the camelCase notation to name variables.
Example
class ClassName {
public function doSomething() {
$data_module = new DataModule();
}
}
Source
The variable $date_time is not named in camelCase. Confirmed
public function guessDateTime($timestring)
{
$date_time = explode(' ', $timestring);
$date = explode('/', $date_time[0]);
- Read upRead up
- Exclude checks
CamelCaseVariableName
Since: 0.2
It is considered best practice to use the camelCase notation to name variables.
Example
class ClassName {
public function doSomething() {
$data_module = new DataModule();
}
}
Source
The variable $date_time is not named in camelCase. Confirmed
public function guessDateTime($timestring)
{
$date_time = explode(' ', $timestring);
$date = explode('/', $date_time[0]);
- Read upRead up
- Exclude checks
CamelCaseVariableName
Since: 0.2
It is considered best practice to use the camelCase notation to name variables.
Example
class ClassName {
public function doSomething() {
$data_module = new DataModule();
}
}