Skip to content

Commit

Permalink
Create a new Numberable helper
Browse files Browse the repository at this point in the history
Building on laravel#48845, this class will work similarly to the `Stringable` class, but for numbers.
  • Loading branch information
caendesilva committed Nov 17, 2023
1 parent caaf0b2 commit f44217a
Show file tree
Hide file tree
Showing 2 changed files with 100 additions and 0 deletions.
61 changes: 61 additions & 0 deletions src/Illuminate/Support/Numberable.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

namespace Illuminate\Support;

use Illuminate\Support\Traits\Conditionable;
use Illuminate\Support\Traits\Macroable;
use Illuminate\Support\Traits\Tappable;

class Numberable
{
use Conditionable, Macroable, Tappable;

/**
* The underlying numeric value.
*
* @var int|float
*/
protected $value;

/**
* Create a new instance of the class.
*
* @param int|float $value
* @return void
*/
public function __construct($value = 0)
{
$this->value = $value;
}

/**
* Get the raw numeric value.
*
* @return int|float
*/
public function value()
{
return $this->value;
}

/**
* Proxy dynamic properties onto methods.
*
* @param string $key
* @return mixed
*/
public function __get($key)
{
return $this->{$key}();
}

/**
* Get the raw string value.
*
* @return string
*/
public function __toString()
{
return (string) $this->value;
}
}
39 changes: 39 additions & 0 deletions tests/Support/SupportNumberableTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<?php

namespace Illuminate\Tests\Support;

use Illuminate\Support\Numberable;
use PHPUnit\Framework\TestCase;

class SupportNumberableTest extends TestCase
{
/**
* @param int|float $number
* @return \Illuminate\Support\Numberable
*/
protected function numberable($number = 0)
{
return new Numberable($number);
}

public function testNumberable()
{
$this->assertSame(0, $this->numberable()->value());
$this->assertSame(1, $this->numberable(1)->value());
$this->assertSame(1.1, $this->numberable(1.1)->value());
}

public function testMagicGet()
{
$this->assertSame(0, $this->numberable()->value);
$this->assertSame(1, $this->numberable(1)->value);
$this->assertSame(1.1, $this->numberable(1.1)->value);
}

public function testStringCast()
{
$this->assertSame('0', (string) $this->numberable());
$this->assertSame('1', (string) $this->numberable(1));
$this->assertSame('1.1', (string) $this->numberable(1.1));
}
}

0 comments on commit f44217a

Please sign in to comment.