Amount of code for the comparison of various styles of writing a clamp
function in PHP Raw
<?php
$file = $argv[1];
$contents = file_get_contents($file);
$all_tokens = token_get_all($contents);
$tokens = array_filter($all_tokens, function ($token) {
return ! is_string($token) && (
$token[0] !== 382 // T_WHITESPACE
);
});
$name = basename($file);
$count_all = count($all_tokens);
$count = count($tokens);
echo <<<TXT
File : $name
Tokens All : $count_all
Tokens : $count
TXT;
📝 This text is part of the article Comparison of various styles of writing a clamp
function in PHP
To measure the amount of code, different metrics can be used. For now I'll use the infamous lines of code (to represent how people see the code) and tokens (to represent how the PHP parser sees the code).
Lines of code can be easily counted using phploc(1).
NCLOC(2) (100.00%) | LLOC(3) | Percentage | subject | description |
---|---|---|---|---|
6 | 1 | 16.67% | 832B9C44 | return min max |
6 | 1 | 16.67% | 60AA891E | return/ternary/ternary |
14 | 3 | 21.43% | 7BC1F85B | if, if, return; |
14 | 3 | 21.43% | 83C742FF | if/return, if/return, return |
12 | 3 | 25.00% | 8389C469 | if, elseif, return |
12 | 3 | 25.00% | CAB599E9 | if/return, elseif/return, else/return |
8 | 3 | 37.50% | A13E087E | if/return, if/return, return (shorthand) |
Using the token_get_all
function, it is possible to see how the PHP compiler sees the code.(4)
tokens | non-whitespace tokens | subject | description |
---|---|---|---|
36 | 12 | 832B9C44 | return min max |
52 | 14 | 60AA891E | return/ternary/ternary |
54 | 18 | A13E087E | if/return, if/return, return (shorthand) |
62 | 18 | 83C742FF | if/return, if/return, return |
66 | 18 | 7BC1F85B | if, if, return; |
66 | 18 | 8389C469 | if, elseif, return |
68 | 19 | CAB599E9 | if/return, elseif/return, else/return |
Footnotes
find . -name 'clamp.*.php' -exec sh -c 'phploc {} | grep "(LLOC)"' \; -print
NCLOC
= Non-Comment Lines of CodeLLOC
= Logical Lines Of Codefind ../comparison-of-clamp-functions_55ca0e9377bbd49ee41241380e1fe3f9/ -type f -name '*.php' -not -path '*/vendor/*' -exec php ./count_tokens_in_file.php {} \;