PHP code example of mcustiel / mockable-datetime

1. Go to this page and download the library: Download mcustiel/mockable-datetime library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mcustiel / mockable-datetime example snippets



use Mcustiel\Mockable\DateTime;

// ...
function savePersonInfoInDatabase(Person $person)
{
    /** @var PersonDbEntity $person */
    $person = $this->converter->convert($person, PersonDbEntity::class);
    $person->setCreatedAt(DateTime::newPhpDateTime()); // DateTime::newImmutablePhpDateTime() can also be used
    $this->dbClient->insert($person);
}
// ...


use Mcustiel\Mockable\DateTime;

// ...
function savePersonInfoInDatabase(Person $person)
{
    /** @var PersonDbEntity $person */
    $person = $this->converter->convert($person, PersonDbEntity::class);
    $person->setCreatedAt(DateTime::newPhpDateTime(
        '-4 months', 
        new \DateTimeZone('America/New_York')
    )); // DateTime::newImmutablePhpDateTime() can also be used
    $this->dbClient->insert($person);
}
// ...

use Mcustiel\Mockable\DateTime;

// ...

/**
 * @test
 */
function shouldCallInsertPersonWithCorrectData()
{
    DateTime::setFixed(new \DateTime('2000-01-01 00:00:01'));
    // Now every call to MockableDateTime::newPhpDateTime() will always return "2000-01-01 00:00:01"
    /** @var Person $person */
    $person = new Person('John', 'Doe');
    /** @var PersonDbEntity $expected */
    $expected = new PersonDbEntity('John', 'Doe');
    $expected->setCreatedAt(new \DateTime('2000-01-01 00:00:01'));    
    
    $this->dbClientMock->expects($this->once())
        ->method('insert')
        ->with($this->equalTo($expected));
    // ...and other needed mocks
    $this->unitUnderTest->savePersonInfoInDatabase($person);
}
// ...