Condition ->
Number of independent linear paths through code.
// 1 point for the function declaration
function foo($list) {
// 1 point for any for, foreach, or while
foreach ($list as $item) {
// 1 point for any if, elseif, case
if ($item == 'foo') {
return 'bar';
}
else if ($item == 'bar') {
return 'baz';
}
//no points given for else, this represents default execution path
else {
return 'default';
}
}
}
function complex_form_alter(&$form, &$form_state, $form_id) {
switch ($form_id) {
case 'search_form':
if (user_is_logged_in()) {
array_unshift($form['#submit'], 'complex_submit');
}
break;
case 'article_node_form':
drupal_set_title('This is an article form!');
break;
default:
watchdog('complex', 'someone accessed a form!');
break;
}
}
function foo($foo, $bar) {
// First conditional, two possible outcomes
if ($foo > 100) {
echo 'path 1';
} else {
echo 'path 2';
}
// Second conditional, two possible outcomes
if ($foo > $bar) {
echo 'path 3';
} else {
echo 'path 4';
}
}
function foo($foo, $bar) {
// First conditional, two possible outcomes
if ($foo > 100) {
echo 'path 1';
}
else {
echo 'path 2';
}
// Second conditional, two possible outcomes
if ($foo > 200) {
echo 'path 3';
}
else {
echo 'path 4';
}
// Third conditional, two possible outcomes
if ($foo > $bar) {
echo 'path 5';
} else {
echo 'path 6';
}
}
composer global require 'phpmd/phpmd'
phpmd [filename|directory] [report format] [ruleset file]
php foo.php text codesize
foo.php:2 The function foo() has a Cyclomatic Complexity of 17. The configured cyclomatic complexity threshold is 10.
NPath complexity too high
foo.php:20 The function bar() has an NPath complexity of 226. The configured NPath complexity threshold is 200.
if ($something) {
foreach ($list as $item) {
if ($item == 'foo') {
foreach ($other_list as $other_item) {
while ($yet_another = get_another_thing()) {
if ($yet_another == 'bar') {
print 'AAAAAAAAHHHHH!!!!!!';
}
}
}
}
}
}
function foo($words) {
$contains_long_word = false;
foreach ($words as $word) {
if (strlen($item) >= 20) {
$contains_long_word = true;
}
}
if ($contains_long_word) {
foreach ($words as $key => $word) {
$words[$key] = strtolower($words[$key);
}
}
}
function array_some($arr, $fn) { foreach ($arr as $item) { if (!$fn($item)) { return false; } return true; } }
function is_long_word($word) { return (strlen($word) >= 20); } function foo($words) { $has_long_word = array_some($words, 'is_long_word'); if ($has_long_word) { return array_map('strtolower', $words); } return $words; }