简体   繁体   中英

PSR coding standard - PHP

just developed a simple CLI php code that calculates the multiplication table of your choosen size but when I check the files to make sure they stick to PSR coding standards, it gives me four errors/violations. I don't know where in the files the errors are after several attempts and days of work on the files.

there are two files: cliVersion.php and generateCLITable.php

The first file gives me 1 PSR error and the second one gives me 3 PSR errors.

this is how I generate the multiplication table of size 12 on command line :

  • php cliVersion.php 12

can anyone help me to find out the PSR errors in the files.

here's the files and the error report:

cliVersion.php

<?php
declare(strict_types=1);

require_once 'generateCLITable.php';
require_once '../model/validateInput.php';
?>

<?php

// Assign the user's input argument value to $input variable
$inputString = $argv[1];

$errorMessage = "Please enter a valid argument (a whole number greater than 1)";


// Check if the user's input argument is not null or empty
if ($inputString == null || $inputString == "") {
    echo $errorMessage;
} else {

    // Create an object of ValidateInput Class
    $inputData = new ValidateInput();

    /*
     Validate the $input variable received from the user as an argument.
     The code will be safe to be processed after this line.
    */
    $validatedInput = $inputData->validateInputData($inputString);
    $validatedInputInt = (int)$validatedInput;

    /*
     Check if the validated input is an Integer and if it is,
     generates the table else returns the error message
    */
    $isInputValidInt = $inputData->isInputInt($validatedInputInt);

    if ($isInputValidInt && $validatedInputInt > 1) {
        $multTable = new MultTable();
        $multTable->generateTable($validatedInputInt);
    } else {
        echo $errorMessage;
    }
}

echo PHP_EOL;

GenerateCLITable.php

<?php
declare(strict_types=1);

class MultTable
{
    /**
     * The public generateTable function generates the multiplication table
     *
     * @param int $inputValue
     * 
     * @return void
     */
    public function generateTable(int $inputValue)
    {

        // Create first row of table headers - green colour
        for ($col=1; $col <= $inputValue; $col++) {
            echo "\033[35m \t$col \033[0m";
        }
        // Create remaining rows
        for ($row=1, $col=1; $row <= $inputValue; $row++) {
            echo "\n";
            // First cell is a table header - green colour
            if ($col == 1) {
                echo "\033[35m \n$row \033[0m";
            }
            while ($col <= $inputValue) {
                echo "\t" . $row * $col++ ;
            }
            // Reset $col at the end of the row
            $col = 1;
        }
    }
}

Error report:

cliVersion.php
----------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE

generateCLITable.php
----------------------------------------------------------------------
FOUND 3 ERRORS AFFECTING 3 LINES

我强烈建议在这种情况下使用https://github.com/FriendsOfPHP/PHP-CS-Fixer

I guess you are trying to unit test the code. I would probably focus on trying to be as thoughtful with the code first . Take cliVersion, I think you can simplify it greatly by creating a single method to handle the input. Also I find a lot of issue with your comments and variables and overdesign.

注释

Revised Version:

<?php
//declare(strict_types=1); // I'm using php 5 so I don't have this (but ok for you)
require_once 'generateCLITable.php';
require_once '../model/validateInput.php';

$must_be_gtr_than = 1; // set floor val for validation
$inputData = new ValidateInput($must_be_gtr_than);
$multTable = new MultTable();

if ($inputData->isValidIntegerData($argv[1])) {
    $tableSize = (int) $argv[1];
    $multTable->generateTable($tableSize);
} else {
    echo "Error: Please enter a valid argument (a whole number greater than ".$must_be_gtr_than.")";
    die();
}

In this example I have one method alone that validates that I have an integer > 0, if isValidIntegerData than proceed . Think about ease of code and names that make sense generateTable doesn't tell me much, is there a better name ? Things like that. Take "$validatedInputInt", that doesn't speak to what you are doing as well as what that int is, "tableSize" makes more sense to me. Also we many times save camel back for Classes etc.. I would look up PSR2.

For example we use

CONST_SOMETHING  = xx; //constants
var_x or varx // lowercase for vars
methodX  //camel back 
ClassName // ucwords for classes 
etc..

UPDATE: This is how I would probably go about building something like this:

<?php
//declare(strict_types=1); // PHP5.x Example

class GenerateCLITable
{
    const DEFAULT_BOARD_SIZE = 12;
    public $game_board, $table_size;

    public function __construct($input = self::DEFAULT_BOARD_SIZE)
    {
        $this->game_board = $this->generateTable($input);
    }

    public function generateTable($inputValue = self::DEFAULT_BOARD_SIZE)
    {
        $table = "";
        // Create first row of table headers - green colour
        for ($col=1; $col <= $inputValue; $col++) {
            $table .= "\033[35m \t$col \033[0m";
        }
        // Create remaining rows
        for ($row=1, $col=1; $row <= $inputValue; $row++) {
            $table .= "\n";
            // First cell is a table header - green colour
            if ($col == 1) {
                $table .= "\033[35m \n$row \033[0m";
            }
            while ($col <= $inputValue) {
                $table .=  "\t" . $row * $col++ ;
            }
            // Reset $col at the end of the row
            $col = 1;
        }
        $this->game_board = $table;
        $this->table_size = $inputValue;
        return $table;
    }

    public function isValidInputValue($input = '', $size = 0)
    {
        return (!empty($input) && $input > $size) ? (is_int((int) $input)) : false;
    }

}

//require_once 'generateCLITable.php';
$multTable = new GenerateCLITable();
$must_be_gtr_than = 1;

if (!$multTable->isValidInputValue($argv[1], $must_be_gtr_than)) {
    echo "Error: Please enter a valid argument (a whole number greater than ".$must_be_gtr_than.")";
    die();
}
$table = $multTable->generateTable((int) $argv[1]);
echo $table . "\n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM