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 |
|---|---|---|---|---|---|---|---|---|
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Specification/PriceSpecification.php | Behavioral/Specification/PriceSpecification.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Specification;
class PriceSpecification implements Specification
{
public function __construct(private ?float $minPrice, private ?float $maxPrice)
{
}
public function isSatisfiedBy(Item $item): bool
{
if ($this->maxPrice !== null && $item->getPrice() > $this->maxPrice) {
return false;
}
if ($this->minPrice !== null && $item->getPrice() < $this->minPrice) {
return false;
}
return true;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Specification/NotSpecification.php | Behavioral/Specification/NotSpecification.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Specification;
class NotSpecification implements Specification
{
public function __construct(private Specification $specification)
{
}
public function isSatisfiedBy(Item $item): bool
{
return !$this->specification->isSatisfiedBy($item);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Specification/OrSpecification.php | Behavioral/Specification/OrSpecification.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Specification;
class OrSpecification implements Specification
{
/**
* @var Specification[]
*/
private array $specifications;
/**
* @param Specification[] $specifications
*/
public function __construct(Specification ...$specifications)
{
$this->specifications = $specifications;
}
/*
* if at least one specification is true, return true, else return false
*/
public function isSatisfiedBy(Item $item): bool
{
foreach ($this->specifications as $specification) {
if ($specification->isSatisfiedBy($item)) {
return true;
}
}
return false;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Specification/Item.php | Behavioral/Specification/Item.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Specification;
class Item
{
public function __construct(private float $price)
{
}
public function getPrice(): float
{
return $this->price;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Specification/Tests/SpecificationTest.php | Behavioral/Specification/Tests/SpecificationTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Specification\Tests;
use DesignPatterns\Behavioral\Specification\Item;
use DesignPatterns\Behavioral\Specification\NotSpecification;
use DesignPatterns\Behavioral\Specification\OrSpecification;
use DesignPatterns\Behavioral\Specification\AndSpecification;
use DesignPatterns\Behavioral\Specification\PriceSpecification;
use PHPUnit\Framework\TestCase;
class SpecificationTest extends TestCase
{
public function testCanOr()
{
$spec1 = new PriceSpecification(50, 99);
$spec2 = new PriceSpecification(101, 200);
$orSpec = new OrSpecification($spec1, $spec2);
$this->assertFalse($orSpec->isSatisfiedBy(new Item(100)));
$this->assertTrue($orSpec->isSatisfiedBy(new Item(51)));
$this->assertTrue($orSpec->isSatisfiedBy(new Item(150)));
}
public function testCanAnd()
{
$spec1 = new PriceSpecification(50, 100);
$spec2 = new PriceSpecification(80, 200);
$andSpec = new AndSpecification($spec1, $spec2);
$this->assertFalse($andSpec->isSatisfiedBy(new Item(150)));
$this->assertFalse($andSpec->isSatisfiedBy(new Item(1)));
$this->assertFalse($andSpec->isSatisfiedBy(new Item(51)));
$this->assertTrue($andSpec->isSatisfiedBy(new Item(100)));
}
public function testCanNot()
{
$spec1 = new PriceSpecification(50, 100);
$notSpec = new NotSpecification($spec1);
$this->assertTrue($notSpec->isSatisfiedBy(new Item(150)));
$this->assertFalse($notSpec->isSatisfiedBy(new Item(50)));
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Interpreter/VariableExp.php | Behavioral/Interpreter/VariableExp.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Interpreter;
/**
* This TerminalExpression
*/
class VariableExp extends AbstractExp
{
public function __construct(private string $name)
{
}
public function interpret(Context $context): bool
{
return $context->lookUp($this->name);
}
public function getName(): string
{
return $this->name;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Interpreter/AbstractExp.php | Behavioral/Interpreter/AbstractExp.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Interpreter;
abstract class AbstractExp
{
abstract public function interpret(Context $context): bool;
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Interpreter/Context.php | Behavioral/Interpreter/Context.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Interpreter;
use Exception;
class Context
{
private array $poolVariable;
public function lookUp(string $name): bool
{
if (!key_exists($name, $this->poolVariable)) {
throw new Exception("no exist variable: $name");
}
return $this->poolVariable[$name];
}
public function assign(VariableExp $variable, bool $val)
{
$this->poolVariable[$variable->getName()] = $val;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Interpreter/AndExp.php | Behavioral/Interpreter/AndExp.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Interpreter;
/**
* This NoTerminalExpression
*/
class AndExp extends AbstractExp
{
public function __construct(private AbstractExp $first, private AbstractExp $second)
{
}
public function interpret(Context $context): bool
{
return $this->first->interpret($context) && $this->second->interpret($context);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Interpreter/OrExp.php | Behavioral/Interpreter/OrExp.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Interpreter;
/**
* This NoTerminalExpression
*/
class OrExp extends AbstractExp
{
public function __construct(private AbstractExp $first, private AbstractExp $second)
{
}
public function interpret(Context $context): bool
{
return $this->first->interpret($context) || $this->second->interpret($context);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Interpreter/Tests/InterpreterTest.php | Behavioral/Interpreter/Tests/InterpreterTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Interpreter\Tests;
use DesignPatterns\Behavioral\Interpreter\AndExp;
use DesignPatterns\Behavioral\Interpreter\Context;
use DesignPatterns\Behavioral\Interpreter\OrExp;
use DesignPatterns\Behavioral\Interpreter\VariableExp;
use PHPUnit\Framework\TestCase;
class InterpreterTest extends TestCase
{
private Context $context;
private VariableExp $a;
private VariableExp $b;
private VariableExp $c;
public function setUp(): void
{
$this->context = new Context();
$this->a = new VariableExp('A');
$this->b = new VariableExp('B');
$this->c = new VariableExp('C');
}
public function testOr()
{
$this->context->assign($this->a, false);
$this->context->assign($this->b, false);
$this->context->assign($this->c, true);
// A ∨ B
$exp1 = new OrExp($this->a, $this->b);
$result1 = $exp1->interpret($this->context);
$this->assertFalse($result1, 'A ∨ B must false');
// $exp1 ∨ C
$exp2 = new OrExp($exp1, $this->c);
$result2 = $exp2->interpret($this->context);
$this->assertTrue($result2, '(A ∨ B) ∨ C must true');
}
public function testAnd()
{
$this->context->assign($this->a, true);
$this->context->assign($this->b, true);
$this->context->assign($this->c, false);
// A ∧ B
$exp1 = new AndExp($this->a, $this->b);
$result1 = $exp1->interpret($this->context);
$this->assertTrue($result1, 'A ∧ B must true');
// $exp1 ∧ C
$exp2 = new AndExp($exp1, $this->c);
$result2 = $exp2->interpret($this->context);
$this->assertFalse($result2, '(A ∧ B) ∧ C must false');
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Observer/User.php | Behavioral/Observer/User.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Observer;
use SplSubject;
use SplObjectStorage;
use SplObserver;
/**
* User implements the observed object (called Subject), it maintains a list of observers and sends notifications to
* them in case changes are made on the User object
*/
class User implements SplSubject
{
private SplObjectStorage $observers;
private $email;
public function __construct()
{
$this->observers = new SplObjectStorage();
}
public function attach(SplObserver $observer): void
{
$this->observers->attach($observer);
}
public function detach(SplObserver $observer): void
{
$this->observers->detach($observer);
}
public function changeEmail(string $email): void
{
$this->email = $email;
$this->notify();
}
public function notify(): void
{
/** @var SplObserver $observer */
foreach ($this->observers as $observer) {
$observer->update($this);
}
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Observer/UserObserver.php | Behavioral/Observer/UserObserver.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Observer;
use SplObserver;
use SplSubject;
class UserObserver implements SplObserver
{
/**
* @var SplSubject[]
*/
private array $changedUsers = [];
/**
* It is called by the Subject, usually by SplSubject::notify()
*/
public function update(SplSubject $subject): void
{
$this->changedUsers[] = clone $subject;
}
/**
* @return SplSubject[]
*/
public function getChangedUsers(): array
{
return $this->changedUsers;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Observer/Tests/ObserverTest.php | Behavioral/Observer/Tests/ObserverTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Observer\Tests;
use DesignPatterns\Behavioral\Observer\User;
use DesignPatterns\Behavioral\Observer\UserObserver;
use PHPUnit\Framework\TestCase;
class ObserverTest extends TestCase
{
public function testChangeInUserLeadsToUserObserverBeingNotified()
{
$observer = new UserObserver();
$user = new User();
$user->attach($observer);
$user->changeEmail('foo@bar.com');
$this->assertCount(1, $observer->getChangedUsers());
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/TemplateMethod/CityJourney.php | Behavioral/TemplateMethod/CityJourney.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\TemplateMethod;
class CityJourney extends Journey
{
protected function enjoyVacation(): string
{
return "Eat, drink, take photos and sleep";
}
protected function buyGift(): ?string
{
return "Buy a gift";
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/TemplateMethod/Journey.php | Behavioral/TemplateMethod/Journey.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\TemplateMethod;
abstract class Journey
{
/**
* @var string[]
*/
private array $thingsToDo = [];
/**
* This is the public service provided by this class and its subclasses.
* Notice it is final to "freeze" the global behavior of algorithm.
* If you want to override this contract, make an interface with only takeATrip()
* and subclass it.
*/
final public function takeATrip()
{
$this->thingsToDo[] = $this->buyAFlight();
$this->thingsToDo[] = $this->takePlane();
$this->thingsToDo[] = $this->enjoyVacation();
$buyGift = $this->buyGift();
if ($buyGift !== null) {
$this->thingsToDo[] = $buyGift;
}
$this->thingsToDo[] = $this->takePlane();
}
/**
* This method must be implemented, this is the key-feature of this pattern.
*/
abstract protected function enjoyVacation(): string;
/**
* This method is also part of the algorithm but it is optional.
* You can override it only if you need to
*/
protected function buyGift(): ?string
{
return null;
}
private function buyAFlight(): string
{
return 'Buy a flight ticket';
}
private function takePlane(): string
{
return 'Taking the plane';
}
/**
* @return string[]
*/
final public function getThingsToDo(): array
{
return $this->thingsToDo;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/TemplateMethod/BeachJourney.php | Behavioral/TemplateMethod/BeachJourney.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\TemplateMethod;
class BeachJourney extends Journey
{
protected function enjoyVacation(): string
{
return "Swimming and sun-bathing";
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/TemplateMethod/Tests/JourneyTest.php | Behavioral/TemplateMethod/Tests/JourneyTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\TemplateMethod\Tests;
use DesignPatterns\Behavioral\TemplateMethod\BeachJourney;
use DesignPatterns\Behavioral\TemplateMethod\CityJourney;
use PHPUnit\Framework\TestCase;
class JourneyTest extends TestCase
{
public function testCanGetOnVacationOnTheBeach()
{
$beachJourney = new BeachJourney();
$beachJourney->takeATrip();
$this->assertSame(
['Buy a flight ticket', 'Taking the plane', 'Swimming and sun-bathing', 'Taking the plane'],
$beachJourney->getThingsToDo()
);
}
public function testCanGetOnAJourneyToACity()
{
$cityJourney = new CityJourney();
$cityJourney->takeATrip();
$this->assertSame(
[
'Buy a flight ticket',
'Taking the plane',
'Eat, drink, take photos and sleep',
'Buy a gift',
'Taking the plane'
],
$cityJourney->getThingsToDo()
);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Mediator/Ui.php | Behavioral/Mediator/Ui.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Mediator;
class Ui extends Colleague
{
public function outputUserInfo(string $username)
{
echo $this->mediator->getUser($username);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Mediator/Mediator.php | Behavioral/Mediator/Mediator.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Mediator;
interface Mediator
{
public function getUser(string $username): string;
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Mediator/Colleague.php | Behavioral/Mediator/Colleague.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Mediator;
abstract class Colleague
{
protected Mediator $mediator;
final public function setMediator(Mediator $mediator)
{
$this->mediator = $mediator;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Mediator/UserRepositoryUiMediator.php | Behavioral/Mediator/UserRepositoryUiMediator.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Mediator;
class UserRepositoryUiMediator implements Mediator
{
public function __construct(private UserRepository $userRepository, private Ui $ui)
{
$this->userRepository->setMediator($this);
$this->ui->setMediator($this);
}
public function printInfoAbout(string $user)
{
$this->ui->outputUserInfo($user);
}
public function getUser(string $username): string
{
return $this->userRepository->getUserName($username);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Mediator/UserRepository.php | Behavioral/Mediator/UserRepository.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Mediator;
class UserRepository extends Colleague
{
public function getUserName(string $user): string
{
return 'User: ' . $user;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Mediator/Tests/MediatorTest.php | Behavioral/Mediator/Tests/MediatorTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Tests\Mediator\Tests;
use DesignPatterns\Behavioral\Mediator\Ui;
use DesignPatterns\Behavioral\Mediator\UserRepository;
use DesignPatterns\Behavioral\Mediator\UserRepositoryUiMediator;
use PHPUnit\Framework\TestCase;
class MediatorTest extends TestCase
{
public function testOutputHelloWorld()
{
$mediator = new UserRepositoryUiMediator(new UserRepository(), new Ui());
$this->expectOutputString('User: Dominik');
$mediator->printInfoAbout('Dominik');
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Command/Invoker.php | Behavioral/Command/Invoker.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Command;
/**
* Invoker is using the command given to it.
* Example : an Application in SF2.
*/
class Invoker
{
private Command $command;
/**
* in the invoker we find this kind of method for subscribing the command
* There can be also a stack, a list, a fixed set ...
*/
public function setCommand(Command $cmd)
{
$this->command = $cmd;
}
/**
* executes the command; the invoker is the same whatever is the command
*/
public function run()
{
$this->command->execute();
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Command/Command.php | Behavioral/Command/Command.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Command;
interface Command
{
/**
* this is the most important method in the Command pattern,
* The Receiver goes in the constructor.
*/
public function execute();
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Command/UndoableCommand.php | Behavioral/Command/UndoableCommand.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Command;
interface UndoableCommand extends Command
{
/**
* This method is used to undo change made by command execution
*/
public function undo();
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Command/AddMessageDateCommand.php | Behavioral/Command/AddMessageDateCommand.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Command;
/**
* This concrete command tweaks receiver to add current date to messages
* invoker just knows that it can call "execute"
*/
class AddMessageDateCommand implements UndoableCommand
{
/**
* Each concrete command is built with different receivers.
* There can be one, many or completely no receivers, but there can be other commands in the parameters.
*/
public function __construct(private Receiver $output)
{
}
/**
* Execute and make receiver to enable displaying messages date.
*/
public function execute()
{
// sometimes, there is no receiver and this is the command which
// does all the work
$this->output->enableDate();
}
/**
* Undo the command and make receiver to disable displaying messages date.
*/
public function undo()
{
// sometimes, there is no receiver and this is the command which
// does all the work
$this->output->disableDate();
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Command/HelloCommand.php | Behavioral/Command/HelloCommand.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Command;
/**
* This concrete command calls "print" on the Receiver, but an external
* invoker just knows that it can call "execute"
*/
class HelloCommand implements Command
{
/**
* Each concrete command is built with different receivers.
* There can be one, many or completely no receivers, but there can be other commands in the parameters
*/
public function __construct(private Receiver $output)
{
}
/**
* execute and output "Hello World".
*/
public function execute()
{
// sometimes, there is no receiver and this is the command which does all the work
$this->output->write('Hello World');
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Command/Receiver.php | Behavioral/Command/Receiver.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Command;
/**
* Receiver is a specific service with its own contract and can be only concrete.
*/
class Receiver
{
private bool $enableDate = false;
/**
* @var string[]
*/
private array $output = [];
public function write(string $str)
{
if ($this->enableDate) {
$str .= ' [' . date('Y-m-d') . ']';
}
$this->output[] = $str;
}
public function getOutput(): string
{
return join("\n", $this->output);
}
/**
* Enable receiver to display message date
*/
public function enableDate()
{
$this->enableDate = true;
}
/**
* Disable receiver to display message date
*/
public function disableDate()
{
$this->enableDate = false;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Command/Tests/UndoableCommandTest.php | Behavioral/Command/Tests/UndoableCommandTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Command\Tests;
use DesignPatterns\Behavioral\Command\AddMessageDateCommand;
use DesignPatterns\Behavioral\Command\HelloCommand;
use DesignPatterns\Behavioral\Command\Invoker;
use DesignPatterns\Behavioral\Command\Receiver;
use PHPUnit\Framework\TestCase;
class UndoableCommandTest extends TestCase
{
public function testInvocation()
{
$invoker = new Invoker();
$receiver = new Receiver();
$invoker->setCommand(new HelloCommand($receiver));
$invoker->run();
$this->assertSame('Hello World', $receiver->getOutput());
$messageDateCommand = new AddMessageDateCommand($receiver);
$messageDateCommand->execute();
$invoker->run();
$this->assertSame("Hello World\nHello World [" . date('Y-m-d') . ']', $receiver->getOutput());
$messageDateCommand->undo();
$invoker->run();
$this->assertSame("Hello World\nHello World [" . date('Y-m-d') . "]\nHello World", $receiver->getOutput());
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Behavioral/Command/Tests/CommandTest.php | Behavioral/Command/Tests/CommandTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Behavioral\Command\Tests;
use DesignPatterns\Behavioral\Command\HelloCommand;
use DesignPatterns\Behavioral\Command\Invoker;
use DesignPatterns\Behavioral\Command\Receiver;
use PHPUnit\Framework\TestCase;
class CommandTest extends TestCase
{
public function testInvocation()
{
$invoker = new Invoker();
$receiver = new Receiver();
$invoker->setCommand(new HelloCommand($receiver));
$invoker->run();
$this->assertSame('Hello World', $receiver->getOutput());
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Registry/Registry.php | Structural/Registry/Registry.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Registry;
use InvalidArgumentException;
abstract class Registry
{
public const LOGGER = 'logger';
/**
* this introduces global state in your application which can not be mocked up for testing
* and is therefor considered an anti-pattern! Use dependency injection instead!
*
* @var Service[]
*/
private static array $services = [];
private static array $allowedKeys = [
self::LOGGER,
];
final public static function set(string $key, Service $value)
{
if (!in_array($key, self::$allowedKeys)) {
throw new InvalidArgumentException('Invalid key given');
}
self::$services[$key] = $value;
}
final public static function get(string $key): Service
{
if (!in_array($key, self::$allowedKeys) || !isset(self::$services[$key])) {
throw new InvalidArgumentException('Invalid key given');
}
return self::$services[$key];
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Registry/Service.php | Structural/Registry/Service.php | <?php
namespace DesignPatterns\Structural\Registry;
class Service
{
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Registry/Tests/RegistryTest.php | Structural/Registry/Tests/RegistryTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Registry\Tests;
use InvalidArgumentException;
use DesignPatterns\Structural\Registry\Registry;
use DesignPatterns\Structural\Registry\Service;
use PHPUnit\Framework\TestCase;
class RegistryTest extends TestCase
{
private Service $service;
protected function setUp(): void
{
$this->service = $this->getMockBuilder(Service::class)->getMock();
}
public function testSetAndGetLogger()
{
Registry::set(Registry::LOGGER, $this->service);
$this->assertSame($this->service, Registry::get(Registry::LOGGER));
}
public function testThrowsExceptionWhenTryingToSetInvalidKey()
{
$this->expectException(InvalidArgumentException::class);
Registry::set('foobar', $this->service);
}
/**
* notice @runInSeparateProcess here: without it, a previous test might have set it already and
* testing would not be possible. That's why you should implement Dependency Injection where an
* injected class may easily be replaced by a mockup
*
* @runInSeparateProcess
*/
public function testThrowsExceptionWhenTryingToGetNotSetKey()
{
$this->expectException(InvalidArgumentException::class);
Registry::get(Registry::LOGGER);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Flyweight/Character.php | Structural/Flyweight/Character.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Flyweight;
/**
* Implements the flyweight interface and adds storage for intrinsic state, if any.
* Instances of concrete flyweights are shared by means of a factory.
*/
class Character implements Text
{
/**
* Any state stored by the concrete flyweight must be independent of its context.
* For flyweights representing characters, this is usually the corresponding character code.
*/
public function __construct(private string $name)
{
}
public function render(string $extrinsicState): string
{
// Clients supply the context-dependent information that the flyweight needs to draw itself
// For flyweights representing characters, extrinsic state usually contains e.g. the font.
return sprintf('Character %s with font %s', $this->name, $extrinsicState);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Flyweight/Text.php | Structural/Flyweight/Text.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Flyweight;
/**
* This is the interface that all flyweights need to implement
*/
interface Text
{
public function render(string $extrinsicState): string;
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Flyweight/TextFactory.php | Structural/Flyweight/TextFactory.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Flyweight;
use Countable;
/**
* A factory manages shared flyweights. Clients should not instantiate them directly,
* but let the factory take care of returning existing objects or creating new ones.
*/
class TextFactory implements Countable
{
/**
* @var Text[]
*/
private array $charPool = [];
public function get(string $name): Text
{
if (!isset($this->charPool[$name])) {
$this->charPool[$name] = $this->create($name);
}
return $this->charPool[$name];
}
private function create(string $name): Text
{
if (strlen($name) == 1) {
return new Character($name);
}
return new Word($name);
}
public function count(): int
{
return count($this->charPool);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Flyweight/Word.php | Structural/Flyweight/Word.php | <?php
namespace DesignPatterns\Structural\Flyweight;
class Word implements Text
{
public function __construct(private string $name)
{
}
public function render(string $extrinsicState): string
{
return sprintf('Word %s with font %s', $this->name, $extrinsicState);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Flyweight/Tests/FlyweightTest.php | Structural/Flyweight/Tests/FlyweightTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Flyweight\Tests;
use DesignPatterns\Structural\Flyweight\TextFactory;
use PHPUnit\Framework\TestCase;
class FlyweightTest extends TestCase
{
private array $characters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
private array $fonts = ['Arial', 'Times New Roman', 'Verdana', 'Helvetica'];
public function testFlyweight()
{
$factory = new TextFactory();
for ($i = 0; $i <= 10; $i++) {
foreach ($this->characters as $char) {
foreach ($this->fonts as $font) {
$flyweight = $factory->get($char);
$rendered = $flyweight->render($font);
$this->assertSame(sprintf('Character %s with font %s', $char, $font), $rendered);
}
}
}
foreach ($this->fonts as $word) {
$flyweight = $factory->get($word);
$rendered = $flyweight->render('foobar');
$this->assertSame(sprintf('Word %s with font foobar', $word), $rendered);
}
// Flyweight pattern ensures that instances are shared
// instead of having hundreds of thousands of individual objects
// there must be one instance for every char that has been reused for displaying in different fonts
$this->assertCount(count($this->characters) + count($this->fonts), $factory);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Decorator/ExtraBed.php | Structural/Decorator/ExtraBed.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Decorator;
class ExtraBed extends BookingDecorator
{
private const PRICE = 30;
public function calculatePrice(): int
{
return $this->booking->calculatePrice() + self::PRICE;
}
public function getDescription(): string
{
return $this->booking->getDescription() . ' with extra bed';
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Decorator/DoubleRoomBooking.php | Structural/Decorator/DoubleRoomBooking.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Decorator;
class DoubleRoomBooking implements Booking
{
public function calculatePrice(): int
{
return 40;
}
public function getDescription(): string
{
return 'double room';
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Decorator/WiFi.php | Structural/Decorator/WiFi.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Decorator;
class WiFi extends BookingDecorator
{
private const PRICE = 2;
public function calculatePrice(): int
{
return $this->booking->calculatePrice() + self::PRICE;
}
public function getDescription(): string
{
return $this->booking->getDescription() . ' with wifi';
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Decorator/Booking.php | Structural/Decorator/Booking.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Decorator;
interface Booking
{
public function calculatePrice(): int;
public function getDescription(): string;
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Decorator/BookingDecorator.php | Structural/Decorator/BookingDecorator.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Decorator;
abstract class BookingDecorator implements Booking
{
public function __construct(protected Booking $booking)
{
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Decorator/Tests/DecoratorTest.php | Structural/Decorator/Tests/DecoratorTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Decorator\Tests;
use DesignPatterns\Structural\Decorator\DoubleRoomBooking;
use DesignPatterns\Structural\Decorator\ExtraBed;
use DesignPatterns\Structural\Decorator\WiFi;
use PHPUnit\Framework\TestCase;
class DecoratorTest extends TestCase
{
public function testCanCalculatePriceForBasicDoubleRoomBooking()
{
$booking = new DoubleRoomBooking();
$this->assertSame(40, $booking->calculatePrice());
$this->assertSame('double room', $booking->getDescription());
}
public function testCanCalculatePriceForDoubleRoomBookingWithWiFi()
{
$booking = new DoubleRoomBooking();
$booking = new WiFi($booking);
$this->assertSame(42, $booking->calculatePrice());
$this->assertSame('double room with wifi', $booking->getDescription());
}
public function testCanCalculatePriceForDoubleRoomBookingWithWiFiAndExtraBed()
{
$booking = new DoubleRoomBooking();
$booking = new WiFi($booking);
$booking = new ExtraBed($booking);
$this->assertSame(72, $booking->calculatePrice());
$this->assertSame('double room with wifi with extra bed', $booking->getDescription());
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Facade/Facade.php | Structural/Facade/Facade.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Facade;
class Facade
{
public function __construct(private Bios $bios, private OperatingSystem $os)
{
}
public function turnOn()
{
$this->bios->execute();
$this->bios->waitForKeyPress();
$this->bios->launch($this->os);
}
public function turnOff()
{
$this->os->halt();
$this->bios->powerDown();
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Facade/Bios.php | Structural/Facade/Bios.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Facade;
interface Bios
{
public function execute();
public function waitForKeyPress();
public function launch(OperatingSystem $os);
public function powerDown();
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Facade/OperatingSystem.php | Structural/Facade/OperatingSystem.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Facade;
interface OperatingSystem
{
public function halt();
public function getName(): string;
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Facade/Tests/FacadeTest.php | Structural/Facade/Tests/FacadeTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Facade\Tests;
use DesignPatterns\Structural\Facade\Bios;
use DesignPatterns\Structural\Facade\Facade;
use DesignPatterns\Structural\Facade\OperatingSystem;
use PHPUnit\Framework\TestCase;
class FacadeTest extends TestCase
{
public function testComputerOn()
{
$os = $this->createMock(OperatingSystem::class);
$os->method('getName')
->will($this->returnValue('Linux'));
$bios = $this->createMock(Bios::class);
$bios->method('launch')
->with($os);
/** @noinspection PhpParamsInspection */
$facade = new Facade($bios, $os);
$facade->turnOn();
$this->assertSame('Linux', $os->getName());
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/DataMapper/User.php | Structural/DataMapper/User.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\DataMapper;
class User
{
public static function fromState(array $state): User
{
// validate state before accessing keys!
return new self(
$state['username'],
$state['email']
);
}
public function __construct(private string $username, private string $email)
{
}
public function getUsername(): string
{
return $this->username;
}
public function getEmail(): string
{
return $this->email;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/DataMapper/StorageAdapter.php | Structural/DataMapper/StorageAdapter.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\DataMapper;
class StorageAdapter
{
public function __construct(private array $data)
{
}
/**
* @return array|null
*/
public function find(int $id)
{
if (isset($this->data[$id])) {
return $this->data[$id];
}
return null;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/DataMapper/UserMapper.php | Structural/DataMapper/UserMapper.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\DataMapper;
use InvalidArgumentException;
class UserMapper
{
public function __construct(private StorageAdapter $adapter)
{
}
/**
* finds a user from storage based on ID and returns a User object located
* in memory. Normally this kind of logic will be implemented using the Repository pattern.
* However the important part is in mapRowToUser() below, that will create a business object from the
* data fetched from storage
*/
public function findById(int $id): User
{
$result = $this->adapter->find($id);
if ($result === null) {
throw new InvalidArgumentException("User #$id not found");
}
return $this->mapRowToUser($result);
}
private function mapRowToUser(array $row): User
{
return User::fromState($row);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/DataMapper/Tests/DataMapperTest.php | Structural/DataMapper/Tests/DataMapperTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\DataMapper\Tests;
use InvalidArgumentException;
use DesignPatterns\Structural\DataMapper\StorageAdapter;
use DesignPatterns\Structural\DataMapper\User;
use DesignPatterns\Structural\DataMapper\UserMapper;
use PHPUnit\Framework\TestCase;
class DataMapperTest extends TestCase
{
public function testCanMapUserFromStorage()
{
$storage = new StorageAdapter([1 => ['username' => 'someone', 'email' => 'someone@example.com']]);
$mapper = new UserMapper($storage);
$user = $mapper->findById(1);
$this->assertInstanceOf(User::class, $user);
}
public function testWillNotMapInvalidData()
{
$this->expectException(InvalidArgumentException::class);
$storage = new StorageAdapter([]);
$mapper = new UserMapper($storage);
$mapper->findById(1);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Composite/InputElement.php | Structural/Composite/InputElement.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Composite;
class InputElement implements Renderable
{
public function render(): string
{
return '<input type="text" />';
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Composite/TextElement.php | Structural/Composite/TextElement.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Composite;
class TextElement implements Renderable
{
public function __construct(private string $text)
{
}
public function render(): string
{
return $this->text;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Composite/Renderable.php | Structural/Composite/Renderable.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Composite;
interface Renderable
{
public function render(): string;
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Composite/Form.php | Structural/Composite/Form.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Composite;
/**
* The composite node MUST extend the component contract. This is mandatory for building
* a tree of components.
*/
class Form implements Renderable
{
/**
* @var Renderable[]
*/
private array $elements;
/**
* runs through all elements and calls render() on them, then returns the complete representation
* of the form.
*
* from the outside, one will not see this and the form will act like a single object instance
*/
public function render(): string
{
$formCode = '<form>';
foreach ($this->elements as $element) {
$formCode .= $element->render();
}
return $formCode . '</form>';
}
public function addElement(Renderable $element)
{
$this->elements[] = $element;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Composite/Tests/CompositeTest.php | Structural/Composite/Tests/CompositeTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Composite\Tests;
use DesignPatterns\Structural\Composite\Form;
use DesignPatterns\Structural\Composite\TextElement;
use DesignPatterns\Structural\Composite\InputElement;
use PHPUnit\Framework\TestCase;
class CompositeTest extends TestCase
{
public function testRender()
{
$form = new Form();
$form->addElement(new TextElement('Email:'));
$form->addElement(new InputElement());
$embed = new Form();
$embed->addElement(new TextElement('Password:'));
$embed->addElement(new InputElement());
$form->addElement($embed);
// This is just an example, in a real world scenario it is important to remember that web browsers do not
// currently support nested forms
$this->assertSame(
'<form>Email:<input type="text" /><form>Password:<input type="text" /></form></form>',
$form->render()
);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/DependencyInjection/DatabaseConnection.php | Structural/DependencyInjection/DatabaseConnection.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\DependencyInjection;
class DatabaseConnection
{
public function __construct(private DatabaseConfiguration $configuration)
{
}
public function getDsn(): string
{
// this is just for the sake of demonstration, not a real DSN
// notice that only the injected config is used here, so there is
// a real separation of concerns here
return sprintf(
'%s:%s@%s:%d',
$this->configuration->getUsername(),
$this->configuration->getPassword(),
$this->configuration->getHost(),
$this->configuration->getPort()
);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/DependencyInjection/DatabaseConfiguration.php | Structural/DependencyInjection/DatabaseConfiguration.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\DependencyInjection;
class DatabaseConfiguration
{
public function __construct(
private string $host,
private int $port,
private string $username,
private string $password
) {
}
public function getHost(): string
{
return $this->host;
}
public function getPort(): int
{
return $this->port;
}
public function getUsername(): string
{
return $this->username;
}
public function getPassword(): string
{
return $this->password;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/DependencyInjection/Tests/DependencyInjectionTest.php | Structural/DependencyInjection/Tests/DependencyInjectionTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\DependencyInjection\Tests;
use DesignPatterns\Structural\DependencyInjection\DatabaseConfiguration;
use DesignPatterns\Structural\DependencyInjection\DatabaseConnection;
use PHPUnit\Framework\TestCase;
class DependencyInjectionTest extends TestCase
{
public function testDependencyInjection()
{
$config = new DatabaseConfiguration('localhost', 3306, 'user', '1234');
$connection = new DatabaseConnection($config);
$this->assertSame('user:1234@localhost:3306', $connection->getDsn());
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Bridge/PingService.php | Structural/Bridge/PingService.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Bridge;
class PingService extends Service
{
public function get(): string
{
return $this->implementation->format('pong');
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Bridge/Service.php | Structural/Bridge/Service.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Bridge;
abstract class Service
{
public function __construct(protected Formatter $implementation)
{
}
final public function setImplementation(Formatter $printer)
{
$this->implementation = $printer;
}
abstract public function get(): string;
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Bridge/Formatter.php | Structural/Bridge/Formatter.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Bridge;
interface Formatter
{
public function format(string $text): string;
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Bridge/HelloWorldService.php | Structural/Bridge/HelloWorldService.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Bridge;
class HelloWorldService extends Service
{
public function get(): string
{
return $this->implementation->format('Hello World');
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Bridge/HtmlFormatter.php | Structural/Bridge/HtmlFormatter.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Bridge;
class HtmlFormatter implements Formatter
{
public function format(string $text): string
{
return sprintf('<p>%s</p>', $text);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Bridge/PlainTextFormatter.php | Structural/Bridge/PlainTextFormatter.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Bridge;
class PlainTextFormatter implements Formatter
{
public function format(string $text): string
{
return $text;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Bridge/Tests/BridgeTest.php | Structural/Bridge/Tests/BridgeTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Bridge\Tests;
use DesignPatterns\Structural\Bridge\HelloWorldService;
use DesignPatterns\Structural\Bridge\HtmlFormatter;
use DesignPatterns\Structural\Bridge\PlainTextFormatter;
use PHPUnit\Framework\TestCase;
class BridgeTest extends TestCase
{
public function testCanPrintUsingThePlainTextFormatter()
{
$service = new HelloWorldService(new PlainTextFormatter());
$this->assertSame('Hello World', $service->get());
}
public function testCanPrintUsingTheHtmlFormatter()
{
$service = new HelloWorldService(new HtmlFormatter());
$this->assertSame('<p>Hello World</p>', $service->get());
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/FluentInterface/Sql.php | Structural/FluentInterface/Sql.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\FluentInterface;
class Sql implements \Stringable
{
private array $fields = [];
private array $from = [];
private array $where = [];
public function select(array $fields): Sql
{
$this->fields = $fields;
return $this;
}
public function from(string $table, string $alias): Sql
{
$this->from[] = $table . ' AS ' . $alias;
return $this;
}
public function where(string $condition): Sql
{
$this->where[] = $condition;
return $this;
}
public function __toString(): string
{
return sprintf(
'SELECT %s FROM %s WHERE %s',
join(', ', $this->fields),
join(', ', $this->from),
join(' AND ', $this->where)
);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/FluentInterface/Tests/FluentInterfaceTest.php | Structural/FluentInterface/Tests/FluentInterfaceTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\FluentInterface\Tests;
use DesignPatterns\Structural\FluentInterface\Sql;
use PHPUnit\Framework\TestCase;
class FluentInterfaceTest extends TestCase
{
public function testBuildSQL()
{
$query = (new Sql())
->select(['foo', 'bar'])
->from('foobar', 'f')
->where('f.bar = ?');
$this->assertSame('SELECT foo, bar FROM foobar AS f WHERE f.bar = ?', (string) $query);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Adapter/Kindle.php | Structural/Adapter/Kindle.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Adapter;
/**
* this is the adapted class. In production code, this could be a class from another package, some vendor code.
* Notice that it uses another naming scheme and the implementation does something similar but in another way
*/
class Kindle implements EBook
{
private int $page = 1;
private int $totalPages = 100;
public function pressNext()
{
$this->page++;
}
public function unlock()
{
}
/**
* returns current page and total number of pages, like [10, 100] is page 10 of 100
*
* @return int[]
*/
public function getPage(): array
{
return [$this->page, $this->totalPages];
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Adapter/EBookAdapter.php | Structural/Adapter/EBookAdapter.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Adapter;
/**
* This is the adapter here. Notice it implements Book,
* therefore you don't have to change the code of the client which is using a Book
*/
class EBookAdapter implements Book
{
public function __construct(protected EBook $eBook)
{
}
/**
* This class makes the proper translation from one interface to another.
*/
public function open()
{
$this->eBook->unlock();
}
public function turnPage()
{
$this->eBook->pressNext();
}
/**
* notice the adapted behavior here: EBook::getPage() will return two integers, but Book
* supports only a current page getter, so we adapt the behavior here
*/
public function getPage(): int
{
return $this->eBook->getPage()[0];
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Adapter/EBook.php | Structural/Adapter/EBook.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Adapter;
interface EBook
{
public function unlock();
public function pressNext();
/**
* returns current page and total number of pages, like [10, 100] is page 10 of 100
*
* @return int[]
*/
public function getPage(): array;
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Adapter/PaperBook.php | Structural/Adapter/PaperBook.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Adapter;
class PaperBook implements Book
{
private int $page;
public function open(): void
{
$this->page = 1;
}
public function turnPage(): void
{
$this->page++;
}
public function getPage(): int
{
return $this->page;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Adapter/Book.php | Structural/Adapter/Book.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Adapter;
interface Book
{
public function turnPage();
public function open();
public function getPage(): int;
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Adapter/Tests/AdapterTest.php | Structural/Adapter/Tests/AdapterTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Adapter\Tests;
use DesignPatterns\Structural\Adapter\PaperBook;
use DesignPatterns\Structural\Adapter\EBookAdapter;
use DesignPatterns\Structural\Adapter\Kindle;
use PHPUnit\Framework\TestCase;
class AdapterTest extends TestCase
{
public function testCanTurnPageOnBook()
{
$book = new PaperBook();
$book->open();
$book->turnPage();
$this->assertSame(2, $book->getPage());
}
public function testCanTurnPageOnKindleLikeInANormalBook()
{
$kindle = new Kindle();
$book = new EBookAdapter($kindle);
$book->open();
$book->turnPage();
$this->assertSame(2, $book->getPage());
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Proxy/HeavyBankAccount.php | Structural/Proxy/HeavyBankAccount.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Proxy;
class HeavyBankAccount implements BankAccount
{
/**
* @var int[]
*/
private array $transactions = [];
public function deposit(int $amount)
{
$this->transactions[] = $amount;
}
public function getBalance(): int
{
// this is the heavy part, imagine all the transactions even from
// years and decades ago must be fetched from a database or web service
// and the balance must be calculated from it
return array_sum($this->transactions);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Proxy/BankAccountProxy.php | Structural/Proxy/BankAccountProxy.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Proxy;
class BankAccountProxy extends HeavyBankAccount implements BankAccount
{
private ?int $balance = null;
public function getBalance(): int
{
// because calculating balance is so expensive,
// the usage of BankAccount::getBalance() is delayed until it really is needed
// and will not be calculated again for this instance
if ($this->balance === null) {
$this->balance = parent::getBalance();
}
return $this->balance;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Proxy/BankAccount.php | Structural/Proxy/BankAccount.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Proxy;
interface BankAccount
{
public function deposit(int $amount);
public function getBalance(): int;
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/Structural/Proxy/Tests/ProxyTest.php | Structural/Proxy/Tests/ProxyTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\Structural\Proxy\Tests;
use DesignPatterns\Structural\Proxy\BankAccountProxy;
use PHPUnit\Framework\TestCase;
class ProxyTest extends TestCase
{
public function testProxyWillOnlyExecuteExpensiveGetBalanceOnce()
{
$bankAccount = new BankAccountProxy();
$bankAccount->deposit(30);
// this time balance is being calculated
$this->assertSame(30, $bankAccount->getBalance());
// inheritance allows for BankAccountProxy to behave to an outsider exactly like ServerBankAccount
$bankAccount->deposit(50);
// this time the previously calculated balance is returned again without re-calculating it
$this->assertSame(30, $bankAccount->getBalance());
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/More/ServiceLocator/LogService.php | More/ServiceLocator/LogService.php | <?php
declare(strict_types=1);
namespace DesignPatterns\More\ServiceLocator;
class LogService implements Service
{
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/More/ServiceLocator/Service.php | More/ServiceLocator/Service.php | <?php
namespace DesignPatterns\More\ServiceLocator;
interface Service
{
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/More/ServiceLocator/ServiceLocator.php | More/ServiceLocator/ServiceLocator.php | <?php
declare(strict_types=1);
namespace DesignPatterns\More\ServiceLocator;
use OutOfRangeException;
use InvalidArgumentException;
class ServiceLocator
{
/**
* @var string[][]
*/
private array $services = [];
/**
* @var Service[]
*/
private array $instantiated = [];
public function addInstance(string $class, Service $service)
{
$this->instantiated[$class] = $service;
}
public function addClass(string $class, array $params)
{
$this->services[$class] = $params;
}
public function has(string $interface): bool
{
return isset($this->services[$interface]) || isset($this->instantiated[$interface]);
}
public function get(string $class): Service
{
if (isset($this->instantiated[$class])) {
return $this->instantiated[$class];
}
$object = new $class(...$this->services[$class]);
if (!$object instanceof Service) {
throw new InvalidArgumentException('Could not register service: is no instance of Service');
}
$this->instantiated[$class] = $object;
return $object;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/More/ServiceLocator/Tests/ServiceLocatorTest.php | More/ServiceLocator/Tests/ServiceLocatorTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\More\ServiceLocator\Tests;
use DesignPatterns\More\ServiceLocator\LogService;
use DesignPatterns\More\ServiceLocator\ServiceLocator;
use PHPUnit\Framework\TestCase;
class ServiceLocatorTest extends TestCase
{
private ServiceLocator $serviceLocator;
public function setUp(): void
{
$this->serviceLocator = new ServiceLocator();
}
public function testHasServices()
{
$this->serviceLocator->addInstance(LogService::class, new LogService());
$this->assertTrue($this->serviceLocator->has(LogService::class));
$this->assertFalse($this->serviceLocator->has(self::class));
}
public function testGetWillInstantiateLogServiceIfNoInstanceHasBeenCreatedYet()
{
$this->serviceLocator->addClass(LogService::class, []);
$logger = $this->serviceLocator->get(LogService::class);
$this->assertInstanceOf(LogService::class, $logger);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/More/EAV/Value.php | More/EAV/Value.php | <?php
declare(strict_types=1);
namespace DesignPatterns\More\EAV;
class Value implements \Stringable
{
public function __construct(private Attribute $attribute, private string $name)
{
$attribute->addValue($this);
}
public function __toString(): string
{
return sprintf('%s: %s', (string) $this->attribute, $this->name);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/More/EAV/Entity.php | More/EAV/Entity.php | <?php
declare(strict_types=1);
namespace DesignPatterns\More\EAV;
use SplObjectStorage;
class Entity implements \Stringable
{
/**
* @var SplObjectStorage<Value,Value>
*/
private $values;
/**
* @param Value[] $values
*/
public function __construct(private string $name, array $values)
{
$this->values = new SplObjectStorage();
foreach ($values as $value) {
$this->values->attach($value);
}
}
public function __toString(): string
{
$text = [$this->name];
foreach ($this->values as $value) {
$text[] = (string) $value;
}
return join(', ', $text);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/More/EAV/Attribute.php | More/EAV/Attribute.php | <?php
declare(strict_types=1);
namespace DesignPatterns\More\EAV;
use SplObjectStorage;
class Attribute implements \Stringable
{
private SplObjectStorage $values;
public function __construct(private string $name)
{
$this->values = new SplObjectStorage();
}
public function addValue(Value $value): void
{
$this->values->attach($value);
}
public function getValues(): SplObjectStorage
{
return $this->values;
}
public function __toString(): string
{
return $this->name;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/More/EAV/Tests/EAVTest.php | More/EAV/Tests/EAVTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\More\EAV\Tests;
use DesignPatterns\More\EAV\Attribute;
use DesignPatterns\More\EAV\Entity;
use DesignPatterns\More\EAV\Value;
use PHPUnit\Framework\TestCase;
class EAVTest extends TestCase
{
public function testCanAddAttributeToEntity(): void
{
$colorAttribute = new Attribute('color');
$colorSilver = new Value($colorAttribute, 'silver');
$colorBlack = new Value($colorAttribute, 'black');
$memoryAttribute = new Attribute('memory');
$memory8Gb = new Value($memoryAttribute, '8GB');
$entity = new Entity('MacBook Pro', [$colorSilver, $colorBlack, $memory8Gb]);
$this->assertEquals('MacBook Pro, color: silver, color: black, memory: 8GB', (string) $entity);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/More/Repository/Persistence.php | More/Repository/Persistence.php | <?php
declare(strict_types=1);
namespace DesignPatterns\More\Repository;
interface Persistence
{
public function generateId(): int;
public function persist(array $data);
public function retrieve(int $id): array;
public function delete(int $id);
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/More/Repository/InMemoryPersistence.php | More/Repository/InMemoryPersistence.php | <?php
declare(strict_types=1);
namespace DesignPatterns\More\Repository;
use OutOfBoundsException;
class InMemoryPersistence implements Persistence
{
private array $data = [];
private int $lastId = 0;
public function generateId(): int
{
$this->lastId++;
return $this->lastId;
}
public function persist(array $data)
{
$this->data[$this->lastId] = $data;
}
public function retrieve(int $id): array
{
if (!isset($this->data[$id])) {
throw new OutOfBoundsException(sprintf('No data found for ID %d', $id));
}
return $this->data[$id];
}
public function delete(int $id)
{
if (!isset($this->data[$id])) {
throw new OutOfBoundsException(sprintf('No data found for ID %d', $id));
}
unset($this->data[$id]);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/More/Repository/PostRepository.php | More/Repository/PostRepository.php | <?php
declare(strict_types=1);
namespace DesignPatterns\More\Repository;
use OutOfBoundsException;
use DesignPatterns\More\Repository\Domain\Post;
use DesignPatterns\More\Repository\Domain\PostId;
/**
* This class is situated between Entity layer (class Post) and access object layer (Persistence).
*
* Repository encapsulates the set of objects persisted in a data store and the operations performed over them
* providing a more object-oriented view of the persistence layer
*
* Repository also supports the objective of achieving a clean separation and one-way dependency
* between the domain and data mapping layers
*/
class PostRepository
{
public function __construct(private Persistence $persistence)
{
}
public function generateId(): PostId
{
return PostId::fromInt($this->persistence->generateId());
}
public function findById(PostId $id): Post
{
try {
$arrayData = $this->persistence->retrieve($id->toInt());
} catch (OutOfBoundsException $e) {
throw new OutOfBoundsException(sprintf('Post with id %d does not exist', $id->toInt()), 0, $e);
}
return Post::fromState($arrayData);
}
public function save(Post $post)
{
$this->persistence->persist([
'id' => $post->getId()->toInt(),
'statusId' => $post->getStatus()->toInt(),
'text' => $post->getText(),
'title' => $post->getTitle(),
]);
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/More/Repository/Domain/PostId.php | More/Repository/Domain/PostId.php | <?php
declare(strict_types=1);
namespace DesignPatterns\More\Repository\Domain;
use InvalidArgumentException;
/**
* This is a perfect example of a value object that is identifiable by it's value alone and
* is guaranteed to be valid each time an instance is created. Another important property of value objects
* is immutability.
*
* Notice also the use of a named constructor (fromInt) which adds a little context when creating an instance.
*/
class PostId
{
public static function fromInt(int $id): PostId
{
self::ensureIsValid($id);
return new self($id);
}
private function __construct(private int $id)
{
}
public function toInt(): int
{
return $this->id;
}
private static function ensureIsValid(int $id)
{
if ($id <= 0) {
throw new InvalidArgumentException('Invalid PostId given');
}
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/More/Repository/Domain/PostStatus.php | More/Repository/Domain/PostStatus.php | <?php
declare(strict_types=1);
namespace DesignPatterns\More\Repository\Domain;
use InvalidArgumentException;
/**
* Like PostId, this is a value object which holds the value of the current status of a Post. It can be constructed
* either from a string or int and is able to validate itself. An instance can then be converted back to int or string.
*/
class PostStatus
{
public const STATE_DRAFT_ID = 1;
public const STATE_PUBLISHED_ID = 2;
public const STATE_DRAFT = 'draft';
public const STATE_PUBLISHED = 'published';
private static array $validStates = [
self::STATE_DRAFT_ID => self::STATE_DRAFT,
self::STATE_PUBLISHED_ID => self::STATE_PUBLISHED,
];
public static function fromInt(int $statusId)
{
self::ensureIsValidId($statusId);
return new self($statusId, self::$validStates[$statusId]);
}
public static function fromString(string $status)
{
self::ensureIsValidName($status);
$state = array_search($status, self::$validStates);
if ($state === false) {
throw new InvalidArgumentException('Invalid state given!');
}
return new self($state, $status);
}
private function __construct(private int $id, private string $name)
{
}
public function toInt(): int
{
return $this->id;
}
/**
* there is a reason that I avoid using __toString() as it operates outside of the stack in PHP
* and is therefore not able to operate well with exceptions
*/
public function toString(): string
{
return $this->name;
}
private static function ensureIsValidId(int $status)
{
if (!in_array($status, array_keys(self::$validStates), true)) {
throw new InvalidArgumentException('Invalid status id given');
}
}
private static function ensureIsValidName(string $status)
{
if (!in_array($status, self::$validStates, true)) {
throw new InvalidArgumentException('Invalid status name given');
}
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/More/Repository/Domain/Post.php | More/Repository/Domain/Post.php | <?php
declare(strict_types=1);
namespace DesignPatterns\More\Repository\Domain;
class Post
{
public static function draft(PostId $id, string $title, string $text): Post
{
return new self(
$id,
PostStatus::fromString(PostStatus::STATE_DRAFT),
$title,
$text
);
}
public static function fromState(array $state): Post
{
return new self(
PostId::fromInt($state['id']),
PostStatus::fromInt($state['statusId']),
$state['title'],
$state['text']
);
}
private function __construct(
private PostId $id,
private PostStatus $status,
private string $title,
private string $text
) {
}
public function getId(): PostId
{
return $this->id;
}
public function getStatus(): PostStatus
{
return $this->status;
}
public function getText(): string
{
return $this->text;
}
public function getTitle(): string
{
return $this->title;
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
DesignPatternsPHP/DesignPatternsPHP | https://github.com/DesignPatternsPHP/DesignPatternsPHP/blob/54254e0f2a59e27280f81304bce9218e12f97a03/More/Repository/Tests/PostRepositoryTest.php | More/Repository/Tests/PostRepositoryTest.php | <?php
declare(strict_types=1);
namespace DesignPatterns\More\Repository\Tests;
use OutOfBoundsException;
use DesignPatterns\More\Repository\Domain\PostId;
use DesignPatterns\More\Repository\Domain\PostStatus;
use DesignPatterns\More\Repository\InMemoryPersistence;
use DesignPatterns\More\Repository\Domain\Post;
use DesignPatterns\More\Repository\PostRepository;
use PHPUnit\Framework\TestCase;
class PostRepositoryTest extends TestCase
{
private PostRepository $repository;
protected function setUp(): void
{
$this->repository = new PostRepository(new InMemoryPersistence());
}
public function testCanGenerateId()
{
$this->assertEquals(1, $this->repository->generateId()->toInt());
}
public function testThrowsExceptionWhenTryingToFindPostWhichDoesNotExist()
{
$this->expectException(OutOfBoundsException::class);
$this->expectExceptionMessage('Post with id 42 does not exist');
$this->repository->findById(PostId::fromInt(42));
}
public function testCanPersistPostDraft()
{
$postId = $this->repository->generateId();
$post = Post::draft($postId, 'Repository Pattern', 'Design Patterns PHP');
$this->repository->save($post);
$this->repository->findById($postId);
$this->assertEquals($postId, $this->repository->findById($postId)->getId());
$this->assertEquals(PostStatus::STATE_DRAFT, $post->getStatus()->toString());
}
}
| php | MIT | 54254e0f2a59e27280f81304bce9218e12f97a03 | 2026-01-04T15:02:34.345104Z | false |
erusev/parsedown | https://github.com/erusev/parsedown/blob/0b274ac959624e6c6d647e9c9b6c2d20da242004/Parsedown.php | Parsedown.php | <?php
#
#
# Parsedown
# http://parsedown.org
#
# (c) Emanuil Rusev
# http://erusev.com
#
# For the full license information, view the LICENSE file that was distributed
# with this source code.
#
#
class Parsedown
{
# ~
const version = '1.8.0';
# ~
function text($text)
{
$Elements = $this->textElements($text);
# convert to markup
$markup = $this->elements($Elements);
# trim line breaks
$markup = trim($markup, "\n");
return $markup;
}
protected function textElements($text)
{
# make sure no definitions are set
$this->DefinitionData = array();
# standardize line breaks
$text = str_replace(array("\r\n", "\r"), "\n", $text);
# remove surrounding line breaks
$text = trim($text, "\n");
# split text into lines
$lines = explode("\n", $text);
# iterate through lines to identify blocks
return $this->linesElements($lines);
}
#
# Setters
#
function setBreaksEnabled($breaksEnabled)
{
$this->breaksEnabled = $breaksEnabled;
return $this;
}
protected $breaksEnabled;
function setMarkupEscaped($markupEscaped)
{
$this->markupEscaped = $markupEscaped;
return $this;
}
protected $markupEscaped;
function setUrlsLinked($urlsLinked)
{
$this->urlsLinked = $urlsLinked;
return $this;
}
protected $urlsLinked = true;
function setSafeMode($safeMode)
{
$this->safeMode = (bool) $safeMode;
return $this;
}
protected $safeMode;
function setStrictMode($strictMode)
{
$this->strictMode = (bool) $strictMode;
return $this;
}
protected $strictMode;
protected $safeLinksWhitelist = array(
'http://',
'https://',
'ftp://',
'ftps://',
'mailto:',
'tel:',
'data:image/png;base64,',
'data:image/gif;base64,',
'data:image/jpeg;base64,',
'irc:',
'ircs:',
'git:',
'ssh:',
'news:',
'steam:',
);
#
# Lines
#
protected $BlockTypes = array(
'#' => array('Header'),
'*' => array('Rule', 'List'),
'+' => array('List'),
'-' => array('SetextHeader', 'Table', 'Rule', 'List'),
'0' => array('List'),
'1' => array('List'),
'2' => array('List'),
'3' => array('List'),
'4' => array('List'),
'5' => array('List'),
'6' => array('List'),
'7' => array('List'),
'8' => array('List'),
'9' => array('List'),
':' => array('Table'),
'<' => array('Comment', 'Markup'),
'=' => array('SetextHeader'),
'>' => array('Quote'),
'[' => array('Reference'),
'_' => array('Rule'),
'`' => array('FencedCode'),
'|' => array('Table'),
'~' => array('FencedCode'),
);
# ~
protected $unmarkedBlockTypes = array(
'Code',
);
#
# Blocks
#
protected function lines(array $lines)
{
return $this->elements($this->linesElements($lines));
}
protected function linesElements(array $lines)
{
$Elements = array();
$CurrentBlock = null;
foreach ($lines as $line)
{
if (chop($line) === '')
{
if (isset($CurrentBlock))
{
$CurrentBlock['interrupted'] = (isset($CurrentBlock['interrupted'])
? $CurrentBlock['interrupted'] + 1 : 1
);
}
continue;
}
while (($beforeTab = strstr($line, "\t", true)) !== false)
{
$shortage = 4 - mb_strlen($beforeTab, 'utf-8') % 4;
$line = $beforeTab
. str_repeat(' ', $shortage)
. substr($line, strlen($beforeTab) + 1)
;
}
$indent = strspn($line, ' ');
$text = $indent > 0 ? substr($line, $indent) : $line;
# ~
$Line = array('body' => $line, 'indent' => $indent, 'text' => $text);
# ~
if (isset($CurrentBlock['continuable']))
{
$methodName = 'block' . $CurrentBlock['type'] . 'Continue';
$Block = $this->$methodName($Line, $CurrentBlock);
if (isset($Block))
{
$CurrentBlock = $Block;
continue;
}
else
{
if ($this->isBlockCompletable($CurrentBlock['type']))
{
$methodName = 'block' . $CurrentBlock['type'] . 'Complete';
$CurrentBlock = $this->$methodName($CurrentBlock);
}
}
}
# ~
$marker = $text[0];
# ~
$blockTypes = $this->unmarkedBlockTypes;
if (isset($this->BlockTypes[$marker]))
{
foreach ($this->BlockTypes[$marker] as $blockType)
{
$blockTypes []= $blockType;
}
}
#
# ~
foreach ($blockTypes as $blockType)
{
$Block = $this->{"block$blockType"}($Line, $CurrentBlock);
if (isset($Block))
{
$Block['type'] = $blockType;
if ( ! isset($Block['identified']))
{
if (isset($CurrentBlock))
{
$Elements[] = $this->extractElement($CurrentBlock);
}
$Block['identified'] = true;
}
if ($this->isBlockContinuable($blockType))
{
$Block['continuable'] = true;
}
$CurrentBlock = $Block;
continue 2;
}
}
# ~
if (isset($CurrentBlock) and $CurrentBlock['type'] === 'Paragraph')
{
$Block = $this->paragraphContinue($Line, $CurrentBlock);
}
if (isset($Block))
{
$CurrentBlock = $Block;
}
else
{
if (isset($CurrentBlock))
{
$Elements[] = $this->extractElement($CurrentBlock);
}
$CurrentBlock = $this->paragraph($Line);
$CurrentBlock['identified'] = true;
}
}
# ~
if (isset($CurrentBlock['continuable']) and $this->isBlockCompletable($CurrentBlock['type']))
{
$methodName = 'block' . $CurrentBlock['type'] . 'Complete';
$CurrentBlock = $this->$methodName($CurrentBlock);
}
# ~
if (isset($CurrentBlock))
{
$Elements[] = $this->extractElement($CurrentBlock);
}
# ~
return $Elements;
}
protected function extractElement(array $Component)
{
if ( ! isset($Component['element']))
{
if (isset($Component['markup']))
{
$Component['element'] = array('rawHtml' => $Component['markup']);
}
elseif (isset($Component['hidden']))
{
$Component['element'] = array();
}
}
return $Component['element'];
}
protected function isBlockContinuable($Type)
{
return method_exists($this, 'block' . $Type . 'Continue');
}
protected function isBlockCompletable($Type)
{
return method_exists($this, 'block' . $Type . 'Complete');
}
#
# Code
protected function blockCode($Line, $Block = null)
{
if (isset($Block) and $Block['type'] === 'Paragraph' and ! isset($Block['interrupted']))
{
return;
}
if ($Line['indent'] >= 4)
{
$text = substr($Line['body'], 4);
$Block = array(
'element' => array(
'name' => 'pre',
'element' => array(
'name' => 'code',
'text' => $text,
),
),
);
return $Block;
}
}
protected function blockCodeContinue($Line, $Block)
{
if ($Line['indent'] >= 4)
{
if (isset($Block['interrupted']))
{
$Block['element']['element']['text'] .= str_repeat("\n", $Block['interrupted']);
unset($Block['interrupted']);
}
$Block['element']['element']['text'] .= "\n";
$text = substr($Line['body'], 4);
$Block['element']['element']['text'] .= $text;
return $Block;
}
}
protected function blockCodeComplete($Block)
{
return $Block;
}
#
# Comment
protected function blockComment($Line)
{
if ($this->markupEscaped or $this->safeMode)
{
return;
}
if (strpos($Line['text'], '<!--') === 0)
{
$Block = array(
'element' => array(
'rawHtml' => $Line['body'],
'autobreak' => true,
),
);
if (strpos($Line['text'], '-->') !== false)
{
$Block['closed'] = true;
}
return $Block;
}
}
protected function blockCommentContinue($Line, array $Block)
{
if (isset($Block['closed']))
{
return;
}
$Block['element']['rawHtml'] .= "\n" . $Line['body'];
if (strpos($Line['text'], '-->') !== false)
{
$Block['closed'] = true;
}
return $Block;
}
#
# Fenced Code
protected function blockFencedCode($Line)
{
$marker = $Line['text'][0];
$openerLength = strspn($Line['text'], $marker);
if ($openerLength < 3)
{
return;
}
$infostring = trim(substr($Line['text'], $openerLength), "\t ");
if (strpos($infostring, '`') !== false)
{
return;
}
$Element = array(
'name' => 'code',
'text' => '',
);
if ($infostring !== '')
{
/**
* https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#classes
* Every HTML element may have a class attribute specified.
* The attribute, if specified, must have a value that is a set
* of space-separated tokens representing the various classes
* that the element belongs to.
* [...]
* The space characters, for the purposes of this specification,
* are U+0020 SPACE, U+0009 CHARACTER TABULATION (tab),
* U+000A LINE FEED (LF), U+000C FORM FEED (FF), and
* U+000D CARRIAGE RETURN (CR).
*/
$language = substr($infostring, 0, strcspn($infostring, " \t\n\f\r"));
$Element['attributes'] = array('class' => "language-$language");
}
$Block = array(
'char' => $marker,
'openerLength' => $openerLength,
'element' => array(
'name' => 'pre',
'element' => $Element,
),
);
return $Block;
}
protected function blockFencedCodeContinue($Line, $Block)
{
if (isset($Block['complete']))
{
return;
}
if (isset($Block['interrupted']))
{
$Block['element']['element']['text'] .= str_repeat("\n", $Block['interrupted']);
unset($Block['interrupted']);
}
if (($len = strspn($Line['text'], $Block['char'])) >= $Block['openerLength']
and chop(substr($Line['text'], $len), ' ') === ''
) {
$Block['element']['element']['text'] = substr($Block['element']['element']['text'], 1);
$Block['complete'] = true;
return $Block;
}
$Block['element']['element']['text'] .= "\n" . $Line['body'];
return $Block;
}
protected function blockFencedCodeComplete($Block)
{
return $Block;
}
#
# Header
protected function blockHeader($Line)
{
$level = strspn($Line['text'], '#');
if ($level > 6)
{
return;
}
$text = trim($Line['text'], '#');
if ($this->strictMode and isset($text[0]) and $text[0] !== ' ')
{
return;
}
$text = trim($text, ' ');
$Block = array(
'element' => array(
'name' => 'h' . $level,
'handler' => array(
'function' => 'lineElements',
'argument' => $text,
'destination' => 'elements',
)
),
);
return $Block;
}
#
# List
protected function blockList($Line, ?array $CurrentBlock = null)
{
list($name, $pattern) = $Line['text'][0] <= '-' ? array('ul', '[*+-]') : array('ol', '[0-9]{1,9}+[.\)]');
if (preg_match('/^('.$pattern.'([ ]++|$))(.*+)/', $Line['text'], $matches))
{
$contentIndent = strlen($matches[2]);
if ($contentIndent >= 5)
{
$contentIndent -= 1;
$matches[1] = substr($matches[1], 0, -$contentIndent);
$matches[3] = str_repeat(' ', $contentIndent) . $matches[3];
}
elseif ($contentIndent === 0)
{
$matches[1] .= ' ';
}
$markerWithoutWhitespace = strstr($matches[1], ' ', true);
$Block = array(
'indent' => $Line['indent'],
'pattern' => $pattern,
'data' => array(
'type' => $name,
'marker' => $matches[1],
'markerType' => ($name === 'ul' ? $markerWithoutWhitespace : substr($markerWithoutWhitespace, -1)),
),
'element' => array(
'name' => $name,
'elements' => array(),
),
);
$Block['data']['markerTypeRegex'] = preg_quote($Block['data']['markerType'], '/');
if ($name === 'ol')
{
$listStart = ltrim(strstr($matches[1], $Block['data']['markerType'], true), '0') ?: '0';
if ($listStart !== '1')
{
if (
isset($CurrentBlock)
and $CurrentBlock['type'] === 'Paragraph'
and ! isset($CurrentBlock['interrupted'])
) {
return;
}
$Block['element']['attributes'] = array('start' => $listStart);
}
}
$Block['li'] = array(
'name' => 'li',
'handler' => array(
'function' => 'li',
'argument' => !empty($matches[3]) ? array($matches[3]) : array(),
'destination' => 'elements'
)
);
$Block['element']['elements'] []= & $Block['li'];
return $Block;
}
}
protected function blockListContinue($Line, array $Block)
{
if (isset($Block['interrupted']) and empty($Block['li']['handler']['argument']))
{
return null;
}
$requiredIndent = ($Block['indent'] + strlen($Block['data']['marker']));
if ($Line['indent'] < $requiredIndent
and (
(
$Block['data']['type'] === 'ol'
and preg_match('/^[0-9]++'.$Block['data']['markerTypeRegex'].'(?:[ ]++(.*)|$)/', $Line['text'], $matches)
) or (
$Block['data']['type'] === 'ul'
and preg_match('/^'.$Block['data']['markerTypeRegex'].'(?:[ ]++(.*)|$)/', $Line['text'], $matches)
)
)
) {
if (isset($Block['interrupted']))
{
$Block['li']['handler']['argument'] []= '';
$Block['loose'] = true;
unset($Block['interrupted']);
}
unset($Block['li']);
$text = isset($matches[1]) ? $matches[1] : '';
$Block['indent'] = $Line['indent'];
$Block['li'] = array(
'name' => 'li',
'handler' => array(
'function' => 'li',
'argument' => array($text),
'destination' => 'elements'
)
);
$Block['element']['elements'] []= & $Block['li'];
return $Block;
}
elseif ($Line['indent'] < $requiredIndent and $this->blockList($Line))
{
return null;
}
if ($Line['text'][0] === '[' and $this->blockReference($Line))
{
return $Block;
}
if ($Line['indent'] >= $requiredIndent)
{
if (isset($Block['interrupted']))
{
$Block['li']['handler']['argument'] []= '';
$Block['loose'] = true;
unset($Block['interrupted']);
}
$text = substr($Line['body'], $requiredIndent);
$Block['li']['handler']['argument'] []= $text;
return $Block;
}
if ( ! isset($Block['interrupted']))
{
$text = preg_replace('/^[ ]{0,'.$requiredIndent.'}+/', '', $Line['body']);
$Block['li']['handler']['argument'] []= $text;
return $Block;
}
}
protected function blockListComplete(array $Block)
{
if (isset($Block['loose']))
{
foreach ($Block['element']['elements'] as &$li)
{
if (end($li['handler']['argument']) !== '')
{
$li['handler']['argument'] []= '';
}
}
}
return $Block;
}
#
# Quote
protected function blockQuote($Line)
{
if (preg_match('/^>[ ]?+(.*+)/', $Line['text'], $matches))
{
$Block = array(
'element' => array(
'name' => 'blockquote',
'handler' => array(
'function' => 'linesElements',
'argument' => (array) $matches[1],
'destination' => 'elements',
)
),
);
return $Block;
}
}
protected function blockQuoteContinue($Line, array $Block)
{
if (isset($Block['interrupted']))
{
return;
}
if ($Line['text'][0] === '>' and preg_match('/^>[ ]?+(.*+)/', $Line['text'], $matches))
{
$Block['element']['handler']['argument'] []= $matches[1];
return $Block;
}
if ( ! isset($Block['interrupted']))
{
$Block['element']['handler']['argument'] []= $Line['text'];
return $Block;
}
}
#
# Rule
protected function blockRule($Line)
{
$marker = $Line['text'][0];
if (substr_count($Line['text'], $marker) >= 3 and chop($Line['text'], " $marker") === '')
{
$Block = array(
'element' => array(
'name' => 'hr',
),
);
return $Block;
}
}
#
# Setext
protected function blockSetextHeader($Line, ?array $Block = null)
{
if ( ! isset($Block) or $Block['type'] !== 'Paragraph' or isset($Block['interrupted']))
{
return;
}
if ($Line['indent'] < 4 and chop(chop($Line['text'], ' '), $Line['text'][0]) === '')
{
$Block['element']['name'] = $Line['text'][0] === '=' ? 'h1' : 'h2';
return $Block;
}
}
#
# Markup
protected function blockMarkup($Line)
{
if ($this->markupEscaped or $this->safeMode)
{
return;
}
if (preg_match('/^<[\/]?+(\w*)(?:[ ]*+'.$this->regexHtmlAttribute.')*+[ ]*+(\/)?>/', $Line['text'], $matches))
{
$element = strtolower($matches[1]);
if (in_array($element, $this->textLevelElements))
{
return;
}
$Block = array(
'name' => $matches[1],
'element' => array(
'rawHtml' => $Line['text'],
'autobreak' => true,
),
);
return $Block;
}
}
protected function blockMarkupContinue($Line, array $Block)
{
if (isset($Block['closed']) or isset($Block['interrupted']))
{
return;
}
$Block['element']['rawHtml'] .= "\n" . $Line['body'];
return $Block;
}
#
# Reference
protected function blockReference($Line)
{
if (strpos($Line['text'], ']') !== false
and preg_match('/^\[(.+?)\]:[ ]*+<?(\S+?)>?(?:[ ]+["\'(](.+)["\')])?[ ]*+$/', $Line['text'], $matches)
) {
$id = strtolower($matches[1]);
$Data = array(
'url' => $matches[2],
'title' => isset($matches[3]) ? $matches[3] : null,
);
$this->DefinitionData['Reference'][$id] = $Data;
$Block = array(
'element' => array(),
);
return $Block;
}
}
#
# Table
protected function blockTable($Line, ?array $Block = null)
{
if ( ! isset($Block) or $Block['type'] !== 'Paragraph' or isset($Block['interrupted']))
{
return;
}
if (
strpos($Block['element']['handler']['argument'], '|') === false
and strpos($Line['text'], '|') === false
and strpos($Line['text'], ':') === false
or strpos($Block['element']['handler']['argument'], "\n") !== false
) {
return;
}
if (chop($Line['text'], ' -:|') !== '')
{
return;
}
$alignments = array();
$divider = $Line['text'];
$divider = trim($divider);
$divider = trim($divider, '|');
$dividerCells = explode('|', $divider);
foreach ($dividerCells as $dividerCell)
{
$dividerCell = trim($dividerCell);
if ($dividerCell === '')
{
return;
}
$alignment = null;
if ($dividerCell[0] === ':')
{
$alignment = 'left';
}
if (substr($dividerCell, - 1) === ':')
{
$alignment = $alignment === 'left' ? 'center' : 'right';
}
$alignments []= $alignment;
}
# ~
$HeaderElements = array();
$header = $Block['element']['handler']['argument'];
$header = trim($header);
$header = trim($header, '|');
$headerCells = explode('|', $header);
if (count($headerCells) !== count($alignments))
{
return;
}
foreach ($headerCells as $index => $headerCell)
{
$headerCell = trim($headerCell);
$HeaderElement = array(
'name' => 'th',
'handler' => array(
'function' => 'lineElements',
'argument' => $headerCell,
'destination' => 'elements',
)
);
if (isset($alignments[$index]))
{
$alignment = $alignments[$index];
$HeaderElement['attributes'] = array(
'style' => "text-align: $alignment;",
);
}
$HeaderElements []= $HeaderElement;
}
# ~
$Block = array(
'alignments' => $alignments,
'identified' => true,
'element' => array(
'name' => 'table',
'elements' => array(),
),
);
$Block['element']['elements'] []= array(
'name' => 'thead',
);
$Block['element']['elements'] []= array(
'name' => 'tbody',
'elements' => array(),
);
$Block['element']['elements'][0]['elements'] []= array(
'name' => 'tr',
'elements' => $HeaderElements,
);
return $Block;
}
protected function blockTableContinue($Line, array $Block)
{
if (isset($Block['interrupted']))
{
return;
}
if (count($Block['alignments']) === 1 or $Line['text'][0] === '|' or strpos($Line['text'], '|'))
{
$Elements = array();
$row = $Line['text'];
$row = trim($row);
$row = trim($row, '|');
preg_match_all('/(?:(\\\\[|])|[^|`]|`[^`]++`|`)++/', $row, $matches);
$cells = array_slice($matches[0], 0, count($Block['alignments']));
foreach ($cells as $index => $cell)
{
$cell = trim($cell);
$Element = array(
'name' => 'td',
'handler' => array(
'function' => 'lineElements',
'argument' => $cell,
'destination' => 'elements',
)
);
if (isset($Block['alignments'][$index]))
{
$Element['attributes'] = array(
'style' => 'text-align: ' . $Block['alignments'][$index] . ';',
);
}
$Elements []= $Element;
}
$Element = array(
'name' => 'tr',
'elements' => $Elements,
);
$Block['element']['elements'][1]['elements'] []= $Element;
return $Block;
}
}
#
# ~
#
protected function paragraph($Line)
{
return array(
'type' => 'Paragraph',
'element' => array(
'name' => 'p',
'handler' => array(
'function' => 'lineElements',
'argument' => $Line['text'],
'destination' => 'elements',
),
),
);
}
protected function paragraphContinue($Line, array $Block)
{
if (isset($Block['interrupted']))
{
return;
}
$Block['element']['handler']['argument'] .= "\n".$Line['text'];
return $Block;
}
#
# Inline Elements
#
protected $InlineTypes = array(
'!' => array('Image'),
'&' => array('SpecialCharacter'),
'*' => array('Emphasis'),
':' => array('Url'),
'<' => array('UrlTag', 'EmailTag', 'Markup'),
'[' => array('Link'),
'_' => array('Emphasis'),
'`' => array('Code'),
'~' => array('Strikethrough'),
'\\' => array('EscapeSequence'),
);
# ~
protected $inlineMarkerList = '!*_&[:<`~\\';
#
# ~
#
public function line($text, $nonNestables = array())
{
return $this->elements($this->lineElements($text, $nonNestables));
}
protected function lineElements($text, $nonNestables = array())
{
# standardize line breaks
$text = str_replace(array("\r\n", "\r"), "\n", $text);
$Elements = array();
$nonNestables = (empty($nonNestables)
? array()
: array_combine($nonNestables, $nonNestables)
);
# $excerpt is based on the first occurrence of a marker
while ($excerpt = strpbrk($text, $this->inlineMarkerList))
{
$marker = $excerpt[0];
$markerPosition = strlen($text) - strlen($excerpt);
$Excerpt = array('text' => $excerpt, 'context' => $text);
foreach ($this->InlineTypes[$marker] as $inlineType)
{
# check to see if the current inline type is nestable in the current context
if (isset($nonNestables[$inlineType]))
{
continue;
}
$Inline = $this->{"inline$inlineType"}($Excerpt);
if ( ! isset($Inline))
{
continue;
}
# makes sure that the inline belongs to "our" marker
if (isset($Inline['position']) and $Inline['position'] > $markerPosition)
{
continue;
}
# sets a default inline position
if ( ! isset($Inline['position']))
{
$Inline['position'] = $markerPosition;
}
# cause the new element to 'inherit' our non nestables
$Inline['element']['nonNestables'] = isset($Inline['element']['nonNestables'])
? array_merge($Inline['element']['nonNestables'], $nonNestables)
: $nonNestables
;
# the text that comes before the inline
$unmarkedText = substr($text, 0, $Inline['position']);
# compile the unmarked text
$InlineText = $this->inlineText($unmarkedText);
$Elements[] = $InlineText['element'];
# compile the inline
$Elements[] = $this->extractElement($Inline);
# remove the examined text
$text = substr($text, $Inline['position'] + $Inline['extent']);
continue 2;
}
# the marker does not belong to an inline
$unmarkedText = substr($text, 0, $markerPosition + 1);
$InlineText = $this->inlineText($unmarkedText);
$Elements[] = $InlineText['element'];
$text = substr($text, $markerPosition + 1);
}
$InlineText = $this->inlineText($text);
$Elements[] = $InlineText['element'];
foreach ($Elements as &$Element)
{
if ( ! isset($Element['autobreak']))
{
$Element['autobreak'] = false;
}
}
return $Elements;
}
#
# ~
#
protected function inlineText($text)
{
$Inline = array(
'extent' => strlen($text),
'element' => array(),
);
$Inline['element']['elements'] = self::pregReplaceElements(
$this->breaksEnabled ? '/[ ]*+\n/' : '/(?:[ ]*+\\\\|[ ]{2,}+)\n/',
array(
array('name' => 'br'),
array('text' => "\n"),
),
$text
);
return $Inline;
}
protected function inlineCode($Excerpt)
{
$marker = $Excerpt['text'][0];
if (preg_match('/^(['.$marker.']++)[ ]*+(.+?)[ ]*+(?<!['.$marker.'])\1(?!'.$marker.')/s', $Excerpt['text'], $matches))
{
$text = $matches[2];
$text = preg_replace('/[ ]*+\n/', ' ', $text);
return array(
'extent' => strlen($matches[0]),
'element' => array(
'name' => 'code',
'text' => $text,
),
);
}
}
protected function inlineEmailTag($Excerpt)
{
$hostnameLabel = '[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?';
$commonMarkEmail = '[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]++@'
. $hostnameLabel . '(?:\.' . $hostnameLabel . ')*';
if (strpos($Excerpt['text'], '>') !== false
and preg_match("/^<((mailto:)?$commonMarkEmail)>/i", $Excerpt['text'], $matches)
){
$url = $matches[1];
if ( ! isset($matches[2]))
{
| php | MIT | 0b274ac959624e6c6d647e9c9b6c2d20da242004 | 2026-01-04T15:02:39.892991Z | true |
erusev/parsedown | https://github.com/erusev/parsedown/blob/0b274ac959624e6c6d647e9c9b6c2d20da242004/test/CommonMarkTestWeak.php | test/CommonMarkTestWeak.php | <?php
require_once(__DIR__ . '/CommonMarkTestStrict.php');
/**
* Test Parsedown against the CommonMark spec, but less aggressive
*
* The resulting HTML markup is cleaned up before comparison, so examples
* which would normally fail due to actually invisible differences (e.g.
* superfluous whitespaces), don't fail. However, cleanup relies on block
* element detection. The detection doesn't work correctly when a element's
* `display` CSS property is manipulated. According to that this test is only
* a interim solution on Parsedown's way to full CommonMark compatibility.
*
* @link http://commonmark.org/ CommonMark
*/
class CommonMarkTestWeak extends CommonMarkTestStrict
{
protected $textLevelElementRegex;
protected function setUp() : void
{
parent::setUp();
$textLevelElements = $this->parsedown->getTextLevelElements();
array_walk($textLevelElements, function (&$element) {
$element = preg_quote($element, '/');
});
$this->textLevelElementRegex = '\b(?:' . implode('|', $textLevelElements) . ')\b';
}
/**
* @dataProvider data
* @param $id
* @param $section
* @param $markdown
* @param $expectedHtml
*/
public function testExample($id, $section, $markdown, $expectedHtml)
{
$expectedHtml = $this->cleanupHtml($expectedHtml);
$actualHtml = $this->parsedown->text($markdown);
$actualHtml = $this->cleanupHtml($actualHtml);
$this->assertEquals($expectedHtml, $actualHtml);
}
protected function cleanupHtml($markup)
{
// invisible whitespaces at the beginning and end of block elements
// however, whitespaces at the beginning of <pre> elements do matter
$markup = preg_replace(
array(
'/(<(?!(?:' . $this->textLevelElementRegex . '|\bpre\b))\w+\b[^>]*>(?:<' . $this->textLevelElementRegex . '[^>]*>)*)\s+/s',
'/\s+((?:<\/' . $this->textLevelElementRegex . '>)*<\/(?!' . $this->textLevelElementRegex . ')\w+\b>)/s'
),
'$1',
$markup
);
return $markup;
}
}
| php | MIT | 0b274ac959624e6c6d647e9c9b6c2d20da242004 | 2026-01-04T15:02:39.892991Z | false |
erusev/parsedown | https://github.com/erusev/parsedown/blob/0b274ac959624e6c6d647e9c9b6c2d20da242004/test/CommonMarkTestStrict.php | test/CommonMarkTestStrict.php | <?php
use PHPUnit\Framework\TestCase;
/**
* Test Parsedown against the CommonMark spec
*
* @link http://commonmark.org/ CommonMark
*/
class CommonMarkTestStrict extends TestCase
{
const SPEC_URL = 'https://raw.githubusercontent.com/jgm/CommonMark/master/spec.txt';
protected $parsedown;
protected function setUp() : void
{
$this->parsedown = new TestParsedown();
$this->parsedown->setUrlsLinked(false);
}
/**
* @dataProvider data
* @param $id
* @param $section
* @param $markdown
* @param $expectedHtml
*/
public function testExample($id, $section, $markdown, $expectedHtml)
{
$actualHtml = $this->parsedown->text($markdown);
$this->assertEquals($expectedHtml, $actualHtml);
}
/**
* @return array
*/
public function data()
{
$spec = file_get_contents(self::SPEC_URL);
if ($spec === false) {
$this->fail('Unable to load CommonMark spec from ' . self::SPEC_URL);
}
$spec = str_replace("\r\n", "\n", $spec);
$spec = strstr($spec, '<!-- END TESTS -->', true);
$matches = array();
preg_match_all('/^`{32} example\n((?s).*?)\n\.\n(?:|((?s).*?)\n)`{32}$|^#{1,6} *(.*?)$/m', $spec, $matches, PREG_SET_ORDER);
$data = array();
$currentId = 0;
$currentSection = '';
foreach ($matches as $match) {
if (isset($match[3])) {
$currentSection = $match[3];
} else {
$currentId++;
$markdown = str_replace('→', "\t", $match[1]);
$expectedHtml = isset($match[2]) ? str_replace('→', "\t", $match[2]) : '';
$data[$currentId] = array(
'id' => $currentId,
'section' => $currentSection,
'markdown' => $markdown,
'expectedHtml' => $expectedHtml
);
}
}
return $data;
}
}
| php | MIT | 0b274ac959624e6c6d647e9c9b6c2d20da242004 | 2026-01-04T15:02:39.892991Z | false |
erusev/parsedown | https://github.com/erusev/parsedown/blob/0b274ac959624e6c6d647e9c9b6c2d20da242004/test/TestParsedown.php | test/TestParsedown.php | <?php
class TestParsedown extends Parsedown
{
public function getTextLevelElements()
{
return $this->textLevelElements;
}
}
| php | MIT | 0b274ac959624e6c6d647e9c9b6c2d20da242004 | 2026-01-04T15:02:39.892991Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.