Optimization of php code (NF key generation)

1

Dear colleagues, I am currently working on a project that sends fiscal coupons, in it I came to a function that generates the nfe key, in it I get the following data:

  • City code
  • Year and month of issue
  • Company Cnpj
  • Note template (65 in case)
  • Series
  • Number of the note (9 positions)
  • Emission type
  • 8-note note number

Function code:

public function GeraChaveNFe($CodCidade , $AnoMesEmissao, $CnpjEmpresa , $Modelo , $Serie, $NumeroNF, $TipoEmissao){
    $NF8 = "";
    $NF9 = "";
    $Chave = "";
    $Digito = "";

    $tam = strlen($NumeroNF);
    if($tam > 0){
        $NF9 = str_pad($NumeroNF, 9 - $tam, "0", STR_PAD_LEFT); 
        $NF8 = str_pad($NumeroNF, 8 - $tam, "0", STR_PAD_LEFT);
    }else{
        $NF9 = $this->right($NumeroNF, 9);
        $NF8 = $this->right($NumeroNF, 8);
    }

    $Chave = $CodCidade . $AnoMesEmissao . $CnpjEmpresa . $Modelo . $Serie . $NF9 . $TipoEmissao . $NF8;

    $Digito = $this->DigitoMod11($Chave);
    return $Chave . $Digito;
}

My question is in the following function:

function right($str, $length) {
    return substr($str, -$length);
}

The function Right does the same as String.Right VB and C # , when searching I did not find the same function in php ... then I used the substr.

The question is, is the substr really the equivalent of right or is there a function that can override this method?

    
asked by anonymous 22.10.2018 / 22:53

1 answer

2
  

The question is, is the substr really the equivalent of right or is there a function that can override this method?

Yes, the substr function of php has the same functionality as String.Right function of Visual Basic . As documentation of microsoft :

  

Returns a string containing a specified number of characters on the right side of a string.

An example using the Right function using visual Basic :

Dim TestString As String = "Hello World!"    
Dim subString As String = Right(TestString, 6)
'Saida :  "World!"

Sample taken from documentation >.

Now, what documentation of PHP says about the substr () :

  

Returns the string part specified by the start and length parameter.

I will not go into detail about the function because this is not the focus of the question.

The same example above using language PHP with function substr() :

$TestString = "Hello World!"    
$subString  = substr($TestString, 6)
//Saida :  "World!"

Conclusion

The two functions are equivalent and serve basically the same thing.

Note: I recommend reading the substr () function documentation because it can receive more parameters from the than those used here in the answer.

    
22.10.2018 / 23:25