Home » Php » symfony – PHP: Check whether an integer is in a certain interval or not

symfony – PHP: Check whether an integer is in a certain interval or not

Posted by: admin July 12, 2020 Leave a comment

Questions:

I am currently working on an achievement system for a small online game. The achievement entity basically has 4 attributes:

  • id
  • earnedBy
  • earnedOn
  • progress

The last one is supposed to be a percentage, meaning a number between 0 and 100. In order to make sure that no numbers greater than 100 or smaller than 0 are saved in the database, my setter-method looks as followed (I am using Symfony2 / Doctrine ORM):

public function setProgress($progress)
    {
        $this->progress = max(min($progress, 100), 0);

        return $this;
    }

The important line here is max(min($progress, 100), 0).

It works totally fine, I just wanted to ask, if there is another built-in function in PHP doing exactly that thing, and if what I am doing is okay (concerning good-developing style)

How to&Answers:

You should consider adding some constraints on your entity from the validation component of Symfony2.

use Symfony\Component\Validator\Constraints as Assert;

class Achievement
{
   /**
    * @Assert\Range(min=0, max=100)
    */
    protected progress;
}

The validator service is called automatically when for example validating forms, but you can even call it manually by getting the validator service, for example in your controller.

$achievement = new Achievement();
$errors = $this->get('validator')->validate($achievement);

Answer:

Since PHP 5.2 there are filter_var() functions with considerable set of options available.

One of them lets you check for number being in a range:

$param = 10;

$result = filter_var( $param, FILTER_VALIDATE_INT, [
    'options' => [
        'min_range' => 20, 
        'max_range' => 40
    ]
]);

var_dump( $result ); // will return FALSE for 10

http://codepad.viper-7.com/kVwx7L

Answer:

You can use the Range constraint:

use Symfony\Component\Validator\Constraints\Range;

class Achievement
{
    /**
     * @Range(min=0, max=100)
     */
    private $progress;
}

Validation in Symfony is handled by a separate layer, so you should not do it in setters.

Answer:

Short answer is no, there is no built-in function in PHP which “truncates” a number at lower and upper boundaries.
And it’s really ok to write min(max(x, max_value), min_value) – it is short and readable.