Example #1
0
 public function testExecuteOverridesInterval()
 {
     $h = new Handler();
     $this->assertNull($h->interval);
     $interval = m::mock('TryAgain\\IntervalInterface');
     $interval->shouldReceive('process');
     $h->execute(function () {
     }, array(), null, $interval);
     $this->assertEquals($interval, $h->interval);
 }
Example #2
0
        $mustRetry = false;
        $written = $handler->getLastResult();
        list($fh, $text) = $handler->getArguments();
        if ($written === false) {
            // we try 3 times before abandoning
            $mustRetry = ++$this->nbErrors <= 3;
        } else {
            $this->written += $written;
            if ($written !== strlen($text)) {
                $mustRetry = true;
                $handler->setArguments(array($fh, substr($text, $written)));
            } else {
                // we force the result with the total written length
                $handler->setResult($this->written);
            }
        }
        return $mustRetry;
    }
}
$handler = new Handler(new FWriteValidator(), new AnonymousInterval(function ($handler) {
    if (false === $handler->getLastResult()) {
        // if there is an error we wait 1 second before trying again
        sleep(1);
    }
}));
$file = __DIR__ . '/../build/logs/fwrite_example_file.txt';
$text = 'Here the text I want to write in my file.';
$fh = fopen($file, 'w+');
$isWritten = false !== $handler->execute('fwrite', array($fh, $text));
fclose($fh);
echo $isWritten ? 'OK' : 'KO';
Example #3
0
<?php

/**
 * This example shows how it can handle exceptions.
 */
namespace TryAgain\Examples;

use TryAgain\Handler;
use TryAgain\Validator\AnonymousValidator;
require_once __DIR__ . '/../vendor/autoload.php';
function divide($a, $b)
{
    if ($b == 0) {
        throw new \InvalidArgumentException('Cannot divide by zero');
    }
    return $a / $b;
}
$handler = new Handler(new AnonymousValidator(function ($handler) {
    if ($handler->getLastException() instanceof \InvalidArgumentException) {
        $handler->setResult($handler->getLastException()->getMessage());
    }
    return false;
}));
header("Content-Type: text/plain");
$a = 6;
for ($b = -3; $b <= 3; $b++) {
    echo sprintf('%d / %d = %s', $a, $b, $handler->execute('TryAgain\\Examples\\divide', array($a, $b))), PHP_EOL;
}