Potherca
9/19/2017 - 9:23 AM

Amount of code for the comparison of various styles of writing a `clamp` function in PHP Raw

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

Summary

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).

Line count

Lines of code can be easily counted using phploc(1).

NCLOC(2) (100.00%)LLOC(3)Percentagesubjectdescription
6116.67%832B9C44return min max
6116.67%60AA891Ereturn/ternary/ternary
14321.43%7BC1F85Bif, if, return;
14321.43%83C742FFif/return, if/return, return
12325.00%8389C469if, elseif, return
12325.00%CAB599E9if/return, elseif/return, else/return
8337.50%A13E087Eif/return, if/return, return (shorthand)

Token count

Using the token_get_all function, it is possible to see how the PHP compiler sees the code.(4)

tokensnon-whitespace tokenssubjectdescription
3612832B9C44return min max
521460AA891Ereturn/ternary/ternary
5418A13E087Eif/return, if/return, return (shorthand)
621883C742FFif/return, if/return, return
66187BC1F85Bif, if, return;
66188389C469if, elseif, return
6819CAB599E9if/return, elseif/return, else/return

Footnotes

  1. Using the following command: find . -name 'clamp.*.php' -exec sh -c 'phploc {} | grep "(LLOC)"' \; -print
  2. NCLOC = Non-Comment Lines of Code
  3. LLOC = Logical Lines Of Code
  4. find ../comparison-of-clamp-functions_55ca0e9377bbd49ee41241380e1fe3f9/ -type f -name '*.php' -not -path '*/vendor/*' -exec php ./count_tokens_in_file.php {} \;