repo stringlengths 7 63 | file_url stringlengths 81 284 | file_path stringlengths 5 200 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:02:33 2026-01-05 05:24:06 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/SyslogUdpHandlerTest.php | tests/Monolog/Handler/SyslogUdpHandlerTest.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use Monolog\Level;
/**
* @requires extension sockets
*/
class SyslogUdpHandlerTest extends \Monolog\Test\MonologTestCase
{
public function testWeValidateFacilities()
{
$this->expectException(\UnexpectedValueException::class);
$handler = new SyslogUdpHandler("ip", 514, "invalidFacility");
}
public function testWeSplitIntoLines()
{
$pid = getmypid();
$host = gethostname();
$handler = new \Monolog\Handler\SyslogUdpHandler("127.0.0.1", 514, "authpriv");
$handler->setFormatter(new \Monolog\Formatter\ChromePHPFormatter());
$time = '2014-01-07T12:34:56+00:00';
$socket = $this->getMockBuilder('Monolog\Handler\SyslogUdp\UdpSocket')
->onlyMethods(['write'])
->setConstructorArgs(['lol'])
->getMock();
$matcher = $this->atLeast(2);
$socket->expects($matcher)
->method('write')
->willReturnCallback(function () use ($matcher, $time, $host, $pid) {
match ($matcher->numberOfInvocations()) {
1 => $this->equalTo("lol") && $this->equalTo("<".(LOG_AUTHPRIV + LOG_WARNING).">1 $time $host php $pid - - "),
2 => $this->equalTo("hej") && $this->equalTo("<".(LOG_AUTHPRIV + LOG_WARNING).">1 $time $host php $pid - - "),
default => $this->assertTrue(true)
};
});
$handler->setSocket($socket);
$handler->handle($this->getRecordWithMessage("hej\nlol"));
}
public function testSplitWorksOnEmptyMsg()
{
$handler = new SyslogUdpHandler("127.0.0.1", 514, "authpriv");
$handler->setFormatter($this->getIdentityFormatter());
$socket = $this->getMockBuilder('Monolog\Handler\SyslogUdp\UdpSocket')
->onlyMethods(['write'])
->setConstructorArgs(['lol'])
->getMock();
$socket->expects($this->never())
->method('write');
$handler->setSocket($socket);
$handler->handle($this->getRecordWithMessage(''));
}
public function testRfc()
{
$time = 'Jan 07 12:34:56';
$pid = getmypid();
$host = gethostname();
$handler = $this->getMockBuilder('\Monolog\Handler\SyslogUdpHandler')
->setConstructorArgs(["127.0.0.1", 514, "authpriv", 'debug', true, "php", \Monolog\Handler\SyslogUdpHandler::RFC3164])
->onlyMethods([])
->getMock();
$handler->setFormatter(new \Monolog\Formatter\ChromePHPFormatter());
$socket = $this->getMockBuilder('\Monolog\Handler\SyslogUdp\UdpSocket')
->setConstructorArgs(['lol', 999])
->onlyMethods(['write'])
->getMock();
$matcher = $this->atLeast(2);
$socket->expects($matcher)
->method('write')
->willReturnCallback(function () use ($matcher, $time, $host, $pid) {
match ($matcher->numberOfInvocations()) {
1 => $this->equalTo("lol") && $this->equalTo("<".(LOG_AUTHPRIV + LOG_WARNING).">$time $host php[$pid]: "),
2 => $this->equalTo("hej") && $this->equalTo("<".(LOG_AUTHPRIV + LOG_WARNING).">$time $host php[$pid]: "),
default => $this->assertTrue(true)
};
});
$handler->setSocket($socket);
$handler->handle($this->getRecordWithMessage("hej\nlol"));
}
protected function getRecordWithMessage($msg)
{
return $this->getRecord(message: $msg, level: Level::Warning, channel: 'lol', datetime: new \DateTimeImmutable('2014-01-07 12:34:56'));
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/RotatingFileHandlerTest.php | tests/Monolog/Handler/RotatingFileHandlerTest.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use InvalidArgumentException;
use PHPUnit\Framework\Attributes\DataProvider;
/**
* @covers Monolog\Handler\RotatingFileHandler
*/
class RotatingFileHandlerTest extends \Monolog\Test\MonologTestCase
{
private array|null $lastError = null;
public function setUp(): void
{
$dir = __DIR__.'/Fixtures';
chmod($dir, 0777);
if (!is_writable($dir)) {
$this->markTestSkipped($dir.' must be writable to test the RotatingFileHandler.');
}
$this->lastError = null;
set_error_handler(function ($code, $message) {
$this->lastError = [
'code' => $code,
'message' => $message,
];
return true;
});
}
public function tearDown(): void
{
parent::tearDown();
foreach (glob(__DIR__.'/Fixtures/*.rot') as $file) {
unlink($file);
}
if ('testRotationWithFolderByDate' === $this->name()) {
foreach (glob(__DIR__.'/Fixtures/[0-9]*') as $folder) {
$this->rrmdir($folder);
}
}
restore_error_handler();
unset($this->lastError);
}
private function rrmdir($directory)
{
if (! is_dir($directory)) {
throw new InvalidArgumentException("$directory must be a directory");
}
if (substr($directory, \strlen($directory) - 1, 1) !== '/') {
$directory .= '/';
}
foreach (glob($directory . '*', GLOB_MARK) as $path) {
if (is_dir($path)) {
$this->rrmdir($path);
} else {
unlink($path);
}
}
return rmdir($directory);
}
private function assertErrorWasTriggered($code, $message)
{
if (empty($this->lastError)) {
$this->fail(
\sprintf(
'Failed asserting that error with code `%d` and message `%s` was triggered',
$code,
$message
)
);
}
$this->assertEquals($code, $this->lastError['code'], \sprintf('Expected an error with code %d to be triggered, got `%s` instead', $code, $this->lastError['code']));
$this->assertEquals($message, $this->lastError['message'], \sprintf('Expected an error with message `%d` to be triggered, got `%s` instead', $message, $this->lastError['message']));
}
public function testRotationCreatesNewFile()
{
touch(__DIR__.'/Fixtures/foo-'.date('Y-m-d', time() - 86400).'.rot');
$handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot');
$handler->setFormatter($this->getIdentityFormatter());
$handler->handle($this->getRecord());
$log = __DIR__.'/Fixtures/foo-'.date('Y-m-d').'.rot';
$this->assertTrue(file_exists($log));
$this->assertEquals('test', file_get_contents($log));
}
#[DataProvider('rotationTests')]
public function testRotation($createFile, $dateFormat, $timeCallback)
{
touch($old1 = __DIR__.'/Fixtures/foo-'.date($dateFormat, $timeCallback(-1)).'.rot');
touch($old2 = __DIR__.'/Fixtures/foo-'.date($dateFormat, $timeCallback(-2)).'.rot');
touch($old3 = __DIR__.'/Fixtures/foo-'.date($dateFormat, $timeCallback(-3)).'.rot');
touch($old4 = __DIR__.'/Fixtures/foo-'.date($dateFormat, $timeCallback(-4)).'.rot');
$log = __DIR__.'/Fixtures/foo-'.date($dateFormat).'.rot';
if ($createFile) {
touch($log);
}
$handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot', 2);
$handler->setFormatter($this->getIdentityFormatter());
$handler->setFilenameFormat('{filename}-{date}', $dateFormat);
$handler->handle($this->getRecord());
$handler->close();
$this->assertTrue(file_exists($log));
$this->assertTrue(file_exists($old1));
$this->assertEquals($createFile, file_exists($old2));
$this->assertEquals($createFile, file_exists($old3));
$this->assertEquals($createFile, file_exists($old4));
$this->assertEquals('test', file_get_contents($log));
}
public static function rotationTests()
{
$now = time();
$dayCallback = function ($ago) use ($now) {
return $now + 86400 * $ago;
};
$monthCallback = function ($ago) {
return gmmktime(0, 0, 0, (int) (date('n') + $ago), 1, (int) date('Y'));
};
$yearCallback = function ($ago) {
return gmmktime(0, 0, 0, 1, 1, (int) (date('Y') + $ago));
};
return [
'Rotation is triggered when the file of the current day is not present'
=> [true, RotatingFileHandler::FILE_PER_DAY, $dayCallback],
'Rotation is not triggered when the file of the current day is already present'
=> [false, RotatingFileHandler::FILE_PER_DAY, $dayCallback],
'Rotation is triggered when the file of the current month is not present'
=> [true, RotatingFileHandler::FILE_PER_MONTH, $monthCallback],
'Rotation is not triggered when the file of the current month is already present'
=> [false, RotatingFileHandler::FILE_PER_MONTH, $monthCallback],
'Rotation is triggered when the file of the current year is not present'
=> [true, RotatingFileHandler::FILE_PER_YEAR, $yearCallback],
'Rotation is not triggered when the file of the current year is already present'
=> [false, RotatingFileHandler::FILE_PER_YEAR, $yearCallback],
];
}
private function createDeep($file)
{
mkdir(\dirname($file), 0777, true);
touch($file);
return $file;
}
#[DataProvider('rotationWithFolderByDateTests')]
public function testRotationWithFolderByDate($createFile, $dateFormat, $timeCallback)
{
$old1 = $this->createDeep(__DIR__.'/Fixtures/'.date($dateFormat, $timeCallback(-1)).'/foo.rot');
$old2 = $this->createDeep(__DIR__.'/Fixtures/'.date($dateFormat, $timeCallback(-2)).'/foo.rot');
$old3 = $this->createDeep(__DIR__.'/Fixtures/'.date($dateFormat, $timeCallback(-3)).'/foo.rot');
$old4 = $this->createDeep(__DIR__.'/Fixtures/'.date($dateFormat, $timeCallback(-4)).'/foo.rot');
$log = __DIR__.'/Fixtures/'.date($dateFormat).'/foo.rot';
if ($createFile) {
$this->createDeep($log);
}
$handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot', 2);
$handler->setFormatter($this->getIdentityFormatter());
$handler->setFilenameFormat('{date}/{filename}', $dateFormat);
$handler->handle($this->getRecord());
$handler->close();
$this->assertTrue(file_exists($log));
$this->assertTrue(file_exists($old1));
$this->assertEquals($createFile, file_exists($old2));
$this->assertEquals($createFile, file_exists($old3));
$this->assertEquals($createFile, file_exists($old4));
$this->assertEquals('test', file_get_contents($log));
}
public static function rotationWithFolderByDateTests()
{
$now = time();
$dayCallback = function ($ago) use ($now) {
return $now + 86400 * $ago;
};
$monthCallback = function ($ago) {
return gmmktime(0, 0, 0, (int) (date('n') + $ago), 1, (int) date('Y'));
};
$yearCallback = function ($ago) {
return gmmktime(0, 0, 0, 1, 1, (int) (date('Y') + $ago));
};
return [
'Rotation is triggered when the file of the current day is not present'
=> [true, 'Y/m/d', $dayCallback],
'Rotation is not triggered when the file of the current day is already present'
=> [false, 'Y/m/d', $dayCallback],
'Rotation is triggered when the file of the current month is not present'
=> [true, 'Y/m', $monthCallback],
'Rotation is not triggered when the file of the current month is already present'
=> [false, 'Y/m', $monthCallback],
'Rotation is triggered when the file of the current year is not present'
=> [true, 'Y', $yearCallback],
'Rotation is not triggered when the file of the current year is already present'
=> [false, 'Y', $yearCallback],
];
}
#[DataProvider('dateFormatProvider')]
public function testAllowOnlyFixedDefinedDateFormats($dateFormat, $valid)
{
$handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot', 2);
if (!$valid) {
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessageMatches('~^Invalid date format~');
}
$handler->setFilenameFormat('{filename}-{date}', $dateFormat);
$this->assertTrue(true);
}
public static function dateFormatProvider()
{
return [
[RotatingFileHandler::FILE_PER_DAY, true],
[RotatingFileHandler::FILE_PER_MONTH, true],
[RotatingFileHandler::FILE_PER_YEAR, true],
['Y/m/d', true],
['Y.m.d', true],
['Y_m_d', true],
['Ymd', true],
['Ym/d', true],
['Y/m', true],
['Ym', true],
['Y.m', true],
['Y_m', true],
['Y/md', true],
['', false],
['m-d-Y', false],
['Y-m-d-h-i', false],
['Y-', false],
['Y-m-', false],
['Y--', false],
['m-d', false],
['Y-d', false],
];
}
#[DataProvider('filenameFormatProvider')]
public function testDisallowFilenameFormatsWithoutDate($filenameFormat, $valid)
{
$handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot', 2);
if (!$valid) {
$this->expectException(InvalidArgumentException::class);
$this->expectExceptionMessageMatches('~^Invalid filename format~');
}
$handler->setFilenameFormat($filenameFormat, RotatingFileHandler::FILE_PER_DAY);
}
public static function filenameFormatProvider()
{
return [
['{filename}', false],
['{filename}-{date}', true],
['{date}', true],
['foobar-{date}', true],
['foo-{date}-bar', true],
['{date}-foobar', true],
['{date}/{filename}', true],
['foobar', false],
];
}
#[DataProvider('rotationWhenSimilarFilesExistTests')]
public function testRotationWhenSimilarFileNamesExist($dateFormat)
{
touch($old1 = __DIR__.'/Fixtures/foo-foo-'.date($dateFormat).'.rot');
touch($old2 = __DIR__.'/Fixtures/foo-bar-'.date($dateFormat).'.rot');
$log = __DIR__.'/Fixtures/foo-'.date($dateFormat).'.rot';
$handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot', 2);
$handler->setFormatter($this->getIdentityFormatter());
$handler->setFilenameFormat('{filename}-{date}', $dateFormat);
$handler->handle($this->getRecord());
$handler->close();
$this->assertTrue(file_exists($log));
}
public static function rotationWhenSimilarFilesExistTests()
{
return [
'Rotation is triggered when the file of the current day is not present but similar exists'
=> [RotatingFileHandler::FILE_PER_DAY],
'Rotation is triggered when the file of the current month is not present but similar exists'
=> [RotatingFileHandler::FILE_PER_MONTH],
'Rotation is triggered when the file of the current year is not present but similar exists'
=> [RotatingFileHandler::FILE_PER_YEAR],
];
}
public function testReuseCurrentFile()
{
$log = __DIR__.'/Fixtures/foo-'.date('Y-m-d').'.rot';
file_put_contents($log, "foo");
$handler = new RotatingFileHandler(__DIR__.'/Fixtures/foo.rot');
$handler->setFormatter($this->getIdentityFormatter());
$handler->handle($this->getRecord());
$this->assertEquals('footest', file_get_contents($log));
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/FilterHandlerTest.php | tests/Monolog/Handler/FilterHandlerTest.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use Monolog\Level;
class FilterHandlerTest extends \Monolog\Test\MonologTestCase
{
/**
* @covers Monolog\Handler\FilterHandler::isHandling
*/
public function testIsHandling()
{
$test = new TestHandler();
$handler = new FilterHandler($test, Level::Info, Level::Notice);
$this->assertFalse($handler->isHandling($this->getRecord(Level::Debug)));
$this->assertTrue($handler->isHandling($this->getRecord(Level::Info)));
$this->assertTrue($handler->isHandling($this->getRecord(Level::Notice)));
$this->assertFalse($handler->isHandling($this->getRecord(Level::Warning)));
$this->assertFalse($handler->isHandling($this->getRecord(Level::Error)));
$this->assertFalse($handler->isHandling($this->getRecord(Level::Critical)));
$this->assertFalse($handler->isHandling($this->getRecord(Level::Alert)));
$this->assertFalse($handler->isHandling($this->getRecord(Level::Emergency)));
}
/**
* @covers Monolog\Handler\FilterHandler::handle
* @covers Monolog\Handler\FilterHandler::setAcceptedLevels
* @covers Monolog\Handler\FilterHandler::isHandling
*/
public function testHandleProcessOnlyNeededLevels()
{
$test = new TestHandler();
$handler = new FilterHandler($test, Level::Info, Level::Notice);
$handler->handle($this->getRecord(Level::Debug));
$this->assertFalse($test->hasDebugRecords());
$handler->handle($this->getRecord(Level::Info));
$this->assertTrue($test->hasInfoRecords());
$handler->handle($this->getRecord(Level::Notice));
$this->assertTrue($test->hasNoticeRecords());
$handler->handle($this->getRecord(Level::Warning));
$this->assertFalse($test->hasWarningRecords());
$handler->handle($this->getRecord(Level::Error));
$this->assertFalse($test->hasErrorRecords());
$handler->handle($this->getRecord(Level::Critical));
$this->assertFalse($test->hasCriticalRecords());
$handler->handle($this->getRecord(Level::Alert));
$this->assertFalse($test->hasAlertRecords());
$handler->handle($this->getRecord(Level::Emergency));
$this->assertFalse($test->hasEmergencyRecords());
$test = new TestHandler();
$handler = new FilterHandler($test, [Level::Info, Level::Error]);
$handler->handle($this->getRecord(Level::Debug));
$this->assertFalse($test->hasDebugRecords());
$handler->handle($this->getRecord(Level::Info));
$this->assertTrue($test->hasInfoRecords());
$handler->handle($this->getRecord(Level::Notice));
$this->assertFalse($test->hasNoticeRecords());
$handler->handle($this->getRecord(Level::Error));
$this->assertTrue($test->hasErrorRecords());
$handler->handle($this->getRecord(Level::Critical));
$this->assertFalse($test->hasCriticalRecords());
}
/**
* @covers Monolog\Handler\FilterHandler::setAcceptedLevels
* @covers Monolog\Handler\FilterHandler::getAcceptedLevels
*/
public function testAcceptedLevelApi()
{
$test = new TestHandler();
$handler = new FilterHandler($test);
$levels = [Level::Info, Level::Error];
$levelsExpect = [Level::Info, Level::Error];
$handler->setAcceptedLevels($levels);
$this->assertSame($levelsExpect, $handler->getAcceptedLevels());
$handler->setAcceptedLevels(['info', 'error']);
$this->assertSame($levelsExpect, $handler->getAcceptedLevels());
$levels = [Level::Critical, Level::Alert, Level::Emergency];
$handler->setAcceptedLevels(Level::Critical, Level::Emergency);
$this->assertSame($levels, $handler->getAcceptedLevels());
$handler->setAcceptedLevels('critical', 'emergency');
$this->assertSame($levels, $handler->getAcceptedLevels());
}
/**
* @covers Monolog\Handler\FilterHandler::handle
*/
public function testHandleUsesProcessors()
{
$test = new TestHandler();
$handler = new FilterHandler($test, Level::Debug, Level::Emergency);
$handler->pushProcessor(
function ($record) {
$record->extra['foo'] = true;
return $record;
}
);
$handler->handle($this->getRecord(Level::Warning));
$this->assertTrue($test->hasWarningRecords());
$records = $test->getRecords();
$this->assertTrue($records[0]['extra']['foo']);
}
/**
* @covers Monolog\Handler\FilterHandler::handle
*/
public function testHandleRespectsBubble()
{
$test = new TestHandler();
$handler = new FilterHandler($test, Level::Info, Level::Notice, false);
$this->assertTrue($handler->handle($this->getRecord(Level::Info)));
$this->assertFalse($handler->handle($this->getRecord(Level::Warning)));
$handler = new FilterHandler($test, Level::Info, Level::Notice, true);
$this->assertFalse($handler->handle($this->getRecord(Level::Info)));
$this->assertFalse($handler->handle($this->getRecord(Level::Warning)));
}
/**
* @covers Monolog\Handler\FilterHandler::handle
*/
public function testHandleWithCallback()
{
$test = new TestHandler();
$handler = new FilterHandler(
function ($record, $handler) use ($test) {
return $test;
},
Level::Info,
Level::Notice,
false
);
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Info));
$this->assertFalse($test->hasDebugRecords());
$this->assertTrue($test->hasInfoRecords());
}
/**
* @covers Monolog\Handler\FilterHandler::handle
*/
public function testHandleWithBadCallbackThrowsException()
{
$handler = new FilterHandler(
function ($record, $handler) {
return 'foo';
}
);
$this->expectException(\RuntimeException::class);
$handler->handle($this->getRecord(Level::Warning));
}
public function testHandleEmptyBatch()
{
$test = new TestHandler();
$handler = new FilterHandler($test);
$handler->handleBatch([]);
$this->assertSame([], $test->getRecords());
}
/**
* @covers Monolog\Handler\FilterHandler::handle
* @covers Monolog\Handler\FilterHandler::reset
*/
public function testResetTestHandler()
{
$test = new TestHandler();
$handler = new FilterHandler($test, [Level::Info, Level::Error]);
$handler->handle($this->getRecord(Level::Info));
$this->assertTrue($test->hasInfoRecords());
$handler->handle($this->getRecord(Level::Error));
$this->assertTrue($test->hasErrorRecords());
$handler->reset();
$this->assertFalse($test->hasInfoRecords());
$this->assertFalse($test->hasInfoRecords());
$this->assertSame([], $test->getRecords());
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/BrowserConsoleHandlerTest.php | tests/Monolog/Handler/BrowserConsoleHandlerTest.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use Monolog\Level;
/**
* @covers Monolog\Handler\BrowserConsoleHandlerTest
*/
class BrowserConsoleHandlerTest extends \Monolog\Test\MonologTestCase
{
protected function setUp(): void
{
BrowserConsoleHandler::resetStatic();
}
protected function generateScript()
{
$reflMethod = new \ReflectionMethod('Monolog\Handler\BrowserConsoleHandler', 'generateScript');
return $reflMethod->invoke(null);
}
public function testStyling()
{
$handler = new BrowserConsoleHandler();
$handler->setFormatter($this->getIdentityFormatter());
$handler->handle($this->getRecord(Level::Debug, 'foo[[bar]]{color: red}'));
$expected = <<<EOF
(function (c) {if (c && c.groupCollapsed) {
c.debug("%cfoo%cbar%c", "font-weight: normal", "color: red", "font-weight: normal");
}})(console);
EOF;
$this->assertEquals($expected, $this->generateScript());
}
public function testStylingMultiple()
{
$handler = new BrowserConsoleHandler();
$handler->setFormatter($this->getIdentityFormatter());
$handler->handle($this->getRecord(Level::Debug, 'foo[[bar]]{color: red}[[baz]]{color: blue}'));
$expected = <<<EOF
(function (c) {if (c && c.groupCollapsed) {
c.debug("%cfoo%cbar%c%cbaz%c", "font-weight: normal", "color: red", "font-weight: normal", "color: blue", "font-weight: normal");
}})(console);
EOF;
$this->assertEquals($expected, $this->generateScript());
}
public function testEscaping()
{
$handler = new BrowserConsoleHandler();
$handler->setFormatter($this->getIdentityFormatter());
$handler->handle($this->getRecord(Level::Debug, "[foo] [[\"bar\n[baz]\"]]{color: red}"));
$expected = <<<EOF
(function (c) {if (c && c.groupCollapsed) {
c.debug("%c[foo] %c\"bar\\n[baz]\"%c", "font-weight: normal", "color: red", "font-weight: normal");
}})(console);
EOF;
$this->assertEquals($expected, $this->generateScript());
}
public function testAutolabel()
{
$handler = new BrowserConsoleHandler();
$handler->setFormatter($this->getIdentityFormatter());
$handler->handle($this->getRecord(Level::Debug, '[[foo]]{macro: autolabel}'));
$handler->handle($this->getRecord(Level::Debug, '[[bar]]{macro: autolabel}'));
$handler->handle($this->getRecord(Level::Debug, '[[foo]]{macro: autolabel}'));
$expected = <<<EOF
(function (c) {if (c && c.groupCollapsed) {
c.debug("%c%cfoo%c", "font-weight: normal", "background-color: blue; color: white; border-radius: 3px; padding: 0 2px 0 2px", "font-weight: normal");
c.debug("%c%cbar%c", "font-weight: normal", "background-color: green; color: white; border-radius: 3px; padding: 0 2px 0 2px", "font-weight: normal");
c.debug("%c%cfoo%c", "font-weight: normal", "background-color: blue; color: white; border-radius: 3px; padding: 0 2px 0 2px", "font-weight: normal");
}})(console);
EOF;
$this->assertEquals($expected, $this->generateScript());
}
public function testContext()
{
$handler = new BrowserConsoleHandler();
$handler->setFormatter($this->getIdentityFormatter());
$handler->handle($this->getRecord(Level::Debug, 'test', ['foo' => 'bar', 0 => 'oop']));
$expected = <<<EOF
(function (c) {if (c && c.groupCollapsed) {
c.groupCollapsed("%ctest", "font-weight: normal");
c.log("%c%s", "font-weight: bold", "Context");
c.log("%s: %o", "foo", "bar");
c.log("%s: %o", "0", "oop");
c.groupEnd();
}})(console);
EOF;
$this->assertEquals($expected, $this->generateScript());
}
public function testConcurrentHandlers()
{
$handler1 = new BrowserConsoleHandler();
$handler1->setFormatter($this->getIdentityFormatter());
$handler2 = new BrowserConsoleHandler();
$handler2->setFormatter($this->getIdentityFormatter());
$handler1->handle($this->getRecord(Level::Debug, 'test1'));
$handler2->handle($this->getRecord(Level::Debug, 'test2'));
$handler1->handle($this->getRecord(Level::Debug, 'test3'));
$handler2->handle($this->getRecord(Level::Debug, 'test4'));
$expected = <<<EOF
(function (c) {if (c && c.groupCollapsed) {
c.debug("%ctest1", "font-weight: normal");
c.debug("%ctest2", "font-weight: normal");
c.debug("%ctest3", "font-weight: normal");
c.debug("%ctest4", "font-weight: normal");
}})(console);
EOF;
$this->assertEquals($expected, $this->generateScript());
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/ElasticsearchHandlerTest.php | tests/Monolog/Handler/ElasticsearchHandlerTest.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use Monolog\Formatter\ElasticsearchFormatter;
use Monolog\Formatter\NormalizerFormatter;
use Monolog\Level;
use Elasticsearch\Client;
use Elastic\Elasticsearch\Client as Client8;
use Elasticsearch\ClientBuilder;
use Elastic\Elasticsearch\ClientBuilder as ClientBuilder8;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
#[Group('Elasticsearch')]
#[CoversClass(ElasticsearchHandler::class)]
class ElasticsearchHandlerTest extends \Monolog\Test\MonologTestCase
{
protected Client|Client8 $client;
/**
* @var array Default handler options
*/
protected array $options = [
'index' => 'my_index',
'type' => 'doc_type',
'op_type' => 'index',
];
public function setUp(): void
{
$hosts = ['http://elastic:changeme@127.0.0.1:9200'];
$this->client = $this->getClientBuilder()
->setHosts($hosts)
->build();
try {
$this->client->info();
} catch (\Throwable $e) {
$this->markTestSkipped('Could not connect to Elasticsearch on 127.0.0.1:9200');
}
}
public function tearDown(): void
{
parent::tearDown();
unset($this->client);
}
public function testSetFormatter()
{
$handler = new ElasticsearchHandler($this->client);
$formatter = new ElasticsearchFormatter('index_new', 'type_new');
$handler->setFormatter($formatter);
$this->assertInstanceOf('Monolog\Formatter\ElasticsearchFormatter', $handler->getFormatter());
$this->assertEquals('index_new', $handler->getFormatter()->getIndex());
$this->assertEquals('type_new', $handler->getFormatter()->getType());
}
public function testSetFormatterInvalid()
{
$handler = new ElasticsearchHandler($this->client);
$formatter = new NormalizerFormatter();
$this->expectException(\InvalidArgumentException::class);
$this->expectExceptionMessage('ElasticsearchHandler is only compatible with ElasticsearchFormatter');
$handler->setFormatter($formatter);
}
public function testOptions()
{
$expected = [
'index' => $this->options['index'],
'type' => $this->options['type'],
'ignore_error' => false,
'op_type' => $this->options['op_type'],
];
if ($this->client instanceof Client8 || $this->client::VERSION[0] === '7') {
$expected['type'] = '_doc';
}
$handler = new ElasticsearchHandler($this->client, $this->options);
$this->assertEquals($expected, $handler->getOptions());
}
#[DataProvider('providerTestConnectionErrors')]
public function testConnectionErrors($ignore, $expectedError)
{
$hosts = ['http://127.0.0.1:1'];
$client = $this->getClientBuilder()
->setHosts($hosts)
->build();
$handlerOpts = ['ignore_error' => $ignore];
$handler = new ElasticsearchHandler($client, $handlerOpts);
if ($expectedError) {
$this->expectException($expectedError[0]);
$this->expectExceptionMessage($expectedError[1]);
$handler->handle($this->getRecord());
} else {
$this->assertFalse($handler->handle($this->getRecord()));
}
}
public static function providerTestConnectionErrors(): array
{
return [
[false, ['RuntimeException', 'Error sending messages to Elasticsearch']],
[true, false],
];
}
/**
* Integration test using localhost Elasticsearch server
*
* @covers Monolog\Handler\ElasticsearchHandler::__construct
* @covers Monolog\Handler\ElasticsearchHandler::handleBatch
* @covers Monolog\Handler\ElasticsearchHandler::bulkSend
* @covers Monolog\Handler\ElasticsearchHandler::getDefaultFormatter
*/
public function testHandleBatchIntegration()
{
$msg = $this->getRecord(Level::Error, 'log', context: ['foo' => 7, 'bar', 'class' => new \stdClass], datetime: new \DateTimeImmutable("@0"));
$expected = $msg->toArray();
$expected['datetime'] = $msg['datetime']->format(\DateTime::ATOM);
$expected['context'] = [
'class' => ["stdClass" => []],
'foo' => 7,
0 => 'bar',
];
$hosts = ['http://elastic:changeme@127.0.0.1:9200'];
$client = $this->getClientBuilder()
->setHosts($hosts)
->build();
$handler = new ElasticsearchHandler($client, $this->options);
$handler->handleBatch([$msg]);
// check document id from ES server response
if ($client instanceof Client8) {
$messageBody = $client->getTransport()->getLastResponse()->getBody();
$info = json_decode((string) $messageBody, true);
$this->assertNotNull($info, 'Decoding failed');
$documentId = $this->getCreatedDocIdV8($info);
$this->assertNotEmpty($documentId, 'No elastic document id received');
} else {
$documentId = $this->getCreatedDocId($client->transport->getLastConnection()->getLastRequestInfo());
$this->assertNotEmpty($documentId, 'No elastic document id received');
}
// retrieve document source from ES and validate
$document = $this->getDocSourceFromElastic(
$client,
$this->options['index'],
$this->options['type'],
$documentId
);
$this->assertEquals($expected, $document);
// remove test index from ES
$client->indices()->delete(['index' => $this->options['index']]);
}
/**
* Return last created document id from ES response
*
* @param array $info Elasticsearch last request info
*/
protected function getCreatedDocId(array $info): ?string
{
$data = json_decode($info['response']['body'], true);
if (!empty($data['items'][0]['index']['_id'])) {
return $data['items'][0]['index']['_id'];
}
return null;
}
/**
* Return last created document id from ES response
*
* @param array $data Elasticsearch last request info
* @return string|null
*/
protected function getCreatedDocIdV8(array $data)
{
if (!empty($data['items'][0]['index']['_id'])) {
return $data['items'][0]['index']['_id'];
}
return null;
}
/**
* Retrieve document by id from Elasticsearch
*
* @return array<mixed>
*/
protected function getDocSourceFromElastic(Client|Client8 $client, string $index, string $type, string $documentId): array
{
$params = [
'index' => $index,
'id' => $documentId,
];
if (!$client instanceof Client8 && $client::VERSION[0] !== '7') {
$params['type'] = $type;
}
$data = $client->get($params);
if (!empty($data['_source'])) {
return $data['_source'];
}
return [];
}
/**
* @return ClientBuilder|ClientBuilder8
*/
private function getClientBuilder()
{
if (class_exists(ClientBuilder8::class)) {
return ClientBuilder8::create();
}
return ClientBuilder::create();
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/GelfHandlerTest.php | tests/Monolog/Handler/GelfHandlerTest.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use Gelf\Message;
use Monolog\Level;
use Monolog\Formatter\GelfMessageFormatter;
class GelfHandlerTest extends \Monolog\Test\MonologTestCase
{
public function setUp(): void
{
if (!class_exists('Gelf\Publisher') || !class_exists('Gelf\Message')) {
$this->markTestSkipped("graylog2/gelf-php not installed");
}
}
/**
* @covers Monolog\Handler\GelfHandler::__construct
*/
public function testConstruct()
{
$handler = new GelfHandler($this->getMessagePublisher());
$this->assertInstanceOf('Monolog\Handler\GelfHandler', $handler);
}
protected function getHandler($messagePublisher)
{
$handler = new GelfHandler($messagePublisher);
return $handler;
}
protected function getMessagePublisher()
{
return $this->getMockBuilder('Gelf\Publisher')
->onlyMethods(['publish'])
->disableOriginalConstructor()
->getMock();
}
public function testDebug()
{
$record = $this->getRecord(Level::Debug, "A test debug message");
$expectedMessage = new Message();
$expectedMessage
->setLevel(7)
->setAdditional('facility', 'test')
->setShortMessage($record->message)
->setTimestamp($record->datetime)
;
$messagePublisher = $this->getMessagePublisher();
$messagePublisher->expects($this->once())
->method('publish')
->with($expectedMessage);
$handler = $this->getHandler($messagePublisher);
$handler->handle($record);
}
public function testWarning()
{
$record = $this->getRecord(Level::Warning, "A test warning message");
$expectedMessage = new Message();
$expectedMessage
->setLevel(4)
->setAdditional('facility', 'test')
->setShortMessage($record->message)
->setTimestamp($record->datetime)
;
$messagePublisher = $this->getMessagePublisher();
$messagePublisher->expects($this->once())
->method('publish')
->with($expectedMessage);
$handler = $this->getHandler($messagePublisher);
$handler->handle($record);
}
public function testInjectedGelfMessageFormatter()
{
$record = $this->getRecord(
Level::Warning,
"A test warning message",
extra: ['blarg' => 'yep'],
context: ['from' => 'logger'],
);
$expectedMessage = new Message();
$expectedMessage
->setLevel(4)
->setAdditional('facility', 'test')
->setHost("mysystem")
->setShortMessage($record->message)
->setTimestamp($record->datetime)
->setAdditional("EXTblarg", 'yep')
->setAdditional("CTXfrom", 'logger')
;
$messagePublisher = $this->getMessagePublisher();
$messagePublisher->expects($this->once())
->method('publish')
->with($expectedMessage);
$handler = $this->getHandler($messagePublisher);
$handler->setFormatter(new GelfMessageFormatter('mysystem', 'EXT', 'CTX'));
$handler->handle($record);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/LogmaticHandlerTest.php | tests/Monolog/Handler/LogmaticHandlerTest.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use Monolog\Level;
use PHPUnit\Framework\MockObject\MockObject;
/**
* @author Julien Breux <julien.breux@gmail.com>
*/
class LogmaticHandlerTest extends \Monolog\Test\MonologTestCase
{
/**
* @var resource
*/
private $res;
private LogmaticHandler&MockObject $handler;
public function tearDown(): void
{
parent::tearDown();
unset($this->res);
unset($this->handler);
}
public function testWriteContent()
{
$this->createHandler();
$this->handler->handle($this->getRecord(Level::Critical, 'Critical write test'));
fseek($this->res, 0);
$content = fread($this->res, 1024);
$this->assertMatchesRegularExpression('/testToken {"message":"Critical write test","context":{},"level":500,"level_name":"CRITICAL","channel":"test","datetime":"(.*)","extra":{},"hostname":"testHostname","appname":"testAppname","@marker":\["sourcecode","php"\]}/', $content);
}
public function testWriteBatchContent()
{
$records = [
$this->getRecord(),
$this->getRecord(),
$this->getRecord(),
];
$this->createHandler();
$this->handler->handleBatch($records);
fseek($this->res, 0);
$content = fread($this->res, 1024);
$this->assertMatchesRegularExpression('/testToken {"message":"test","context":{},"level":300,"level_name":"WARNING","channel":"test","datetime":"(.*)","extra":{},"hostname":"testHostname","appname":"testAppname","@marker":\["sourcecode","php"\]}/', $content);
}
private function createHandler()
{
$useSSL = \extension_loaded('openssl');
$args = ['testToken', 'testHostname', 'testAppname', $useSSL, Level::Debug, true];
$this->res = fopen('php://memory', 'a');
$this->handler = $this->getMockBuilder('Monolog\Handler\LogmaticHandler')
->setConstructorArgs($args)
->onlyMethods(['fsockopen', 'streamSetTimeout', 'closeSocket'])
->getMock();
$reflectionProperty = new \ReflectionProperty('Monolog\Handler\SocketHandler', 'connectionString');
$reflectionProperty->setValue($this->handler, 'localhost:1234');
$this->handler->expects($this->any())
->method('fsockopen')
->willReturn($this->res);
$this->handler->expects($this->any())
->method('streamSetTimeout')
->willReturn(true);
$this->handler->expects($this->any())
->method('closeSocket');
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/FingersCrossedHandlerTest.php | tests/Monolog/Handler/FingersCrossedHandlerTest.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use Monolog\Level;
use Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy;
use Monolog\Handler\FingersCrossed\ChannelLevelActivationStrategy;
use Psr\Log\LogLevel;
class FingersCrossedHandlerTest extends \Monolog\Test\MonologTestCase
{
/**
* @covers Monolog\Handler\FingersCrossedHandler::__construct
* @covers Monolog\Handler\FingersCrossedHandler::handle
* @covers Monolog\Handler\FingersCrossedHandler::activate
*/
public function testHandleBuffers()
{
$test = new TestHandler();
$handler = new FingersCrossedHandler($test);
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Info));
$this->assertFalse($test->hasDebugRecords());
$this->assertFalse($test->hasInfoRecords());
$handler->handle($this->getRecord(Level::Warning));
$handler->close();
$this->assertTrue($test->hasInfoRecords());
$this->assertCount(3, $test->getRecords());
}
/**
* @covers Monolog\Handler\FingersCrossedHandler::handle
* @covers Monolog\Handler\FingersCrossedHandler::activate
*/
public function testHandleStopsBufferingAfterTrigger()
{
$test = new TestHandler();
$handler = new FingersCrossedHandler($test);
$handler->handle($this->getRecord(Level::Warning));
$handler->handle($this->getRecord(Level::Debug));
$handler->close();
$this->assertTrue($test->hasWarningRecords());
$this->assertTrue($test->hasDebugRecords());
}
/**
* @covers Monolog\Handler\FingersCrossedHandler::handle
* @covers Monolog\Handler\FingersCrossedHandler::activate
* @covers Monolog\Handler\FingersCrossedHandler::reset
*/
public function testHandleResetBufferingAfterReset()
{
$test = new TestHandler();
$test->setSkipReset(true);
$handler = new FingersCrossedHandler($test);
$handler->handle($this->getRecord(Level::Warning));
$handler->handle($this->getRecord(Level::Debug));
$handler->reset();
$handler->handle($this->getRecord(Level::Info));
$handler->close();
$this->assertTrue($test->hasWarningRecords());
$this->assertTrue($test->hasDebugRecords());
$this->assertFalse($test->hasInfoRecords());
}
/**
* @covers Monolog\Handler\FingersCrossedHandler::handle
* @covers Monolog\Handler\FingersCrossedHandler::activate
*/
public function testHandleResetBufferingAfterBeingTriggeredWhenStopBufferingIsDisabled()
{
$test = new TestHandler();
$handler = new FingersCrossedHandler($test, Level::Warning, 0, false, false);
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Warning));
$handler->handle($this->getRecord(Level::Info));
$handler->close();
$this->assertTrue($test->hasWarningRecords());
$this->assertTrue($test->hasDebugRecords());
$this->assertFalse($test->hasInfoRecords());
}
/**
* @covers Monolog\Handler\FingersCrossedHandler::handle
* @covers Monolog\Handler\FingersCrossedHandler::activate
*/
public function testHandleBufferLimit()
{
$test = new TestHandler();
$handler = new FingersCrossedHandler($test, Level::Warning, 2);
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Info));
$handler->handle($this->getRecord(Level::Warning));
$this->assertTrue($test->hasWarningRecords());
$this->assertTrue($test->hasInfoRecords());
$this->assertFalse($test->hasDebugRecords());
}
/**
* @covers Monolog\Handler\FingersCrossedHandler::handle
* @covers Monolog\Handler\FingersCrossedHandler::activate
*/
public function testHandleWithCallback()
{
$test = new TestHandler();
$handler = new FingersCrossedHandler(function ($record, $handler) use ($test) {
return $test;
});
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Info));
$this->assertFalse($test->hasDebugRecords());
$this->assertFalse($test->hasInfoRecords());
$handler->handle($this->getRecord(Level::Warning));
$this->assertTrue($test->hasInfoRecords());
$this->assertCount(3, $test->getRecords());
}
/**
* @covers Monolog\Handler\FingersCrossedHandler::handle
* @covers Monolog\Handler\FingersCrossedHandler::activate
*/
public function testHandleWithBadCallbackThrowsException()
{
$handler = new FingersCrossedHandler(function ($record, $handler) {
return 'foo';
});
$this->expectException(\RuntimeException::class);
$handler->handle($this->getRecord(Level::Warning));
}
/**
* @covers Monolog\Handler\FingersCrossedHandler::isHandling
*/
public function testIsHandlingAlways()
{
$test = new TestHandler();
$handler = new FingersCrossedHandler($test, Level::Error);
$this->assertTrue($handler->isHandling($this->getRecord(Level::Debug)));
}
/**
* @covers Monolog\Handler\FingersCrossedHandler::__construct
* @covers Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy::__construct
* @covers Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy::isHandlerActivated
*/
public function testErrorLevelActivationStrategy()
{
$test = new TestHandler();
$handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy(Level::Warning));
$handler->handle($this->getRecord(Level::Debug));
$this->assertFalse($test->hasDebugRecords());
$handler->handle($this->getRecord(Level::Warning));
$this->assertTrue($test->hasDebugRecords());
$this->assertTrue($test->hasWarningRecords());
}
/**
* @covers Monolog\Handler\FingersCrossedHandler::__construct
* @covers Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy::__construct
* @covers Monolog\Handler\FingersCrossed\ErrorLevelActivationStrategy::isHandlerActivated
*/
public function testErrorLevelActivationStrategyWithPsrLevel()
{
$test = new TestHandler();
$handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy('warning'));
$handler->handle($this->getRecord(Level::Debug));
$this->assertFalse($test->hasDebugRecords());
$handler->handle($this->getRecord(Level::Warning));
$this->assertTrue($test->hasDebugRecords());
$this->assertTrue($test->hasWarningRecords());
}
/**
* @covers Monolog\Handler\FingersCrossedHandler::__construct
* @covers Monolog\Handler\FingersCrossedHandler::activate
*/
public function testOverrideActivationStrategy()
{
$test = new TestHandler();
$handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy('warning'));
$handler->handle($this->getRecord(Level::Debug));
$this->assertFalse($test->hasDebugRecords());
$handler->activate();
$this->assertTrue($test->hasDebugRecords());
$handler->handle($this->getRecord(Level::Info));
$this->assertTrue($test->hasInfoRecords());
}
/**
* @covers Monolog\Handler\FingersCrossed\ChannelLevelActivationStrategy::__construct
* @covers Monolog\Handler\FingersCrossed\ChannelLevelActivationStrategy::isHandlerActivated
*/
public function testChannelLevelActivationStrategy()
{
$test = new TestHandler();
$handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy(Level::Error, ['othertest' => Level::Debug]));
$handler->handle($this->getRecord(Level::Warning));
$this->assertFalse($test->hasWarningRecords());
$record = $this->getRecord(Level::Debug, channel: 'othertest');
$handler->handle($record);
$this->assertTrue($test->hasDebugRecords());
$this->assertTrue($test->hasWarningRecords());
}
/**
* @covers Monolog\Handler\FingersCrossed\ChannelLevelActivationStrategy::__construct
* @covers Monolog\Handler\FingersCrossed\ChannelLevelActivationStrategy::isHandlerActivated
*/
public function testChannelLevelActivationStrategyWithPsrLevels()
{
$test = new TestHandler();
$handler = new FingersCrossedHandler($test, new ChannelLevelActivationStrategy('error', ['othertest' => 'debug']));
$handler->handle($this->getRecord(Level::Warning));
$this->assertFalse($test->hasWarningRecords());
$record = $this->getRecord(Level::Debug, channel: 'othertest');
$handler->handle($record);
$this->assertTrue($test->hasDebugRecords());
$this->assertTrue($test->hasWarningRecords());
}
/**
* @covers Monolog\Handler\FingersCrossedHandler::handle
* @covers Monolog\Handler\FingersCrossedHandler::activate
*/
public function testHandleUsesProcessors()
{
$test = new TestHandler();
$handler = new FingersCrossedHandler($test, Level::Info);
$handler->pushProcessor(function ($record) {
$record->extra['foo'] = true;
return $record;
});
$handler->handle($this->getRecord(Level::Warning));
$this->assertTrue($test->hasWarningRecords());
$records = $test->getRecords();
$this->assertTrue($records[0]['extra']['foo']);
}
/**
* @covers Monolog\Handler\FingersCrossedHandler::close
*/
public function testPassthruOnClose()
{
$test = new TestHandler();
$handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy(Level::Warning), 0, true, true, Level::Info);
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Info));
$handler->handle($this->getRecord(Level::Notice));
$handler->close();
$this->assertFalse($test->hasDebugRecords());
$this->assertTrue($test->hasInfoRecords());
$this->assertTrue($test->hasNoticeRecords());
}
/**
* @covers Monolog\Handler\FingersCrossedHandler::close
*/
public function testPsrLevelPassthruOnClose()
{
$test = new TestHandler();
$handler = new FingersCrossedHandler($test, new ErrorLevelActivationStrategy(Level::Warning), 0, true, true, LogLevel::INFO);
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Info));
$handler->handle($this->getRecord(Level::Notice));
$handler->close();
$this->assertFalse($test->hasDebugRecords());
$this->assertTrue($test->hasInfoRecords());
$this->assertTrue($test->hasNoticeRecords());
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/OverflowHandlerTest.php | tests/Monolog/Handler/OverflowHandlerTest.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use Monolog\Level;
/**
* @author Kris Buist <krisbuist@gmail.com>
* @covers \Monolog\Handler\OverflowHandler
*/
class OverflowHandlerTest extends \Monolog\Test\MonologTestCase
{
public function testNotPassingRecordsBeneathLogLevel()
{
$testHandler = new TestHandler();
$handler = new OverflowHandler($testHandler, [], Level::Info);
$handler->handle($this->getRecord(Level::Debug));
$this->assertFalse($testHandler->hasDebugRecords());
}
public function testPassThroughWithoutThreshold()
{
$testHandler = new TestHandler();
$handler = new OverflowHandler($testHandler, [], Level::Info);
$handler->handle($this->getRecord(Level::Info, 'Info 1'));
$handler->handle($this->getRecord(Level::Info, 'Info 2'));
$handler->handle($this->getRecord(Level::Warning, 'Warning 1'));
$this->assertTrue($testHandler->hasInfoThatContains('Info 1'));
$this->assertTrue($testHandler->hasInfoThatContains('Info 2'));
$this->assertTrue($testHandler->hasWarningThatContains('Warning 1'));
}
/**
* @test
*/
public function testHoldingMessagesBeneathThreshold()
{
$testHandler = new TestHandler();
$handler = new OverflowHandler($testHandler, [Level::Info->value => 3]);
$handler->handle($this->getRecord(Level::Debug, 'debug 1'));
$handler->handle($this->getRecord(Level::Debug, 'debug 2'));
foreach (range(1, 3) as $i) {
$handler->handle($this->getRecord(Level::Info, 'info ' . $i));
}
$this->assertTrue($testHandler->hasDebugThatContains('debug 1'));
$this->assertTrue($testHandler->hasDebugThatContains('debug 2'));
$this->assertFalse($testHandler->hasInfoRecords());
$handler->handle($this->getRecord(Level::Info, 'info 4'));
foreach (range(1, 4) as $i) {
$this->assertTrue($testHandler->hasInfoThatContains('info ' . $i));
}
}
/**
* @test
*/
public function testCombinedThresholds()
{
$testHandler = new TestHandler();
$handler = new OverflowHandler($testHandler, [Level::Info->value => 5, Level::Warning->value => 10]);
$handler->handle($this->getRecord(Level::Debug));
foreach (range(1, 5) as $i) {
$handler->handle($this->getRecord(Level::Info, 'info ' . $i));
}
foreach (range(1, 10) as $i) {
$handler->handle($this->getRecord(Level::Warning, 'warning ' . $i));
}
// Only 1 DEBUG records
$this->assertCount(1, $testHandler->getRecords());
$handler->handle($this->getRecord(Level::Info, 'info final'));
// 1 DEBUG + 5 buffered INFO + 1 new INFO
$this->assertCount(7, $testHandler->getRecords());
$handler->handle($this->getRecord(Level::Warning, 'warning final'));
// 1 DEBUG + 6 INFO + 10 buffered WARNING + 1 new WARNING
$this->assertCount(18, $testHandler->getRecords());
$handler->handle($this->getRecord(Level::Info, 'Another info'));
$handler->handle($this->getRecord(Level::Warning, 'Anther warning'));
// 1 DEBUG + 6 INFO + 11 WARNING + 1 new INFO + 1 new WARNING
$this->assertCount(20, $testHandler->getRecords());
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/SlackWebhookHandlerTest.php | tests/Monolog/Handler/SlackWebhookHandlerTest.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use Monolog\Level;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\Slack\SlackRecord;
/**
* @author Haralan Dobrev <hkdobrev@gmail.com>
* @see https://api.slack.com/incoming-webhooks
* @coversDefaultClass Monolog\Handler\SlackWebhookHandler
*/
class SlackWebhookHandlerTest extends \Monolog\Test\MonologTestCase
{
const WEBHOOK_URL = 'https://hooks.slack.com/services/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E';
/**
* @covers ::__construct
* @covers ::getSlackRecord
*/
public function testConstructorMinimal()
{
$handler = new SlackWebhookHandler(self::WEBHOOK_URL);
$record = $this->getRecord();
$slackRecord = $handler->getSlackRecord();
$this->assertInstanceOf('Monolog\Handler\Slack\SlackRecord', $slackRecord);
$this->assertEquals([
'attachments' => [
[
'fallback' => 'test',
'text' => 'test',
'color' => SlackRecord::COLOR_WARNING,
'fields' => [
[
'title' => 'Level',
'value' => 'WARNING',
'short' => false,
],
],
'title' => 'Message',
'mrkdwn_in' => ['fields'],
'ts' => $record->datetime->getTimestamp(),
'footer' => null,
'footer_icon' => null,
],
],
], $slackRecord->getSlackData($record));
}
/**
* @covers ::__construct
* @covers ::getSlackRecord
*/
public function testConstructorFull()
{
$handler = new SlackWebhookHandler(
self::WEBHOOK_URL,
'test-channel',
'test-username',
false,
':ghost:',
false,
false,
Level::Debug,
false
);
$slackRecord = $handler->getSlackRecord();
$this->assertInstanceOf('Monolog\Handler\Slack\SlackRecord', $slackRecord);
$this->assertEquals([
'username' => 'test-username',
'text' => 'test',
'channel' => 'test-channel',
'icon_emoji' => ':ghost:',
], $slackRecord->getSlackData($this->getRecord()));
}
/**
* @covers ::__construct
* @covers ::getSlackRecord
*/
public function testConstructorFullWithAttachment()
{
$handler = new SlackWebhookHandler(
self::WEBHOOK_URL,
'test-channel-with-attachment',
'test-username-with-attachment',
true,
'https://www.example.com/example.png',
false,
false,
Level::Debug,
false
);
$record = $this->getRecord();
$slackRecord = $handler->getSlackRecord();
$this->assertInstanceOf('Monolog\Handler\Slack\SlackRecord', $slackRecord);
$this->assertEquals([
'username' => 'test-username-with-attachment',
'channel' => 'test-channel-with-attachment',
'attachments' => [
[
'fallback' => 'test',
'text' => 'test',
'color' => SlackRecord::COLOR_WARNING,
'fields' => [
[
'title' => 'Level',
'value' => Level::Warning->getName(),
'short' => false,
],
],
'mrkdwn_in' => ['fields'],
'ts' => $record['datetime']->getTimestamp(),
'footer' => 'test-username-with-attachment',
'footer_icon' => 'https://www.example.com/example.png',
'title' => 'Message',
],
],
'icon_url' => 'https://www.example.com/example.png',
], $slackRecord->getSlackData($record));
}
/**
* @covers ::getFormatter
*/
public function testGetFormatter()
{
$handler = new SlackWebhookHandler(self::WEBHOOK_URL);
$formatter = $handler->getFormatter();
$this->assertInstanceOf('Monolog\Formatter\FormatterInterface', $formatter);
}
/**
* @covers ::setFormatter
*/
public function testSetFormatter()
{
$handler = new SlackWebhookHandler(self::WEBHOOK_URL);
$formatter = new LineFormatter();
$handler->setFormatter($formatter);
$this->assertSame($formatter, $handler->getFormatter());
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/FleepHookHandlerTest.php | tests/Monolog/Handler/FleepHookHandlerTest.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use Monolog\Formatter\LineFormatter;
use Monolog\Level;
/**
* @coversDefaultClass \Monolog\Handler\FleepHookHandler
*/
class FleepHookHandlerTest extends \Monolog\Test\MonologTestCase
{
/**
* Default token to use in tests
*/
const TOKEN = '123abc';
private FleepHookHandler $handler;
public function setUp(): void
{
parent::setUp();
if (!\extension_loaded('openssl')) {
$this->markTestSkipped('This test requires openssl extension to run');
}
// Create instances of the handler and logger for convenience
$this->handler = new FleepHookHandler(self::TOKEN);
}
public function tearDown(): void
{
parent::tearDown();
unset($this->handler);
}
/**
* @covers ::__construct
*/
public function testConstructorSetsExpectedDefaults()
{
$this->assertEquals(Level::Debug, $this->handler->getLevel());
$this->assertEquals(true, $this->handler->getBubble());
}
/**
* @covers ::getDefaultFormatter
*/
public function testHandlerUsesLineFormatterWhichIgnoresEmptyArrays()
{
$record = $this->getRecord(Level::Debug, 'msg');
$expectedFormatter = new LineFormatter(null, null, true, true);
$expected = $expectedFormatter->format($record);
$handlerFormatter = $this->handler->getFormatter();
$actual = $handlerFormatter->format($record);
$this->assertEquals($expected, $actual, 'Empty context and extra arrays should not be rendered');
}
/**
* @covers ::__construct
*/
public function testConnectionStringisConstructedCorrectly()
{
$this->assertEquals('ssl://fleep.io:443', $this->handler->getConnectionString());
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/AbstractProcessingHandlerTest.php | tests/Monolog/Handler/AbstractProcessingHandlerTest.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use Monolog\Level;
use Monolog\Processor\WebProcessor;
use Monolog\Formatter\LineFormatter;
class AbstractProcessingHandlerTest extends \Monolog\Test\MonologTestCase
{
/**
* @covers Monolog\Handler\FormattableHandlerTrait::getFormatter
* @covers Monolog\Handler\FormattableHandlerTrait::setFormatter
*/
public function testConstructAndGetSet()
{
$handler = $this->getMockBuilder('Monolog\Handler\AbstractProcessingHandler')->setConstructorArgs([Level::Warning, false])->onlyMethods(['write'])->getMock();
$handler->setFormatter($formatter = new LineFormatter);
$this->assertSame($formatter, $handler->getFormatter());
}
/**
* @covers Monolog\Handler\AbstractProcessingHandler::handle
*/
public function testHandleLowerLevelMessage()
{
$handler = $this->getMockBuilder('Monolog\Handler\AbstractProcessingHandler')->setConstructorArgs([Level::Warning, true])->onlyMethods(['write'])->getMock();
$this->assertFalse($handler->handle($this->getRecord(Level::Debug)));
}
/**
* @covers Monolog\Handler\AbstractProcessingHandler::handle
*/
public function testHandleBubbling()
{
$handler = $this->getMockBuilder('Monolog\Handler\AbstractProcessingHandler')->setConstructorArgs([Level::Debug, true])->onlyMethods(['write'])->getMock();
$this->assertFalse($handler->handle($this->getRecord()));
}
/**
* @covers Monolog\Handler\AbstractProcessingHandler::handle
*/
public function testHandleNotBubbling()
{
$handler = $this->getMockBuilder('Monolog\Handler\AbstractProcessingHandler')->setConstructorArgs([Level::Debug, false])->onlyMethods(['write'])->getMock();
$this->assertTrue($handler->handle($this->getRecord()));
}
/**
* @covers Monolog\Handler\AbstractProcessingHandler::handle
*/
public function testHandleIsFalseWhenNotHandled()
{
$handler = $this->getMockBuilder('Monolog\Handler\AbstractProcessingHandler')->setConstructorArgs([Level::Warning, false])->onlyMethods(['write'])->getMock();
$this->assertTrue($handler->handle($this->getRecord()));
$this->assertFalse($handler->handle($this->getRecord(Level::Debug)));
}
/**
* @covers Monolog\Handler\AbstractProcessingHandler::processRecord
*/
public function testProcessRecord()
{
$handler = $this->createPartialMock('Monolog\Handler\AbstractProcessingHandler', ['write']);
$handler->pushProcessor(new WebProcessor([
'REQUEST_URI' => '',
'REQUEST_METHOD' => '',
'REMOTE_ADDR' => '',
'SERVER_NAME' => '',
'UNIQUE_ID' => '',
]));
$handledRecord = null;
$handler->expects($this->once())
->method('write')
->willReturnCallback(function ($record) use (&$handledRecord) {
$handledRecord = $record;
})
;
$handler->handle($this->getRecord());
$this->assertEquals(6, \count($handledRecord['extra']));
}
/**
* @covers Monolog\Handler\ProcessableHandlerTrait::pushProcessor
* @covers Monolog\Handler\ProcessableHandlerTrait::popProcessor
*/
public function testPushPopProcessor()
{
$logger = $this->createPartialMock('Monolog\Handler\AbstractProcessingHandler', ['write']);
$processor1 = new WebProcessor;
$processor2 = new WebProcessor;
$logger->pushProcessor($processor1);
$logger->pushProcessor($processor2);
$this->assertEquals($processor2, $logger->popProcessor());
$this->assertEquals($processor1, $logger->popProcessor());
$this->expectException(\LogicException::class);
$logger->popProcessor();
}
/**
* @covers Monolog\Handler\ProcessableHandlerTrait::pushProcessor
*/
public function testPushProcessorWithNonCallable()
{
$handler = $this->createPartialMock('Monolog\Handler\AbstractProcessingHandler', ['write']);
$this->expectException(\TypeError::class);
$handler->pushProcessor(new \stdClass());
}
/**
* @covers Monolog\Handler\FormattableHandlerTrait::getFormatter
* @covers Monolog\Handler\FormattableHandlerTrait::getDefaultFormatter
*/
public function testGetFormatterInitializesDefault()
{
$handler = $this->createPartialMock('Monolog\Handler\AbstractProcessingHandler', ['write']);
$this->assertInstanceOf(LineFormatter::class, $handler->getFormatter());
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/RedisHandlerTest.php | tests/Monolog/Handler/RedisHandlerTest.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use Monolog\Level;
use Monolog\Formatter\LineFormatter;
class RedisHandlerTest extends \Monolog\Test\MonologTestCase
{
public function testConstructorShouldWorkWithPredis()
{
$redis = $this->createMock('Predis\Client');
$this->assertInstanceof('Monolog\Handler\RedisHandler', new RedisHandler($redis, 'key'));
}
public function testConstructorShouldWorkWithRedis()
{
if (!class_exists('Redis')) {
$this->markTestSkipped('The redis ext is required to run this test');
}
$redis = $this->createMock('Redis');
$this->assertInstanceof('Monolog\Handler\RedisHandler', new RedisHandler($redis, 'key'));
}
public function testPredisHandle()
{
$redis = $this->getMockBuilder('Predis\Client')->getMock();
$redis->expects($this->atLeastOnce())
->method('__call')
->with(self::equalTo('rpush'), self::equalTo(['key', 'test']));
$record = $this->getRecord(Level::Warning, 'test', ['data' => new \stdClass, 'foo' => 34]);
$handler = new RedisHandler($redis, 'key');
$handler->setFormatter(new LineFormatter("%message%"));
$handler->handle($record);
}
public function testRedisHandle()
{
if (!class_exists('Redis')) {
$this->markTestSkipped('The redis ext is required to run this test');
}
$redis = $this->createPartialMock('Redis', ['rPush']);
// Redis uses rPush
$redis->expects($this->once())
->method('rPush')
->with('key', 'test');
$record = $this->getRecord(Level::Warning, 'test', ['data' => new \stdClass, 'foo' => 34]);
$handler = new RedisHandler($redis, 'key');
$handler->setFormatter(new LineFormatter("%message%"));
$handler->handle($record);
}
public function testRedisHandleCapped()
{
if (!class_exists('Redis')) {
$this->markTestSkipped('The redis ext is required to run this test');
}
$redis = $this->createPartialMock('Redis', ['multi', 'rPush', 'lTrim', 'exec']);
// Redis uses multi
$redis->expects($this->once())
->method('multi')
->willReturnSelf();
$redis->expects($this->once())
->method('rPush')
->willReturnSelf();
$redis->expects($this->once())
->method('lTrim')
->willReturnSelf();
$redis->expects($this->once())
->method('exec')
->willReturnSelf();
$record = $this->getRecord(Level::Warning, 'test', ['data' => new \stdClass, 'foo' => 34]);
$handler = new RedisHandler($redis, 'key', Level::Debug, true, 10);
$handler->setFormatter(new LineFormatter("%message%"));
$handler->handle($record);
}
public function testPredisHandleCapped()
{
$redis = new class extends \Predis\Client {
public array $testResults = [];
public function rpush(...$args)
{
$this->testResults[] = ['rpush', ...$args];
return $this;
}
public function ltrim(...$args)
{
$this->testResults[] = ['ltrim', ...$args];
return $this;
}
public function transaction(...$args)
{
$this->testResults[] = ['transaction start'];
return ($args[0])($this);
}
};
$record = $this->getRecord(Level::Warning, 'test', ['data' => new \stdClass, 'foo' => 34]);
$handler = new RedisHandler($redis, 'key', Level::Debug, true, 10);
$handler->setFormatter(new LineFormatter("%message%"));
$handler->handle($record);
self::assertsame([
['transaction start'],
['rpush', 'key', 'test'],
['ltrim', 'key', -10, -1],
], $redis->testResults);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/CouchDBHandlerTest.php | tests/Monolog/Handler/CouchDBHandlerTest.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use Monolog\Level;
class CouchDBHandlerTest extends \Monolog\Test\MonologTestCase
{
public function testHandle()
{
$record = $this->getRecord(Level::Warning, 'test', ['data' => new \stdClass, 'foo' => 34]);
$handler = new CouchDBHandler();
try {
$handler->handle($record);
} catch (\RuntimeException $e) {
$this->markTestSkipped('Could not connect to couchdb server on http://localhost:5984');
}
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/MailHandlerTest.php | tests/Monolog/Handler/MailHandlerTest.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use Monolog\Level;
class MailHandlerTest extends \Monolog\Test\MonologTestCase
{
/**
* @covers Monolog\Handler\MailHandler::handleBatch
*/
public function testHandleBatch()
{
$formatter = $this->createMock('Monolog\Formatter\FormatterInterface');
$formatter->expects($this->once())
->method('formatBatch'); // Each record is formatted
$handler = $this->createPartialMock('Monolog\Handler\MailHandler', ['send', 'write']);
$handler->expects($this->once())
->method('send');
$handler->expects($this->never())
->method('write'); // write is for individual records
$handler->setFormatter($formatter);
$handler->handleBatch($this->getMultipleRecords());
}
/**
* @covers Monolog\Handler\MailHandler::handleBatch
*/
public function testHandleBatchNotSendsMailIfMessagesAreBelowLevel()
{
$records = [
$this->getRecord(Level::Debug, 'debug message 1'),
$this->getRecord(Level::Debug, 'debug message 2'),
$this->getRecord(Level::Info, 'information'),
];
$handler = $this->createPartialMock('Monolog\Handler\MailHandler', ['send']);
$handler->expects($this->never())
->method('send');
$handler->setLevel(Level::Error);
$handler->handleBatch($records);
}
/**
* @covers Monolog\Handler\MailHandler::write
*/
public function testHandle()
{
$handler = $this->createPartialMock('Monolog\Handler\MailHandler', ['send']);
$handler->setFormatter(new \Monolog\Formatter\LineFormatter);
$record = $this->getRecord(message: 'test handle');
$record->formatted = '['.$record->datetime.'] test.WARNING: test handle [] []'."\n";
$handler->expects($this->once())
->method('send')
->with($record->formatted, [$record]);
$handler->handle($record);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/MongoDBHandlerTest.php | tests/Monolog/Handler/MongoDBHandlerTest.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use MongoDB\BSON\UTCDateTime;
use MongoDB\Client;
use MongoDB\Collection;
use MongoDB\Driver\Manager;
use PHPUnit\Framework\Attributes\RequiresPhpExtension;
#[RequiresPhpExtension('mongodb')]
class MongoDBHandlerTest extends \Monolog\Test\MonologTestCase
{
public function testConstructorShouldThrowExceptionForInvalidMongo()
{
$this->expectException(\TypeError::class);
new MongoDBHandler(new \stdClass, 'db', 'collection');
}
public function testHandleWithLibraryClient()
{
if (!class_exists(Client::class)) {
$this->markTestSkipped('mongodb/mongodb not installed');
}
$client = $this->getMockBuilder(Client::class)
->disableOriginalConstructor()
->getMock();
$collection = $this->getMockBuilder(Collection::class)
->disableOriginalConstructor()
->getMock();
$client->expects($this->once())
->method('getCollection')
->with('db', 'collection')
->willReturn($collection);
$record = $this->getRecord();
$expected = $record->toArray();
$expected['datetime'] = new UTCDateTime((int) floor(((float) $record->datetime->format('U.u')) * 1000));
$collection->expects($this->once())
->method('insertOne')
->with($expected);
$handler = new MongoDBHandler($client, 'db', 'collection');
$handler->handle($record);
}
public function testHandleWithDriverManager()
{
$manager = new Manager('mongodb://localhost:27017');
$handler = new MongoDBHandler($manager, 'test', 'monolog');
$record = $this->getRecord();
try {
$handler->handle($record);
} catch (\RuntimeException $e) {
$this->markTestSkipped('Could not connect to MongoDB server on mongodb://localhost:27017');
}
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/DeduplicationHandlerTest.php | tests/Monolog/Handler/DeduplicationHandlerTest.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler;
use Monolog\Level;
class DeduplicationHandlerTest extends \Monolog\Test\MonologTestCase
{
/**
* @covers Monolog\Handler\DeduplicationHandler::flush
*/
public function testFlushPassthruIfAllRecordsUnderTrigger()
{
$test = new TestHandler();
@unlink(sys_get_temp_dir().'/monolog_dedup.log');
$handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', Level::Debug);
$handler->handle($this->getRecord(Level::Debug));
$handler->handle($this->getRecord(Level::Info));
$handler->flush();
$this->assertTrue($test->hasInfoRecords());
$this->assertTrue($test->hasDebugRecords());
$this->assertFalse($test->hasWarningRecords());
}
/**
* @covers Monolog\Handler\DeduplicationHandler::flush
* @covers Monolog\Handler\DeduplicationHandler::appendRecord
*/
public function testFlushPassthruIfEmptyLog()
{
$test = new TestHandler();
@unlink(sys_get_temp_dir().'/monolog_dedup.log');
$handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', Level::Debug);
$handler->handle($this->getRecord(Level::Error, 'Foo:bar'));
$handler->handle($this->getRecord(Level::Critical, "Foo\nbar"));
$handler->flush();
$this->assertTrue($test->hasErrorRecords());
$this->assertTrue($test->hasCriticalRecords());
$this->assertFalse($test->hasWarningRecords());
}
/**
* @covers Monolog\Handler\DeduplicationHandler::flush
* @covers Monolog\Handler\DeduplicationHandler::appendRecord
* @covers Monolog\Handler\DeduplicationHandler::isDuplicate
* @depends testFlushPassthruIfEmptyLog
*/
public function testFlushSkipsIfLogExists()
{
$test = new TestHandler();
$handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', Level::Debug);
$handler->handle($this->getRecord(Level::Error, 'Foo:bar'));
$handler->handle($this->getRecord(Level::Critical, "Foo\nbar"));
$handler->flush();
$this->assertFalse($test->hasErrorRecords());
$this->assertFalse($test->hasCriticalRecords());
$this->assertFalse($test->hasWarningRecords());
}
/**
* @covers Monolog\Handler\DeduplicationHandler::flush
* @covers Monolog\Handler\DeduplicationHandler::appendRecord
* @covers Monolog\Handler\DeduplicationHandler::isDuplicate
* @depends testFlushPassthruIfEmptyLog
*/
public function testFlushPassthruIfLogTooOld()
{
$test = new TestHandler();
$handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', Level::Debug);
$record = $this->getRecord(Level::Error, datetime: new \DateTimeImmutable('+62seconds'));
$handler->handle($record);
$record = $this->getRecord(Level::Critical, datetime: new \DateTimeImmutable('+62seconds'));
$handler->handle($record);
$handler->flush();
$this->assertTrue($test->hasErrorRecords());
$this->assertTrue($test->hasCriticalRecords());
$this->assertFalse($test->hasWarningRecords());
}
/**
* @covers Monolog\Handler\DeduplicationHandler::flush
* @covers Monolog\Handler\DeduplicationHandler::appendRecord
* @covers Monolog\Handler\DeduplicationHandler::isDuplicate
* @covers Monolog\Handler\DeduplicationHandler::collectLogs
*/
public function testGcOldLogs()
{
$test = new TestHandler();
@unlink(sys_get_temp_dir().'/monolog_dedup.log');
$handler = new DeduplicationHandler($test, sys_get_temp_dir().'/monolog_dedup.log', Level::Debug);
// handle two records from yesterday, and one recent
$record = $this->getRecord(Level::Error, datetime: new \DateTimeImmutable('-1day -10seconds'));
$handler->handle($record);
$record2 = $this->getRecord(Level::Critical, datetime: new \DateTimeImmutable('-1day -10seconds'));
$handler->handle($record2);
$record3 = $this->getRecord(Level::Critical, datetime: new \DateTimeImmutable('-30seconds'));
$handler->handle($record3);
// log is written as none of them are duplicate
$handler->flush();
$this->assertSame(
$record->datetime->getTimestamp() . ":ERROR:test\n" .
$record2['datetime']->getTimestamp() . ":CRITICAL:test\n" .
$record3['datetime']->getTimestamp() . ":CRITICAL:test\n",
file_get_contents(sys_get_temp_dir() . '/monolog_dedup.log')
);
$this->assertTrue($test->hasErrorRecords());
$this->assertTrue($test->hasCriticalRecords());
$this->assertFalse($test->hasWarningRecords());
// clear test handler
$test->clear();
$this->assertFalse($test->hasErrorRecords());
$this->assertFalse($test->hasCriticalRecords());
// log new records, duplicate log gets GC'd at the end of this flush call
$handler->handle($record = $this->getRecord(Level::Error));
$handler->handle($record2 = $this->getRecord(Level::Critical));
$handler->flush();
// log should now contain the new errors and the previous one that was recent enough
$this->assertSame(
$record3['datetime']->getTimestamp() . ":CRITICAL:test\n" .
$record->datetime->getTimestamp() . ":ERROR:test\n" .
$record2['datetime']->getTimestamp() . ":CRITICAL:test\n",
file_get_contents(sys_get_temp_dir() . '/monolog_dedup.log')
);
$this->assertTrue($test->hasErrorRecords());
$this->assertTrue($test->hasCriticalRecords());
$this->assertFalse($test->hasWarningRecords());
}
public static function tearDownAfterClass(): void
{
@unlink(sys_get_temp_dir().'/monolog_dedup.log');
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Handler/Slack/SlackRecordTest.php | tests/Monolog/Handler/Slack/SlackRecordTest.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Handler\Slack;
use Monolog\Level;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
#[CoversClass(SlackRecord::class)]
class SlackRecordTest extends \Monolog\Test\MonologTestCase
{
public static function dataGetAttachmentColor()
{
return [
[Level::Debug, SlackRecord::COLOR_DEFAULT],
[Level::Info, SlackRecord::COLOR_GOOD],
[Level::Notice, SlackRecord::COLOR_GOOD],
[Level::Warning, SlackRecord::COLOR_WARNING],
[Level::Error, SlackRecord::COLOR_DANGER],
[Level::Critical, SlackRecord::COLOR_DANGER],
[Level::Alert, SlackRecord::COLOR_DANGER],
[Level::Emergency, SlackRecord::COLOR_DANGER],
];
}
#[DataProvider('dataGetAttachmentColor')]
public function testGetAttachmentColor(Level $logLevel, string $expectedColour)
{
$slackRecord = new SlackRecord();
$this->assertSame(
$expectedColour,
$slackRecord->getAttachmentColor($logLevel)
);
}
public function testAddsChannel()
{
$channel = '#test';
$record = new SlackRecord($channel);
$data = $record->getSlackData($this->getRecord());
$this->assertArrayHasKey('channel', $data);
$this->assertSame($channel, $data['channel']);
}
public function testNoUsernameByDefault()
{
$record = new SlackRecord();
$data = $record->getSlackData($this->getRecord());
$this->assertArrayNotHasKey('username', $data);
}
public static function dataStringify(): array
{
$multipleDimensions = [[1, 2]];
$numericKeys = ['library' => 'monolog'];
$singleDimension = [1, 'Hello', 'Jordi'];
return [
[[], '[]'],
[$multipleDimensions, json_encode($multipleDimensions, JSON_PRETTY_PRINT)],
[$numericKeys, json_encode($numericKeys, JSON_PRETTY_PRINT)],
[$singleDimension, json_encode($singleDimension)],
];
}
#[DataProvider('dataStringify')]
public function testStringify($fields, $expectedResult)
{
$slackRecord = new SlackRecord(
'#test',
'test',
true,
null,
true,
true
);
$this->assertSame($expectedResult, $slackRecord->stringify($fields));
}
public function testAddsCustomUsername()
{
$username = 'Monolog bot';
$record = new SlackRecord(null, $username);
$data = $record->getSlackData($this->getRecord());
$this->assertArrayHasKey('username', $data);
$this->assertSame($username, $data['username']);
}
public function testNoIcon()
{
$record = new SlackRecord();
$data = $record->getSlackData($this->getRecord());
$this->assertArrayNotHasKey('icon_emoji', $data);
}
public function testAddsIcon()
{
$record = $this->getRecord();
$slackRecord = new SlackRecord(null, null, false, 'ghost');
$data = $slackRecord->getSlackData($record);
$slackRecord2 = new SlackRecord(null, null, false, 'http://github.com/Seldaek/monolog');
$data2 = $slackRecord2->getSlackData($record);
$this->assertArrayHasKey('icon_emoji', $data);
$this->assertSame(':ghost:', $data['icon_emoji']);
$this->assertArrayHasKey('icon_url', $data2);
$this->assertSame('http://github.com/Seldaek/monolog', $data2['icon_url']);
}
public function testAttachmentsNotPresentIfNoAttachment()
{
$record = new SlackRecord(null, null, false);
$data = $record->getSlackData($this->getRecord());
$this->assertArrayNotHasKey('attachments', $data);
}
public function testAddsOneAttachment()
{
$record = new SlackRecord();
$data = $record->getSlackData($this->getRecord());
$this->assertArrayHasKey('attachments', $data);
$this->assertArrayHasKey(0, $data['attachments']);
$this->assertIsArray($data['attachments'][0]);
}
public function testTextEqualsMessageIfNoAttachment()
{
$message = 'Test message';
$record = new SlackRecord(null, null, false);
$data = $record->getSlackData($this->getRecord(Level::Warning, $message));
$this->assertArrayHasKey('text', $data);
$this->assertSame($message, $data['text']);
}
public function testTextEqualsFormatterOutput()
{
$formatter = $this->createMock('Monolog\\Formatter\\FormatterInterface');
$formatter
->expects($this->any())
->method('format')
->willReturnCallback(function ($record) {
return $record->message . 'test';
});
$formatter2 = $this->createMock('Monolog\\Formatter\\FormatterInterface');
$formatter2
->expects($this->any())
->method('format')
->willReturnCallback(function ($record) {
return $record->message . 'test1';
});
$message = 'Test message';
$record = new SlackRecord(null, null, false, null, false, false, [], $formatter);
$data = $record->getSlackData($this->getRecord(Level::Warning, $message));
$this->assertArrayHasKey('text', $data);
$this->assertSame($message . 'test', $data['text']);
$record->setFormatter($formatter2);
$data = $record->getSlackData($this->getRecord(Level::Warning, $message));
$this->assertArrayHasKey('text', $data);
$this->assertSame($message . 'test1', $data['text']);
}
public function testAddsFallbackAndTextToAttachment()
{
$message = 'Test message';
$record = new SlackRecord(null);
$data = $record->getSlackData($this->getRecord(Level::Warning, $message));
$this->assertSame($message, $data['attachments'][0]['text']);
$this->assertSame($message, $data['attachments'][0]['fallback']);
}
public function testMapsLevelToColorAttachmentColor()
{
$record = new SlackRecord(null);
$errorLoggerRecord = $this->getRecord(Level::Error);
$emergencyLoggerRecord = $this->getRecord(Level::Emergency);
$warningLoggerRecord = $this->getRecord(Level::Warning);
$infoLoggerRecord = $this->getRecord(Level::Info);
$debugLoggerRecord = $this->getRecord(Level::Debug);
$data = $record->getSlackData($errorLoggerRecord);
$this->assertSame(SlackRecord::COLOR_DANGER, $data['attachments'][0]['color']);
$data = $record->getSlackData($emergencyLoggerRecord);
$this->assertSame(SlackRecord::COLOR_DANGER, $data['attachments'][0]['color']);
$data = $record->getSlackData($warningLoggerRecord);
$this->assertSame(SlackRecord::COLOR_WARNING, $data['attachments'][0]['color']);
$data = $record->getSlackData($infoLoggerRecord);
$this->assertSame(SlackRecord::COLOR_GOOD, $data['attachments'][0]['color']);
$data = $record->getSlackData($debugLoggerRecord);
$this->assertSame(SlackRecord::COLOR_DEFAULT, $data['attachments'][0]['color']);
}
public function testAddsShortAttachmentWithoutContextAndExtra()
{
$level = Level::Error;
$levelName = $level->getName();
$record = new SlackRecord(null, null, true, null, true);
$data = $record->getSlackData($this->getRecord($level, 'test', ['test' => 1]));
$attachment = $data['attachments'][0];
$this->assertArrayHasKey('title', $attachment);
$this->assertArrayHasKey('fields', $attachment);
$this->assertSame($levelName, $attachment['title']);
$this->assertSame([], $attachment['fields']);
}
public function testAddsShortAttachmentWithContextAndExtra()
{
$level = Level::Error;
$levelName = $level->getName();
$context = ['test' => 1];
$extra = ['tags' => ['web']];
$record = new SlackRecord(null, null, true, null, true, true);
$loggerRecord = $this->getRecord($level, 'test', $context);
$loggerRecord['extra'] = $extra;
$data = $record->getSlackData($loggerRecord);
$attachment = $data['attachments'][0];
$this->assertArrayHasKey('title', $attachment);
$this->assertArrayHasKey('fields', $attachment);
$this->assertCount(2, $attachment['fields']);
$this->assertSame($levelName, $attachment['title']);
$this->assertSame(
[
[
'title' => 'Extra',
'value' => \sprintf('```%s```', json_encode($extra, JSON_PRETTY_PRINT)),
'short' => false,
],
[
'title' => 'Context',
'value' => \sprintf('```%s```', json_encode($context, JSON_PRETTY_PRINT)),
'short' => false,
],
],
$attachment['fields']
);
}
public function testAddsLongAttachmentWithoutContextAndExtra()
{
$level = Level::Error;
$levelName = $level->getName();
$record = new SlackRecord(null, null, true, null);
$data = $record->getSlackData($this->getRecord($level, 'test', ['test' => 1]));
$attachment = $data['attachments'][0];
$this->assertArrayHasKey('title', $attachment);
$this->assertArrayHasKey('fields', $attachment);
$this->assertCount(1, $attachment['fields']);
$this->assertSame('Message', $attachment['title']);
$this->assertSame(
[[
'title' => 'Level',
'value' => $levelName,
'short' => false,
]],
$attachment['fields']
);
}
public function testAddsLongAttachmentWithContextAndExtra()
{
$level = Level::Error;
$levelName = $level->getName();
$context = ['test' => 1];
$extra = ['tags' => ['web']];
$record = new SlackRecord(null, null, true, null, false, true);
$loggerRecord = $this->getRecord($level, 'test', $context);
$loggerRecord['extra'] = $extra;
$data = $record->getSlackData($loggerRecord);
$expectedFields = [
[
'title' => 'Level',
'value' => $levelName,
'short' => false,
],
[
'title' => 'Tags',
'value' => \sprintf('```%s```', json_encode($extra['tags'])),
'short' => false,
],
[
'title' => 'Test',
'value' => $context['test'],
'short' => false,
],
];
$attachment = $data['attachments'][0];
$this->assertArrayHasKey('title', $attachment);
$this->assertArrayHasKey('fields', $attachment);
$this->assertCount(3, $attachment['fields']);
$this->assertSame('Message', $attachment['title']);
$this->assertSame(
$expectedFields,
$attachment['fields']
);
}
public function testAddsTimestampToAttachment()
{
$record = $this->getRecord();
$slackRecord = new SlackRecord();
$data = $slackRecord->getSlackData($this->getRecord());
$attachment = $data['attachments'][0];
$this->assertArrayHasKey('ts', $attachment);
$this->assertSame($record->datetime->getTimestamp(), $attachment['ts']);
}
public function testContextHasException()
{
$record = $this->getRecord(Level::Critical, 'This is a critical message.', ['exception' => new \Exception()]);
$slackRecord = new SlackRecord(null, null, true, null, false, true);
$data = $slackRecord->getSlackData($record);
$this->assertIsString($data['attachments'][0]['fields'][1]['value']);
}
public function testExcludeExtraAndContextFields()
{
$record = $this->getRecord(
Level::Warning,
'test',
context: ['info' => ['library' => 'monolog', 'author' => 'Jordi']],
extra: ['tags' => ['web', 'cli']],
);
$slackRecord = new SlackRecord(null, null, true, null, false, true, ['context.info.library', 'extra.tags.1']);
$data = $slackRecord->getSlackData($record);
$attachment = $data['attachments'][0];
$expected = [
[
'title' => 'Info',
'value' => \sprintf('```%s```', json_encode(['author' => 'Jordi'], JSON_PRETTY_PRINT)),
'short' => false,
],
[
'title' => 'Tags',
'value' => \sprintf('```%s```', json_encode(['web'])),
'short' => false,
],
];
foreach ($expected as $field) {
$this->assertNotFalse(array_search($field, $attachment['fields']));
break;
}
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Attribute/WithMonologChannelTest.php | tests/Monolog/Attribute/WithMonologChannelTest.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Attribute;
class WithMonologChannelTest extends \Monolog\Test\MonologTestCase
{
public function test(): void
{
$attribute = new WithMonologChannel('fixture');
$this->assertSame('fixture', $attribute->channel);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
Seldaek/monolog | https://github.com/Seldaek/monolog/blob/b321dd6749f0bf7189444158a3ce785cc16d69b0/tests/Monolog/Attribute/AsMonologProcessorTest.php | tests/Monolog/Attribute/AsMonologProcessorTest.php | <?php declare(strict_types=1);
/*
* This file is part of the Monolog package.
*
* (c) Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Monolog\Attribute;
/**
* @requires PHP 8.0
*/
final class AsMonologProcessorTest extends \Monolog\Test\MonologTestCase
{
public function test(): void
{
$asMonologProcessor = new AsMonologProcessor('channel', 'handler', 'method', -10);
$this->assertSame('channel', $asMonologProcessor->channel);
$this->assertSame('handler', $asMonologProcessor->handler);
$this->assertSame('method', $asMonologProcessor->method);
$this->assertSame(-10, $asMonologProcessor->priority);
$asMonologProcessor = new AsMonologProcessor(null, null, null, null);
$this->assertNull($asMonologProcessor->channel);
$this->assertNull($asMonologProcessor->handler);
$this->assertNull($asMonologProcessor->method);
$this->assertNull($asMonologProcessor->priority);
}
}
| php | MIT | b321dd6749f0bf7189444158a3ce785cc16d69b0 | 2026-01-04T15:02:34.332473Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/Builder/Builder.php | Creational/Builder/Builder.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\Builder;
use DesignPatterns\Creational\Builder\Parts\Vehicle;
interface Builder
{
public function createVehicle(): void;
public function addWheel(): void;
public function addEngine(): void;
public function addDoors(): void;
public function getVehicle(): Vehicle;
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/Builder/TruckBuilder.php | Creational/Builder/TruckBuilder.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\Builder;
use DesignPatterns\Creational\Builder\Parts\Door;
use DesignPatterns\Creational\Builder\Parts\Engine;
use DesignPatterns\Creational\Builder\Parts\Wheel;
use DesignPatterns\Creational\Builder\Parts\Truck;
use DesignPatterns\Creational\Builder\Parts\Vehicle;
class TruckBuilder implements Builder
{
private Truck $truck;
public function addDoors(): void
{
$this->truck->setPart('rightDoor', new Door());
$this->truck->setPart('leftDoor', new Door());
}
public function addEngine(): void
{
$this->truck->setPart('truckEngine', new Engine());
}
public function addWheel(): void
{
$this->truck->setPart('wheel1', new Wheel());
$this->truck->setPart('wheel2', new Wheel());
$this->truck->setPart('wheel3', new Wheel());
$this->truck->setPart('wheel4', new Wheel());
$this->truck->setPart('wheel5', new Wheel());
$this->truck->setPart('wheel6', new Wheel());
}
public function createVehicle(): void
{
$this->truck = new Truck();
}
public function getVehicle(): Vehicle
{
return $this->truck;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/Builder/Director.php | Creational/Builder/Director.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\Builder;
use DesignPatterns\Creational\Builder\Parts\Vehicle;
/**
* Director is part of the builder pattern. It knows the interface of the builder
* and builds a complex object with the help of the builder
*
* You can also inject many builders instead of one to build more complex objects
*/
class Director
{
public function build(Builder $builder): Vehicle
{
$builder->createVehicle();
$builder->addDoors();
$builder->addEngine();
$builder->addWheel();
return $builder->getVehicle();
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/Builder/CarBuilder.php | Creational/Builder/CarBuilder.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\Builder;
use DesignPatterns\Creational\Builder\Parts\Door;
use DesignPatterns\Creational\Builder\Parts\Engine;
use DesignPatterns\Creational\Builder\Parts\Wheel;
use DesignPatterns\Creational\Builder\Parts\Car;
use DesignPatterns\Creational\Builder\Parts\Vehicle;
class CarBuilder implements Builder
{
private Car $car;
public function addDoors(): void
{
$this->car->setPart('rightDoor', new Door());
$this->car->setPart('leftDoor', new Door());
$this->car->setPart('trunkLid', new Door());
}
public function addEngine(): void
{
$this->car->setPart('engine', new Engine());
}
public function addWheel(): void
{
$this->car->setPart('wheelLF', new Wheel());
$this->car->setPart('wheelRF', new Wheel());
$this->car->setPart('wheelLR', new Wheel());
$this->car->setPart('wheelRR', new Wheel());
}
public function createVehicle(): void
{
$this->car = new Car();
}
public function getVehicle(): Vehicle
{
return $this->car;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/Builder/Parts/Door.php | Creational/Builder/Parts/Door.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\Builder\Parts;
class Door
{
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/Builder/Parts/Engine.php | Creational/Builder/Parts/Engine.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\Builder\Parts;
class Engine
{
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/Builder/Parts/Truck.php | Creational/Builder/Parts/Truck.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\Builder\Parts;
class Truck extends Vehicle
{
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/Builder/Parts/Car.php | Creational/Builder/Parts/Car.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\Builder\Parts;
class Car extends Vehicle
{
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/Builder/Parts/Vehicle.php | Creational/Builder/Parts/Vehicle.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\Builder\Parts;
abstract class Vehicle
{
final public function setPart(string $key, object $value)
{
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/Builder/Parts/Wheel.php | Creational/Builder/Parts/Wheel.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\Builder\Parts;
class Wheel
{
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/Builder/Tests/DirectorTest.php | Creational/Builder/Tests/DirectorTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\Builder\Tests;
use DesignPatterns\Creational\Builder\Parts\Car;
use DesignPatterns\Creational\Builder\Parts\Truck;
use DesignPatterns\Creational\Builder\TruckBuilder;
use DesignPatterns\Creational\Builder\CarBuilder;
use DesignPatterns\Creational\Builder\Director;
use PHPUnit\Framework\TestCase;
class DirectorTest extends TestCase
{
public function testCanBuildTruck()
{
$truckBuilder = new TruckBuilder();
$newVehicle = (new Director())->build($truckBuilder);
$this->assertInstanceOf(Truck::class, $newVehicle);
}
public function testCanBuildCar()
{
$carBuilder = new CarBuilder();
$newVehicle = (new Director())->build($carBuilder);
$this->assertInstanceOf(Car::class, $newVehicle);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/Pool/WorkerPool.php | Creational/Pool/WorkerPool.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\Pool;
use Countable;
class WorkerPool implements Countable
{
/**
* @var StringReverseWorker[]
*/
private array $occupiedWorkers = [];
/**
* @var StringReverseWorker[]
*/
private array $freeWorkers = [];
public function get(): StringReverseWorker
{
if (count($this->freeWorkers) === 0) {
$worker = new StringReverseWorker();
} else {
$worker = array_pop($this->freeWorkers);
}
$this->occupiedWorkers[spl_object_hash($worker)] = $worker;
return $worker;
}
public function dispose(StringReverseWorker $worker): void
{
$key = spl_object_hash($worker);
if (isset($this->occupiedWorkers[$key])) {
unset($this->occupiedWorkers[$key]);
$this->freeWorkers[$key] = $worker;
}
}
public function count(): int
{
return count($this->occupiedWorkers) + count($this->freeWorkers);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/Pool/StringReverseWorker.php | Creational/Pool/StringReverseWorker.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\Pool;
class StringReverseWorker
{
public function run(string $text): string
{
return strrev($text);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/Pool/Tests/PoolTest.php | Creational/Pool/Tests/PoolTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\Pool\Tests;
use DesignPatterns\Creational\Pool\WorkerPool;
use PHPUnit\Framework\TestCase;
class PoolTest extends TestCase
{
public function testCanGetNewInstancesWithGet()
{
$pool = new WorkerPool();
$worker1 = $pool->get();
$worker2 = $pool->get();
$this->assertCount(2, $pool);
$this->assertNotSame($worker1, $worker2);
}
public function testCanGetSameInstanceTwiceWhenDisposingItFirst()
{
$pool = new WorkerPool();
$worker1 = $pool->get();
$pool->dispose($worker1);
$worker2 = $pool->get();
$this->assertCount(1, $pool);
$this->assertSame($worker1, $worker2);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/SimpleFactory/SimpleFactory.php | Creational/SimpleFactory/SimpleFactory.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\SimpleFactory;
class SimpleFactory
{
public function createBicycle(): Bicycle
{
return new Bicycle();
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/SimpleFactory/Bicycle.php | Creational/SimpleFactory/Bicycle.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\SimpleFactory;
class Bicycle
{
public function driveTo(string $destination)
{
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/SimpleFactory/Tests/SimpleFactoryTest.php | Creational/SimpleFactory/Tests/SimpleFactoryTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\SimpleFactory\Tests;
use DesignPatterns\Creational\SimpleFactory\Bicycle;
use DesignPatterns\Creational\SimpleFactory\SimpleFactory;
use PHPUnit\Framework\TestCase;
class SimpleFactoryTest extends TestCase
{
public function testCanCreateBicycle()
{
$bicycle = (new SimpleFactory())->createBicycle();
$this->assertInstanceOf(Bicycle::class, $bicycle);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/Singleton/Singleton.php | Creational/Singleton/Singleton.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\Singleton;
use Exception;
final class Singleton
{
private static ?Singleton $instance = null;
/**
* gets the instance via lazy initialization (created on first usage)
*/
public static function getInstance(): Singleton
{
if (self::$instance === null) {
self::$instance = new self();
}
return self::$instance;
}
/**
* is not allowed to call from outside to prevent from creating multiple instances,
* to use the singleton, you have to obtain the instance from Singleton::getInstance() instead
*/
private function __construct()
{
}
/**
* prevent the instance from being cloned (which would create a second instance of it)
*/
private function __clone()
{
}
/**
* prevent from being unserialized (which would create a second instance of it)
*/
public function __wakeup()
{
throw new Exception("Cannot unserialize singleton");
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/Singleton/Tests/SingletonTest.php | Creational/Singleton/Tests/SingletonTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\Singleton\Tests;
use DesignPatterns\Creational\Singleton\Singleton;
use PHPUnit\Framework\TestCase;
class SingletonTest extends TestCase
{
public function testUniqueness()
{
$firstCall = Singleton::getInstance();
$secondCall = Singleton::getInstance();
$this->assertInstanceOf(Singleton::class, $firstCall);
$this->assertSame($firstCall, $secondCall);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/StaticFactory/FormatString.php | Creational/StaticFactory/FormatString.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\StaticFactory;
class FormatString implements Formatter
{
public function format(string $input): string
{
return $input;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/StaticFactory/FormatNumber.php | Creational/StaticFactory/FormatNumber.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\StaticFactory;
class FormatNumber implements Formatter
{
public function format(string $input): string
{
return number_format((int) $input);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/StaticFactory/Formatter.php | Creational/StaticFactory/Formatter.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\StaticFactory;
interface Formatter
{
public function format(string $input): string;
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/StaticFactory/StaticFactory.php | Creational/StaticFactory/StaticFactory.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\StaticFactory;
use InvalidArgumentException;
/**
* Note1: Remember, static means global state which is evil because it can't be mocked for tests
* Note2: Cannot be subclassed or mock-upped or have multiple different instances.
*/
final class StaticFactory
{
public static function factory(string $type): Formatter
{
return match ($type) {
'number' => new FormatNumber(),
'string' => new FormatString(),
default => throw new InvalidArgumentException('Unknown format given'),
};
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/StaticFactory/Tests/StaticFactoryTest.php | Creational/StaticFactory/Tests/StaticFactoryTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\StaticFactory\Tests;
use InvalidArgumentException;
use DesignPatterns\Creational\StaticFactory\FormatNumber;
use DesignPatterns\Creational\StaticFactory\FormatString;
use DesignPatterns\Creational\StaticFactory\StaticFactory;
use PHPUnit\Framework\TestCase;
class StaticFactoryTest extends TestCase
{
public function testCanCreateNumberFormatter()
{
$this->assertInstanceOf(FormatNumber::class, StaticFactory::factory('number'));
}
public function testCanCreateStringFormatter()
{
$this->assertInstanceOf(FormatString::class, StaticFactory::factory('string'));
}
public function testException()
{
$this->expectException(InvalidArgumentException::class);
StaticFactory::factory('object');
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/AbstractFactory/WinWriterFactory.php | Creational/AbstractFactory/WinWriterFactory.php | <?php
namespace DesignPatterns\Creational\AbstractFactory;
class WinWriterFactory implements WriterFactory
{
public function createCsvWriter(): CsvWriter
{
return new WinCsvWriter();
}
public function createJsonWriter(): JsonWriter
{
return new WinJsonWriter();
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/AbstractFactory/CsvWriter.php | Creational/AbstractFactory/CsvWriter.php | <?php
namespace DesignPatterns\Creational\AbstractFactory;
interface CsvWriter
{
public function write(array $line): string;
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/AbstractFactory/WriterFactory.php | Creational/AbstractFactory/WriterFactory.php | <?php
namespace DesignPatterns\Creational\AbstractFactory;
interface WriterFactory
{
public function createCsvWriter(): CsvWriter;
public function createJsonWriter(): JsonWriter;
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/AbstractFactory/UnixWriterFactory.php | Creational/AbstractFactory/UnixWriterFactory.php | <?php
namespace DesignPatterns\Creational\AbstractFactory;
class UnixWriterFactory implements WriterFactory
{
public function createCsvWriter(): CsvWriter
{
return new UnixCsvWriter();
}
public function createJsonWriter(): JsonWriter
{
return new UnixJsonWriter();
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/AbstractFactory/JsonWriter.php | Creational/AbstractFactory/JsonWriter.php | <?php
namespace DesignPatterns\Creational\AbstractFactory;
interface JsonWriter
{
public function write(array $data, bool $formatted): string;
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/AbstractFactory/UnixJsonWriter.php | Creational/AbstractFactory/UnixJsonWriter.php | <?php
namespace DesignPatterns\Creational\AbstractFactory;
class UnixJsonWriter implements JsonWriter
{
public function write(array $data, bool $formatted): string
{
$options = 0;
if ($formatted) {
$options = JSON_PRETTY_PRINT;
}
return json_encode($data, $options);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/AbstractFactory/UnixCsvWriter.php | Creational/AbstractFactory/UnixCsvWriter.php | <?php
namespace DesignPatterns\Creational\AbstractFactory;
class UnixCsvWriter implements CsvWriter
{
public function write(array $line): string
{
return join(',', $line) . "\n";
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/AbstractFactory/WinCsvWriter.php | Creational/AbstractFactory/WinCsvWriter.php | <?php
namespace DesignPatterns\Creational\AbstractFactory;
class WinCsvWriter implements CsvWriter
{
public function write(array $line): string
{
return join(',', $line) . "\r\n";
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/AbstractFactory/WinJsonWriter.php | Creational/AbstractFactory/WinJsonWriter.php | <?php
namespace DesignPatterns\Creational\AbstractFactory;
class WinJsonWriter implements JsonWriter
{
public function write(array $data, bool $formatted): string
{
$options = 0;
if ($formatted) {
$options = JSON_PRETTY_PRINT;
}
return json_encode($data, $options);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/AbstractFactory/Tests/AbstractFactoryTest.php | Creational/AbstractFactory/Tests/AbstractFactoryTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\AbstractFactory\Tests;
use DesignPatterns\Creational\AbstractFactory\CsvWriter;
use DesignPatterns\Creational\AbstractFactory\JsonWriter;
use DesignPatterns\Creational\AbstractFactory\UnixWriterFactory;
use DesignPatterns\Creational\AbstractFactory\WinWriterFactory;
use DesignPatterns\Creational\AbstractFactory\WriterFactory;
use PHPUnit\Framework\TestCase;
class AbstractFactoryTest extends TestCase
{
public function provideFactory()
{
return [
[new UnixWriterFactory()],
[new WinWriterFactory()]
];
}
/**
* @dataProvider provideFactory
*/
public function testCanCreateCsvWriterOnUnix(WriterFactory $writerFactory)
{
$this->assertInstanceOf(JsonWriter::class, $writerFactory->createJsonWriter());
$this->assertInstanceOf(CsvWriter::class, $writerFactory->createCsvWriter());
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/Prototype/FooBookPrototype.php | Creational/Prototype/FooBookPrototype.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\Prototype;
class FooBookPrototype extends BookPrototype
{
protected string $category = 'Foo';
public function __clone()
{
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/Prototype/BarBookPrototype.php | Creational/Prototype/BarBookPrototype.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\Prototype;
class BarBookPrototype extends BookPrototype
{
protected string $category = 'Bar';
public function __clone()
{
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/Prototype/BookPrototype.php | Creational/Prototype/BookPrototype.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\Prototype;
abstract class BookPrototype
{
protected string $title;
protected string $category;
abstract public function __clone();
final public function getTitle(): string
{
return $this->title;
}
final public function setTitle(string $title): void
{
$this->title = $title;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/Prototype/Tests/PrototypeTest.php | Creational/Prototype/Tests/PrototypeTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\Prototype\Tests;
use DesignPatterns\Creational\Prototype\BarBookPrototype;
use DesignPatterns\Creational\Prototype\FooBookPrototype;
use PHPUnit\Framework\TestCase;
class PrototypeTest extends TestCase
{
public function testCanGetFooBook()
{
$fooPrototype = new FooBookPrototype();
$barPrototype = new BarBookPrototype();
for ($i = 0; $i < 10; $i++) {
$book = clone $fooPrototype;
$book->setTitle('Foo Book No ' . $i);
$this->assertInstanceOf(FooBookPrototype::class, $book);
}
for ($i = 0; $i < 5; $i++) {
$book = clone $barPrototype;
$book->setTitle('Bar Book No ' . $i);
$this->assertInstanceOf(BarBookPrototype::class, $book);
}
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/FactoryMethod/StdoutLoggerFactory.php | Creational/FactoryMethod/StdoutLoggerFactory.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\FactoryMethod;
class StdoutLoggerFactory implements LoggerFactory
{
public function createLogger(): Logger
{
return new StdoutLogger();
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/FactoryMethod/LoggerFactory.php | Creational/FactoryMethod/LoggerFactory.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\FactoryMethod;
interface LoggerFactory
{
public function createLogger(): Logger;
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/FactoryMethod/FileLoggerFactory.php | Creational/FactoryMethod/FileLoggerFactory.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\FactoryMethod;
class FileLoggerFactory implements LoggerFactory
{
public function __construct(private string $filePath)
{
}
public function createLogger(): Logger
{
return new FileLogger($this->filePath);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/FactoryMethod/Logger.php | Creational/FactoryMethod/Logger.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\FactoryMethod;
interface Logger
{
public function log(string $message);
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/FactoryMethod/FileLogger.php | Creational/FactoryMethod/FileLogger.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\FactoryMethod;
class FileLogger implements Logger
{
public function __construct(private string $filePath)
{
}
public function log(string $message)
{
file_put_contents($this->filePath, $message . PHP_EOL, FILE_APPEND);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/FactoryMethod/StdoutLogger.php | Creational/FactoryMethod/StdoutLogger.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\FactoryMethod;
class StdoutLogger implements Logger
{
public function log(string $message)
{
echo $message;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Creational/FactoryMethod/Tests/FactoryMethodTest.php | Creational/FactoryMethod/Tests/FactoryMethodTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Creational\FactoryMethod\Tests;
use DesignPatterns\Creational\FactoryMethod\FileLogger;
use DesignPatterns\Creational\FactoryMethod\FileLoggerFactory;
use DesignPatterns\Creational\FactoryMethod\StdoutLogger;
use DesignPatterns\Creational\FactoryMethod\StdoutLoggerFactory;
use PHPUnit\Framework\TestCase;
class FactoryMethodTest extends TestCase
{
public function testCanCreateStdoutLogging()
{
$loggerFactory = new StdoutLoggerFactory();
$logger = $loggerFactory->createLogger();
$this->assertInstanceOf(StdoutLogger::class, $logger);
}
public function testCanCreateFileLogging()
{
$loggerFactory = new FileLoggerFactory(sys_get_temp_dir());
$logger = $loggerFactory->createLogger();
$this->assertInstanceOf(FileLogger::class, $logger);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Iterator/BookList.php | Behavioral/Iterator/BookList.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Iterator;
use Countable;
use Iterator;
class BookList implements Countable, Iterator
{
/**
* @var Book[]
*/
private array $books = [];
private int $currentIndex = 0;
public function addBook(Book $book)
{
$this->books[] = $book;
}
public function removeBook(Book $bookToRemove)
{
foreach ($this->books as $key => $book) {
if ($book->getAuthorAndTitle() === $bookToRemove->getAuthorAndTitle()) {
unset($this->books[$key]);
}
}
$this->books = array_values($this->books);
}
public function count(): int
{
return count($this->books);
}
public function current(): Book
{
return $this->books[$this->currentIndex];
}
public function key(): int
{
return $this->currentIndex;
}
public function next(): void
{
$this->currentIndex++;
}
public function rewind(): void
{
$this->currentIndex = 0;
}
public function valid(): bool
{
return isset($this->books[$this->currentIndex]);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Iterator/Book.php | Behavioral/Iterator/Book.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Iterator;
class Book
{
public function __construct(private string $title, private string $author)
{
}
public function getAuthor(): string
{
return $this->author;
}
public function getTitle(): string
{
return $this->title;
}
public function getAuthorAndTitle(): string
{
return $this->getTitle() . ' by ' . $this->getAuthor();
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Iterator/Tests/IteratorTest.php | Behavioral/Iterator/Tests/IteratorTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Iterator\Tests;
use DesignPatterns\Behavioral\Iterator\Book;
use DesignPatterns\Behavioral\Iterator\BookList;
use PHPUnit\Framework\TestCase;
class IteratorTest extends TestCase
{
public function testCanIterateOverBookList()
{
$bookList = new BookList();
$bookList->addBook(new Book('Learning PHP Design Patterns', 'William Sanders'));
$bookList->addBook(new Book('Professional Php Design Patterns', 'Aaron Saray'));
$bookList->addBook(new Book('Clean Code', 'Robert C. Martin'));
$books = [];
foreach ($bookList as $book) {
$books[] = $book->getAuthorAndTitle();
}
$this->assertSame(
[
'Learning PHP Design Patterns by William Sanders',
'Professional Php Design Patterns by Aaron Saray',
'Clean Code by Robert C. Martin',
],
$books
);
}
public function testCanIterateOverBookListAfterRemovingBook()
{
$book = new Book('Clean Code', 'Robert C. Martin');
$book2 = new Book('Professional Php Design Patterns', 'Aaron Saray');
$bookList = new BookList();
$bookList->addBook($book);
$bookList->addBook($book2);
$bookList->removeBook($book);
$books = [];
foreach ($bookList as $book) {
$books[] = $book->getAuthorAndTitle();
}
$this->assertSame(
['Professional Php Design Patterns by Aaron Saray'],
$books
);
}
public function testCanAddBookToList()
{
$book = new Book('Clean Code', 'Robert C. Martin');
$bookList = new BookList();
$bookList->addBook($book);
$this->assertCount(1, $bookList);
}
public function testCanRemoveBookFromList()
{
$book = new Book('Clean Code', 'Robert C. Martin');
$bookList = new BookList();
$bookList->addBook($book);
$bookList->removeBook($book);
$this->assertCount(0, $bookList);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/ChainOfResponsibilities/Handler.php | Behavioral/ChainOfResponsibilities/Handler.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\ChainOfResponsibilities;
use Psr\Http\Message\RequestInterface;
abstract class Handler
{
public function __construct(private ?Handler $successor = null)
{
}
/**
* This approach by using a template method pattern ensures you that
* each subclass will not forget to call the successor
*/
final public function handle(RequestInterface $request): ?string
{
$processed = $this->processing($request);
if ($processed === null && $this->successor !== null) {
// the request has not been processed by this handler => see the next
$processed = $this->successor->handle($request);
}
return $processed;
}
abstract protected function processing(RequestInterface $request): ?string;
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/ChainOfResponsibilities/Responsible/SlowDatabaseHandler.php | Behavioral/ChainOfResponsibilities/Responsible/SlowDatabaseHandler.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\ChainOfResponsibilities\Responsible;
use DesignPatterns\Behavioral\ChainOfResponsibilities\Handler;
use Psr\Http\Message\RequestInterface;
class SlowDatabaseHandler extends Handler
{
protected function processing(RequestInterface $request): ?string
{
// this is a mockup, in production code you would ask a slow (compared to in-memory) DB for the results
return 'Hello World!';
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/ChainOfResponsibilities/Responsible/HttpInMemoryCacheHandler.php | Behavioral/ChainOfResponsibilities/Responsible/HttpInMemoryCacheHandler.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\ChainOfResponsibilities\Responsible;
use DesignPatterns\Behavioral\ChainOfResponsibilities\Handler;
use Psr\Http\Message\RequestInterface;
class HttpInMemoryCacheHandler extends Handler
{
public function __construct(private array $data, ?Handler $successor = null)
{
parent::__construct($successor);
}
protected function processing(RequestInterface $request): ?string
{
$key = sprintf(
'%s?%s',
$request->getUri()->getPath(),
$request->getUri()->getQuery()
);
if ($request->getMethod() == 'GET' && isset($this->data[$key])) {
return $this->data[$key];
}
return null;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/ChainOfResponsibilities/Tests/ChainTest.php | Behavioral/ChainOfResponsibilities/Tests/ChainTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\ChainOfResponsibilities\Tests;
use DesignPatterns\Behavioral\ChainOfResponsibilities\Handler;
use DesignPatterns\Behavioral\ChainOfResponsibilities\Responsible\HttpInMemoryCacheHandler;
use DesignPatterns\Behavioral\ChainOfResponsibilities\Responsible\SlowDatabaseHandler;
use PHPUnit\Framework\TestCase;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\UriInterface;
class ChainTest extends TestCase
{
private Handler $chain;
protected function setUp(): void
{
$this->chain = new HttpInMemoryCacheHandler(
['/foo/bar?index=1' => 'Hello In Memory!'],
new SlowDatabaseHandler()
);
}
public function testCanRequestKeyInFastStorage()
{
$uri = $this->createMock(UriInterface::class);
$uri->method('getPath')->willReturn('/foo/bar');
$uri->method('getQuery')->willReturn('index=1');
$request = $this->createMock(RequestInterface::class);
$request->method('getMethod')
->willReturn('GET');
$request->method('getUri')->willReturn($uri);
$this->assertSame('Hello In Memory!', $this->chain->handle($request));
}
public function testCanRequestKeyInSlowStorage()
{
$uri = $this->createMock(UriInterface::class);
$uri->method('getPath')->willReturn('/foo/baz');
$uri->method('getQuery')->willReturn('');
$request = $this->createMock(RequestInterface::class);
$request->method('getMethod')
->willReturn('GET');
$request->method('getUri')->willReturn($uri);
$this->assertSame('Hello World!', $this->chain->handle($request));
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Strategy/Comparator.php | Behavioral/Strategy/Comparator.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Strategy;
interface Comparator
{
/**
* @param mixed $a
* @param mixed $b
*/
public function compare($a, $b): int;
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Strategy/Context.php | Behavioral/Strategy/Context.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Strategy;
class Context
{
public function __construct(private Comparator $comparator)
{
}
public function executeStrategy(array $elements): array
{
uasort($elements, [$this->comparator, 'compare']);
return $elements;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Strategy/DateComparator.php | Behavioral/Strategy/DateComparator.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Strategy;
use DateTime;
class DateComparator implements Comparator
{
public function compare($a, $b): int
{
$aDate = new DateTime($a['date']);
$bDate = new DateTime($b['date']);
return $aDate <=> $bDate;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Strategy/IdComparator.php | Behavioral/Strategy/IdComparator.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Strategy;
class IdComparator implements Comparator
{
public function compare($a, $b): int
{
return $a['id'] <=> $b['id'];
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Strategy/Tests/StrategyTest.php | Behavioral/Strategy/Tests/StrategyTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Strategy\Tests;
use DesignPatterns\Behavioral\Strategy\Context;
use DesignPatterns\Behavioral\Strategy\DateComparator;
use DesignPatterns\Behavioral\Strategy\IdComparator;
use PHPUnit\Framework\TestCase;
class StrategyTest extends TestCase
{
public function provideIntegers()
{
return [
[
[['id' => 2], ['id' => 1], ['id' => 3]],
['id' => 1],
],
[
[['id' => 3], ['id' => 2], ['id' => 1]],
['id' => 1],
],
];
}
public function provideDates()
{
return [
[
[['date' => '2014-03-03'], ['date' => '2015-03-02'], ['date' => '2013-03-01']],
['date' => '2013-03-01'],
],
[
[['date' => '2014-02-03'], ['date' => '2013-02-01'], ['date' => '2015-02-02']],
['date' => '2013-02-01'],
],
];
}
/**
* @dataProvider provideIntegers
*
* @param array $collection
* @param array $expected
*/
public function testIdComparator($collection, $expected)
{
$obj = new Context(new IdComparator());
$elements = $obj->executeStrategy($collection);
$firstElement = array_shift($elements);
$this->assertSame($expected, $firstElement);
}
/**
* @dataProvider provideDates
*
* @param array $collection
* @param array $expected
*/
public function testDateComparator($collection, $expected)
{
$obj = new Context(new DateComparator());
$elements = $obj->executeStrategy($collection);
$firstElement = array_shift($elements);
$this->assertSame($expected, $firstElement);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Memento/State.php | Behavioral/Memento/State.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Memento;
use InvalidArgumentException;
class State implements \Stringable
{
public const STATE_CREATED = 'created';
public const STATE_OPENED = 'opened';
public const STATE_ASSIGNED = 'assigned';
public const STATE_CLOSED = 'closed';
private string $state;
/**
* @var string[]
*/
private static array $validStates = [
self::STATE_CREATED,
self::STATE_OPENED,
self::STATE_ASSIGNED,
self::STATE_CLOSED,
];
public function __construct(string $state)
{
self::ensureIsValidState($state);
$this->state = $state;
}
private static function ensureIsValidState(string $state)
{
if (!in_array($state, self::$validStates)) {
throw new InvalidArgumentException('Invalid state given');
}
}
public function __toString(): string
{
return $this->state;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Memento/Ticket.php | Behavioral/Memento/Ticket.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Memento;
/**
* Ticket is the "Originator" in this implementation
*/
class Ticket
{
private State $currentState;
public function __construct()
{
$this->currentState = new State(State::STATE_CREATED);
}
public function open()
{
$this->currentState = new State(State::STATE_OPENED);
}
public function assign()
{
$this->currentState = new State(State::STATE_ASSIGNED);
}
public function close()
{
$this->currentState = new State(State::STATE_CLOSED);
}
public function saveToMemento(): Memento
{
return new Memento(clone $this->currentState);
}
public function restoreFromMemento(Memento $memento)
{
$this->currentState = $memento->getState();
}
public function getState(): State
{
return $this->currentState;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Memento/Memento.php | Behavioral/Memento/Memento.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Memento;
class Memento
{
public function __construct(private State $state)
{
}
public function getState(): State
{
return $this->state;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Memento/Tests/MementoTest.php | Behavioral/Memento/Tests/MementoTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Memento\Tests;
use DesignPatterns\Behavioral\Memento\State;
use DesignPatterns\Behavioral\Memento\Ticket;
use PHPUnit\Framework\TestCase;
class MementoTest extends TestCase
{
public function testOpenTicketAssignAndSetBackToOpen()
{
$ticket = new Ticket();
// open the ticket
$ticket->open();
$openedState = $ticket->getState();
$this->assertSame(State::STATE_OPENED, (string) $ticket->getState());
$memento = $ticket->saveToMemento();
// assign the ticket
$ticket->assign();
$this->assertSame(State::STATE_ASSIGNED, (string) $ticket->getState());
// now restore to the opened state, but verify that the state object has been cloned for the memento
$ticket->restoreFromMemento($memento);
$this->assertSame(State::STATE_OPENED, (string) $ticket->getState());
$this->assertNotSame($openedState, $ticket->getState());
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Visitor/RecordingVisitor.php | Behavioral/Visitor/RecordingVisitor.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Visitor;
class RecordingVisitor implements RoleVisitor
{
/**
* @var Role[]
*/
private array $visited = [];
public function visitGroup(Group $role)
{
$this->visited[] = $role;
}
public function visitUser(User $role)
{
$this->visited[] = $role;
}
/**
* @return Role[]
*/
public function getVisited(): array
{
return $this->visited;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Visitor/User.php | Behavioral/Visitor/User.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Visitor;
class User implements Role
{
public function __construct(private string $name)
{
}
public function getName(): string
{
return sprintf('User %s', $this->name);
}
public function accept(RoleVisitor $visitor)
{
$visitor->visitUser($this);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Visitor/RoleVisitor.php | Behavioral/Visitor/RoleVisitor.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Visitor;
/**
* Note: the visitor must not choose itself which method to
* invoke, it is the visited object that makes this decision
*/
interface RoleVisitor
{
public function visitUser(User $role);
public function visitGroup(Group $role);
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Visitor/Role.php | Behavioral/Visitor/Role.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Visitor;
interface Role
{
public function accept(RoleVisitor $visitor);
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Visitor/Group.php | Behavioral/Visitor/Group.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Visitor;
class Group implements Role
{
public function __construct(private string $name)
{
}
public function getName(): string
{
return sprintf('Group: %s', $this->name);
}
public function accept(RoleVisitor $visitor)
{
$visitor->visitGroup($this);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Visitor/Tests/VisitorTest.php | Behavioral/Visitor/Tests/VisitorTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Tests\Visitor\Tests;
use DesignPatterns\Behavioral\Visitor\RecordingVisitor;
use DesignPatterns\Behavioral\Visitor\User;
use DesignPatterns\Behavioral\Visitor\Group;
use DesignPatterns\Behavioral\Visitor\Role;
use DesignPatterns\Behavioral\Visitor;
use PHPUnit\Framework\TestCase;
class VisitorTest extends TestCase
{
private RecordingVisitor $visitor;
protected function setUp(): void
{
$this->visitor = new RecordingVisitor();
}
public function provideRoles()
{
return [
[new User('Dominik')],
[new Group('Administrators')],
];
}
/**
* @dataProvider provideRoles
*/
public function testVisitSomeRole(Role $role)
{
$role->accept($this->visitor);
$this->assertSame($role, $this->visitor->getVisited()[0]);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/NullObject/PrintLogger.php | Behavioral/NullObject/PrintLogger.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\NullObject;
class PrintLogger implements Logger
{
public function log(string $str)
{
echo $str;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/NullObject/Service.php | Behavioral/NullObject/Service.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\NullObject;
class Service
{
public function __construct(private Logger $logger)
{
}
/**
* do something ...
*/
public function doSomething()
{
// notice here that you don't have to check if the logger is set with eg. is_null(), instead just use it
$this->logger->log('We are in ' . __METHOD__);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/NullObject/NullLogger.php | Behavioral/NullObject/NullLogger.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\NullObject;
class NullLogger implements Logger
{
public function log(string $str)
{
// do nothing
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/NullObject/Logger.php | Behavioral/NullObject/Logger.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\NullObject;
/**
* Key feature: NullLogger must inherit from this interface like any other loggers
*/
interface Logger
{
public function log(string $str);
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/NullObject/Tests/LoggerTest.php | Behavioral/NullObject/Tests/LoggerTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\NullObject\Tests;
use DesignPatterns\Behavioral\NullObject\NullLogger;
use DesignPatterns\Behavioral\NullObject\PrintLogger;
use DesignPatterns\Behavioral\NullObject\Service;
use PHPUnit\Framework\TestCase;
class LoggerTest extends TestCase
{
public function testNullObject()
{
$service = new Service(new NullLogger());
$this->expectOutputString('');
$service->doSomething();
}
public function testStandardLogger()
{
$service = new Service(new PrintLogger());
$this->expectOutputString('We are in DesignPatterns\Behavioral\NullObject\Service::doSomething');
$service->doSomething();
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/State/OrderDone.php | Behavioral/State/OrderDone.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\State;
class OrderDone implements StateOrder
{
public function proceedToNext(ContextOrder $context): void
{
// there is nothing more to do
}
public function toString(): string
{
return 'done';
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/State/ShippingOrder.php | Behavioral/State/ShippingOrder.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\State;
class ShippingOrder implements StateOrder
{
public function proceedToNext(ContextOrder $context): void
{
$context->setState(new OrderDone());
}
public function toString(): string
{
return 'shipped';
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/State/ContextOrder.php | Behavioral/State/ContextOrder.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\State;
class ContextOrder
{
private StateOrder $state;
public static function create(): ContextOrder
{
$order = new self();
$order->state = new CreateOrder();
return $order;
}
public function setState(StateOrder $state): void
{
$this->state = $state;
}
public function proceedToNext(): void
{
$this->state->proceedToNext($this);
}
public function toString(): string
{
return $this->state->toString();
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/State/CreateOrder.php | Behavioral/State/CreateOrder.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\State;
class CreateOrder implements StateOrder
{
public function proceedToNext(ContextOrder $context): void
{
$context->setState(new ShippingOrder());
}
public function toString(): string
{
return 'created';
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/State/StateOrder.php | Behavioral/State/StateOrder.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\State;
interface StateOrder
{
public function proceedToNext(ContextOrder $context): void;
public function toString(): string;
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/State/Tests/StateTest.php | Behavioral/State/Tests/StateTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\State\Tests;
use DesignPatterns\Behavioral\State\ContextOrder;
use PHPUnit\Framework\TestCase;
class StateTest extends TestCase
{
public function testIsCreatedWithStateCreated(): void
{
$orderContext = ContextOrder::create();
$this->assertSame('created', $orderContext->toString());
}
public function testCanProceedToStateShipped(): void
{
$contextOrder = ContextOrder::create();
$contextOrder->proceedToNext();
$this->assertSame('shipped', $contextOrder->toString());
}
public function testCanProceedToStateDone(): void
{
$contextOrder = ContextOrder::create();
$contextOrder->proceedToNext();
$contextOrder->proceedToNext();
$this->assertSame('done', $contextOrder->toString());
}
public function testStateDoneIsTheLastPossibleState(): void
{
$contextOrder = ContextOrder::create();
$contextOrder->proceedToNext();
$contextOrder->proceedToNext();
$contextOrder->proceedToNext();
$this->assertSame('done', $contextOrder->toString());
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Specification/Specification.php | Behavioral/Specification/Specification.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Specification;
interface Specification
{
public function isSatisfiedBy(Item $item): bool;
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Specification/AndSpecification.php | Behavioral/Specification/AndSpecification.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Specification;
class AndSpecification implements Specification
{
/**
* @var Specification[]
*/
private array $specifications;
/**
* @param Specification[] $specifications
*/
public function __construct(Specification ...$specifications)
{
$this->specifications = $specifications;
}
/**
* if at least one specification is false, return false, else return true.
*/
public function isSatisfiedBy(Item $item): bool
{
foreach ($this->specifications as $specification) {
if (!$specification->isSatisfiedBy($item)) {
return false;
}
}
return true;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.