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
symfony/ldap
https://github.com/symfony/ldap/blob/180c544c90b46fbca1ea7501d0ae2129aaf60530/Security/CheckLdapCredentialsListener.php
Security/CheckLdapCredentialsListener.php
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Ldap\Security; use Psr\Container\ContainerInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\Ldap\Exception\InvalidCredentialsException; use Symfony\Component\Ldap\Exception\InvalidSearchCredentialsException; use Symfony\Component\Ldap\LdapInterface; use Symfony\Component\Security\Core\Exception\BadCredentialsException; use Symfony\Component\Security\Core\Exception\LogicException; use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials; use Symfony\Component\Security\Http\Event\CheckPassportEvent; /** * Verifies password credentials using an LDAP service whenever the * LdapBadge is attached to the Security passport. * * @author Wouter de Jong <wouter@wouterj.nl> */ class CheckLdapCredentialsListener implements EventSubscriberInterface { public function __construct( private ContainerInterface $ldapLocator, ) { } public function onCheckPassport(CheckPassportEvent $event): void { $passport = $event->getPassport(); if (!$passport->hasBadge(LdapBadge::class)) { return; } /** @var LdapBadge $ldapBadge */ $ldapBadge = $passport->getBadge(LdapBadge::class); if ($ldapBadge->isResolved()) { return; } if (!$passport->hasBadge(PasswordCredentials::class)) { throw new \LogicException(\sprintf('LDAP authentication requires a passport containing password credentials, authenticator "%s" does not fulfill these requirements.', $event->getAuthenticator()::class)); } /** @var PasswordCredentials $passwordCredentials */ $passwordCredentials = $passport->getBadge(PasswordCredentials::class); if ($passwordCredentials->isResolved()) { throw new \LogicException('LDAP authentication password verification cannot be completed because something else has already resolved the PasswordCredentials.'); } if (!$this->ldapLocator->has($ldapBadge->getLdapServiceId())) { throw new \LogicException(\sprintf('Cannot check credentials using the "%s" ldap service, as such service is not found. Did you maybe forget to add the "ldap" service tag to this service?', $ldapBadge->getLdapServiceId())); } $presentedPassword = $passwordCredentials->getPassword(); if ('' === $presentedPassword) { throw new BadCredentialsException('The presented password cannot be empty.'); } $user = $passport->getUser(); /** @var LdapInterface $ldap */ $ldap = $this->ldapLocator->get($ldapBadge->getLdapServiceId()); try { if ($ldapBadge->getQueryString()) { if ('' !== $ldapBadge->getSearchDn() && '' !== $ldapBadge->getSearchPassword()) { try { $ldap->bind($ldapBadge->getSearchDn(), $ldapBadge->getSearchPassword()); } catch (InvalidCredentialsException) { throw new InvalidSearchCredentialsException(); } } else { throw new LogicException('Using the "query_string" config without using a "search_dn" and a "search_password" is not supported.'); } $identifier = $ldap->escape($user->getUserIdentifier(), '', LdapInterface::ESCAPE_FILTER); $query = str_replace('{user_identifier}', $identifier, $ldapBadge->getQueryString()); $result = $ldap->query($ldapBadge->getDnString(), $query)->execute(); if (1 !== $result->count()) { throw new BadCredentialsException('The presented user identifier is invalid.'); } $dn = $result[0]->getDn(); } else { $identifier = $ldap->escape($user->getUserIdentifier(), '', LdapInterface::ESCAPE_DN); $dn = str_replace('{user_identifier}', $identifier, $ldapBadge->getDnString()); } $ldap->bind($dn, $presentedPassword); } catch (InvalidCredentialsException) { throw new BadCredentialsException('The presented password is invalid.'); } $passwordCredentials->markResolved(); $ldapBadge->markResolved(); } public static function getSubscribedEvents(): array { return [CheckPassportEvent::class => ['onCheckPassport', 144]]; } }
php
MIT
180c544c90b46fbca1ea7501d0ae2129aaf60530
2026-01-05T05:06:37.562733Z
false
symfony/ldap
https://github.com/symfony/ldap/blob/180c544c90b46fbca1ea7501d0ae2129aaf60530/Security/LdapAuthenticator.php
Security/LdapAuthenticator.php
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Ldap\Security; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Http\Authenticator\AuthenticatorInterface; use Symfony\Component\Security\Http\Authenticator\InteractiveAuthenticatorInterface; use Symfony\Component\Security\Http\Authenticator\Passport\Passport; use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface; use Symfony\Component\Security\Http\EntryPoint\Exception\NotAnEntryPointException; /** * This class decorates internal authenticators to add the LDAP integration. * * In your own authenticators, it is recommended to directly use the * LdapBadge in the authenticate() method. This class should only be * used for Symfony or third party authenticators. * * @author Wouter de Jong <wouter@wouterj.nl> * * @final */ class LdapAuthenticator implements AuthenticationEntryPointInterface, InteractiveAuthenticatorInterface { public function __construct( private AuthenticatorInterface $authenticator, private string $ldapServiceId, private string $dnString = '{user_identifier}', private string $searchDn = '', private string $searchPassword = '', private string $queryString = '', ) { } public function supports(Request $request): ?bool { return $this->authenticator->supports($request); } public function authenticate(Request $request): Passport { $passport = $this->authenticator->authenticate($request); $passport->addBadge(new LdapBadge($this->ldapServiceId, $this->dnString, $this->searchDn, $this->searchPassword, $this->queryString)); return $passport; } public function createToken(Passport $passport, string $firewallName): TokenInterface { return $this->authenticator->createToken($passport, $firewallName); } public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response { return $this->authenticator->onAuthenticationSuccess($request, $token, $firewallName); } public function onAuthenticationFailure(Request $request, AuthenticationException $exception): ?Response { return $this->authenticator->onAuthenticationFailure($request, $exception); } public function start(Request $request, ?AuthenticationException $authException = null): Response { if (!$this->authenticator instanceof AuthenticationEntryPointInterface) { throw new NotAnEntryPointException(\sprintf('Decorated authenticator "%s" does not implement interface "%s".', get_debug_type($this->authenticator), AuthenticationEntryPointInterface::class)); } return $this->authenticator->start($request, $authException); } public function isInteractive(): bool { if ($this->authenticator instanceof InteractiveAuthenticatorInterface) { return $this->authenticator->isInteractive(); } return false; } }
php
MIT
180c544c90b46fbca1ea7501d0ae2129aaf60530
2026-01-05T05:06:37.562733Z
false
symfony/ldap
https://github.com/symfony/ldap/blob/180c544c90b46fbca1ea7501d0ae2129aaf60530/Security/LdapUserProvider.php
Security/LdapUserProvider.php
<?php /* * This file is part of the Symfony package. * * (c) Fabien Potencier <fabien@symfony.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace Symfony\Component\Ldap\Security; use Symfony\Component\Ldap\Entry; use Symfony\Component\Ldap\Exception\ExceptionInterface; use Symfony\Component\Ldap\Exception\InvalidCredentialsException; use Symfony\Component\Ldap\Exception\InvalidSearchCredentialsException; use Symfony\Component\Ldap\LdapInterface; use Symfony\Component\Security\Core\Exception\InvalidArgumentException; use Symfony\Component\Security\Core\Exception\UnsupportedUserException; use Symfony\Component\Security\Core\Exception\UserNotFoundException; use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface; use Symfony\Component\Security\Core\User\PasswordUpgraderInterface; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\User\UserProviderInterface; /** * LdapUserProvider is a simple user provider on top of LDAP. * * @author Grégoire Pineau <lyrixx@lyrixx.info> * @author Charles Sarrazin <charles@sarraz.in> * @author Robin Chalas <robin.chalas@gmail.com> * * @template-implements UserProviderInterface<LdapUser> */ class LdapUserProvider implements UserProviderInterface, PasswordUpgraderInterface { private string $uidKey; private string $defaultSearch; private RoleFetcherInterface $roleFetcher; public function __construct( private LdapInterface $ldap, private string $baseDn, private ?string $searchDn = null, #[\SensitiveParameter] private ?string $searchPassword = null, array|RoleFetcherInterface $defaultRoles = [], ?string $uidKey = null, ?string $filter = null, private ?string $passwordAttribute = null, private array $extraFields = [], ) { $uidKey ??= 'sAMAccountName'; $filter ??= '({uid_key}={user_identifier})'; $this->uidKey = $uidKey; $this->defaultSearch = str_replace('{uid_key}', $uidKey, $filter); $this->roleFetcher = \is_array($defaultRoles) ? new AssignDefaultRoles($defaultRoles) : $defaultRoles; } public function loadUserByIdentifier(string $identifier): UserInterface { try { $this->ldap->bind($this->searchDn, $this->searchPassword); } catch (InvalidCredentialsException) { throw new InvalidSearchCredentialsException(); } $identifier = $this->ldap->escape($identifier, '', LdapInterface::ESCAPE_FILTER); $query = str_replace('{user_identifier}', $identifier, $this->defaultSearch); $search = $this->ldap->query($this->baseDn, $query, ['filter' => 0 == \count($this->extraFields) ? '*' : $this->extraFields]); $entries = $search->execute(); $count = \count($entries); if (!$count) { $e = new UserNotFoundException(\sprintf('User "%s" not found.', $identifier)); $e->setUserIdentifier($identifier); throw $e; } if ($count > 1) { $e = new UserNotFoundException('More than one user found.'); $e->setUserIdentifier($identifier); throw $e; } $entry = $entries[0]; try { $identifier = $this->getAttributeValue($entry, $this->uidKey); } catch (InvalidArgumentException) { } return $this->loadUser($identifier, $entry); } public function refreshUser(UserInterface $user): UserInterface { if (!$user instanceof LdapUser) { throw new UnsupportedUserException(\sprintf('Instances of "%s" are not supported.', get_debug_type($user))); } return new LdapUser($user->getEntry(), $user->getUserIdentifier(), $user->getPassword(), $user->getRoles(), $user->getExtraFields()); } /** * @final */ public function upgradePassword(PasswordAuthenticatedUserInterface $user, string $newHashedPassword): void { if (!$user instanceof LdapUser) { throw new UnsupportedUserException(\sprintf('Instances of "%s" are not supported.', get_debug_type($user))); } if (null === $this->passwordAttribute) { return; } try { $user->getEntry()->setAttribute($this->passwordAttribute, [$newHashedPassword]); $this->ldap->getEntryManager()->update($user->getEntry()); $user->setPassword($newHashedPassword); } catch (ExceptionInterface) { // ignore failed password upgrades } } public function supportsClass(string $class): bool { return LdapUser::class === $class; } /** * Loads a user from an LDAP entry. */ protected function loadUser(string $identifier, Entry $entry): UserInterface { $password = null; $extraFields = []; if (null !== $this->passwordAttribute) { $password = $this->getAttributeValue($entry, $this->passwordAttribute); } foreach ($this->extraFields as $field) { $extraFields[$field] = $this->getAttributeValue($entry, $field); } $roles = $this->roleFetcher->fetchRoles($entry); return new LdapUser($entry, $identifier, $password, $roles, $extraFields); } private function getAttributeValue(Entry $entry, string $attribute): mixed { if (!$entry->hasAttribute($attribute)) { throw new InvalidArgumentException(\sprintf('Missing attribute "%s" for user "%s".', $attribute, $entry->getDn())); } $values = $entry->getAttribute($attribute); if (!\in_array($attribute, [$this->uidKey, $this->passwordAttribute])) { return $values; } if (1 !== \count($values)) { throw new InvalidArgumentException(\sprintf('Attribute "%s" has multiple values.', $attribute)); } return $values[0]; } }
php
MIT
180c544c90b46fbca1ea7501d0ae2129aaf60530
2026-01-05T05:06:37.562733Z
false
Intervention/image-laravel
https://github.com/Intervention/image-laravel/blob/2d55a29c191025f2e6433ad2558fd8e80695e3e2/src/ImageResponseFactory.php
src/ImageResponseFactory.php
<?php declare(strict_types=1); namespace Intervention\Image\Laravel; use Illuminate\Http\Response; use Intervention\Image\Exceptions\DriverException; use Intervention\Image\Exceptions\NotSupportedException; use Intervention\Image\Exceptions\RuntimeException; use Intervention\Image\FileExtension; use Intervention\Image\Format; use Intervention\Image\Image; use Intervention\Image\MediaType; class ImageResponseFactory { /** * Image encoder options * * @var array<string, mixed> */ protected array $options = []; /** * Create new ImageResponseFactory instance * * @param Image $image * @param null|string|Format|MediaType|FileExtension $format * @param mixed ...$options * @return void */ public function __construct( protected Image $image, protected null|string|Format|MediaType|FileExtension $format = null, mixed ...$options ) { $this->options = $options; } /** * Static factory method to create HTTP response directly * * @param Image $image * @param null|string|Format|MediaType|FileExtension $format * @param mixed ...$options * @throws NotSupportedException * @throws DriverException * @throws RuntimeException * @return Response */ public static function make( Image $image, null|string|Format|MediaType|FileExtension $format = null, mixed ...$options, ): Response { return (new self($image, $format, ...$options))->response(); } /** * Create HTTP response * * @throws NotSupportedException * @throws DriverException * @throws RuntimeException * @return Response */ public function response(): Response { return new Response( content: $this->content(), headers: $this->headers() ); } /** * Read image contents * * @throws NotSupportedException * @throws DriverException * @throws RuntimeException * @return string */ private function content(): string { return (string) $this->image->encodeByMediaType( $this->format()->mediaType(), ...$this->options ); } /** * Return HTTP response headers to be attached in the image response * * @return array */ private function headers(): array { return [ 'Content-Type' => $this->format()->mediaType()->value ]; } /** * Determine the target format of the image in the HTTP response * * @return Format */ private function format(): Format { if ($this->format instanceof Format) { return $this->format; } if (($this->format instanceof MediaType)) { return $this->format->format(); } if ($this->format instanceof FileExtension) { return $this->format->format(); } if (is_string($this->format)) { return Format::create($this->format); } // target format is undefined (null) at this point: // try to extract the original image format or use jpeg by default. return Format::tryCreate($this->image->origin()->mediaType()) ?? Format::JPEG; } }
php
MIT
2d55a29c191025f2e6433ad2558fd8e80695e3e2
2026-01-05T05:06:52.912739Z
false
Intervention/image-laravel
https://github.com/Intervention/image-laravel/blob/2d55a29c191025f2e6433ad2558fd8e80695e3e2/src/ServiceProvider.php
src/ServiceProvider.php
<?php declare(strict_types=1); namespace Intervention\Image\Laravel; use Illuminate\Contracts\Routing\ResponseFactory; use Illuminate\Support\Facades\Response as ResponseFacade; use Illuminate\Support\ServiceProvider as BaseServiceProvider; use Intervention\Image\ImageManager; use Intervention\Image\Image; use Illuminate\Http\Response; use Intervention\Image\FileExtension; use Intervention\Image\Format; use Intervention\Image\MediaType; class ServiceProvider extends BaseServiceProvider { /** * Bootstrap application events * * @return void */ public function boot() { // define config files for publishing $this->publishes([ __DIR__ . '/../config/image.php' => config_path(Facades\Image::BINDING . '.php') ]); $this->app->afterResolving(ResponseFactory::class, function (): void { // register response macro "image" if ($this->shouldCreateResponseMacro()) { ResponseFacade::macro(Facades\Image::BINDING, function ( Image $image, null|string|Format|MediaType|FileExtension $format = null, mixed ...$options, ): Response { return ImageResponseFactory::make($image, $format, ...$options); }); } }); } /** * Register the image service * * @return void */ public function register() { $this->mergeConfigFrom( __DIR__ . '/../config/image.php', Facades\Image::BINDING ); $this->app->singleton(Facades\Image::BINDING, function () { return new ImageManager( driver: config('image.driver'), autoOrientation: config('image.options.autoOrientation', true), decodeAnimation: config('image.options.decodeAnimation', true), blendingColor: config('image.options.blendingColor', 'ffffff'), strip: config('image.options.strip', false) ); }); } /** * Determine if response macro should be created */ private function shouldCreateResponseMacro(): bool { if (!$this->app->runningUnitTests() && $this->app->runningInConsole()) { return false; } return !ResponseFacade::hasMacro(Facades\Image::BINDING); } }
php
MIT
2d55a29c191025f2e6433ad2558fd8e80695e3e2
2026-01-05T05:06:52.912739Z
false
Intervention/image-laravel
https://github.com/Intervention/image-laravel/blob/2d55a29c191025f2e6433ad2558fd8e80695e3e2/src/Facades/Image.php
src/Facades/Image.php
<?php declare(strict_types=1); namespace Intervention\Image\Laravel\Facades; use Illuminate\Support\Facades\Facade; /** * @method static \Intervention\Image\Interfaces\ImageInterface read(mixed $input, string|array|\Intervention\Image\Interfaces\DecoderInterface $decoders = []) * @method static \Intervention\Image\Interfaces\ImageInterface create(int $width, int $height) * @method static \Intervention\Image\Interfaces\ImageInterface animate(callable $callback) */ class Image extends Facade { /** * Binding name of the service container */ public const BINDING = 'image'; protected static function getFacadeAccessor() { return self::BINDING; } }
php
MIT
2d55a29c191025f2e6433ad2558fd8e80695e3e2
2026-01-05T05:06:52.912739Z
false
Intervention/image-laravel
https://github.com/Intervention/image-laravel/blob/2d55a29c191025f2e6433ad2558fd8e80695e3e2/tests/FacadeTest.php
tests/FacadeTest.php
<?php declare(strict_types=1); namespace Intervention\Image\Laravel\Tests; use Illuminate\Http\UploadedFile; use Illuminate\Support\Facades\Storage; use Intervention\Image\Exceptions\DecoderException; use Intervention\Image\Interfaces\ImageInterface; use Intervention\Image\Laravel\Facades\Image; use Orchestra\Testbench\Concerns\WithWorkbench; use Orchestra\Testbench\TestCase as TestBenchTestCase; use ReflectionClass; use TypeError; use ValueError; final class FacadeTest extends TestBenchTestCase { use WithWorkbench; public function testImageFacadeIsASubclassOfFacade(): void { $facade = new ReflectionClass('Illuminate\Support\Facades\Facade'); $reflection = new ReflectionClass('Intervention\Image\Laravel\Facades\Image'); $this->assertTrue($reflection->isSubclassOf($facade)); } public function testFacadeAccessorReturnsImage(): void { $reflection = new ReflectionClass('Intervention\Image\Laravel\Facades\Image'); $method = $reflection->getMethod('getFacadeAccessor'); $method->setAccessible(true); $this->assertSame('image', $method->invoke(null)); } public function testReadAnImage(): void { Storage::fake('images'); $input = UploadedFile::fake()->image('image.jpg'); $result = Image::read($input); $this->assertInstanceOf(ImageInterface::class, $result); } public function testThrowsExceptionWhenReadingNonExistentImage(): void { $this->expectException(DecoderException::class); $input = 'path/to/non_existent_image.jpg'; Image::read($input); } public function testCreateAnImage(): void { $width = 200; $height = 200; $result = Image::create($width, $height); $this->assertInstanceOf(ImageInterface::class, $result); } public function testThrowsExceptionWhenCreatingImageWithInvalidDimensions(): void { $this->expectException(ValueError::class); $width = -200; $height = 200; Image::create($width, $height); } public function testAnimateAnImage(): void { $result = Image::animate(fn () => null); $this->assertInstanceOf(ImageInterface::class, $result); } public function testThrowsExceptionWhenAnimatingImageWithInvalidCallback(): void { $this->expectException(TypeError::class); $callback = 'not_callable'; Image::animate($callback); } }
php
MIT
2d55a29c191025f2e6433ad2558fd8e80695e3e2
2026-01-05T05:06:52.912739Z
false
Intervention/image-laravel
https://github.com/Intervention/image-laravel/blob/2d55a29c191025f2e6433ad2558fd8e80695e3e2/tests/ImageResponseFactoryTest.php
tests/ImageResponseFactoryTest.php
<?php declare(strict_types=1); namespace Intervention\Image\Laravel\Tests; use finfo; use Intervention\Image\Exceptions\NotSupportedException; use Intervention\Image\FileExtension; use Intervention\Image\Format; use Intervention\Image\Image; use Intervention\Image\ImageManager; use Intervention\Image\Laravel\ImageResponseFactory; use Intervention\Image\MediaType; use PHPUnit\Framework\TestCase; class ImageResponseFactoryTest extends TestCase { protected Image $image; protected function setUp(): void { $this->image = ImageManager::gd()->create(3, 2)->fill('f50'); } public function testDefaultFormat(): void { $response = ImageResponseFactory::make($this->image); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('image/jpeg', $response->headers->get('content-type')); $this->assertMimeType('image/jpeg', $response->content()); $response = ImageResponseFactory::make(ImageManager::gd()->read($this->image->toGif())); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('image/gif', $response->headers->get('content-type')); $this->assertMimeType('image/gif', $response->content()); } public function testNonDefaultFormat(): void { $response = ImageResponseFactory::make( $this->image, Format::GIF, ); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('image/gif', $response->headers->get('content-type')); $this->assertMimeType('image/gif', $response->content()); $response = ImageResponseFactory::make( ImageManager::gd()->read($this->image->toGif()), Format::JPEG, ); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('image/jpeg', $response->headers->get('content-type')); $this->assertMimeType('image/jpeg', $response->content()); } public function testStringFormat(): void { $response = ImageResponseFactory::make( $this->image, 'gif', ); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('image/gif', $response->headers->get('content-type')); $this->assertMimeType('image/gif', $response->content()); $response = ImageResponseFactory::make( ImageManager::gd()->read($this->image->toGif()), 'jpg', ); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('image/jpeg', $response->headers->get('content-type')); $this->assertMimeType('image/jpeg', $response->content()); $response = ImageResponseFactory::make( ImageManager::gd()->read($this->image->toGif()), 'image/jpeg', ); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('image/jpeg', $response->headers->get('content-type')); $this->assertMimeType('image/jpeg', $response->content()); } public function testMediaTypeFormat(): void { $response = ImageResponseFactory::make( $this->image, MediaType::IMAGE_GIF, ); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('image/gif', $response->headers->get('content-type')); $this->assertMimeType('image/gif', $response->content()); $response = ImageResponseFactory::make( ImageManager::gd()->read($this->image->toGif()), MediaType::IMAGE_JPEG, ); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('image/jpeg', $response->headers->get('content-type')); $this->assertMimeType('image/jpeg', $response->content()); $response = ImageResponseFactory::make( ImageManager::gd()->read($this->image->toGif()), MediaType::IMAGE_JPEG, ); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('image/jpeg', $response->headers->get('content-type')); $this->assertMimeType('image/jpeg', $response->content()); } public function testFileExtensionFormat(): void { $response = ImageResponseFactory::make( $this->image, FileExtension::GIF ); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('image/gif', $response->headers->get('content-type')); $this->assertMimeType('image/gif', $response->content()); $response = ImageResponseFactory::make( ImageManager::gd()->read($this->image->toGif()), FileExtension::JPG ); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('image/jpeg', $response->headers->get('content-type')); $this->assertMimeType('image/jpeg', $response->content()); $response = ImageResponseFactory::make( ImageManager::gd()->read($this->image->toGif()), FileExtension::JPEG ); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('image/jpeg', $response->headers->get('content-type')); $this->assertMimeType('image/jpeg', $response->content()); } public function testUnknownFormat(): void { $this->expectException(NotSupportedException::class); ImageResponseFactory::make($this->image, 'unknown'); } public function testWithEncoderOptions(): void { $response = ImageResponseFactory::make($this->image, Format::JPEG, quality: 10); $this->assertEquals(200, $response->getStatusCode()); $this->assertEquals('image/jpeg', $response->headers->get('content-type')); $this->assertMimeType('image/jpeg', $response->content()); } private function assertMimeType(string $mimeType, string $contents): void { $detected = (new finfo(FILEINFO_MIME))->buffer($contents); $this->assertTrue( str_starts_with($detected, $mimeType), 'The detected type ' . $detected . ' does not correspond to ' . $mimeType . '.' ); } }
php
MIT
2d55a29c191025f2e6433ad2558fd8e80695e3e2
2026-01-05T05:06:52.912739Z
false
Intervention/image-laravel
https://github.com/Intervention/image-laravel/blob/2d55a29c191025f2e6433ad2558fd8e80695e3e2/config/image.php
config/image.php
<?php return [ /* |-------------------------------------------------------------------------- | Image Driver |-------------------------------------------------------------------------- | | Intervention Image supports “GD Library” and “Imagick” to process images | internally. Depending on your PHP setup, you can choose one of them. | | Included options: | - \Intervention\Image\Drivers\Gd\Driver::class | - \Intervention\Image\Drivers\Imagick\Driver::class | */ 'driver' => \Intervention\Image\Drivers\Gd\Driver::class, /* |-------------------------------------------------------------------------- | Configuration Options |-------------------------------------------------------------------------- | | These options control the behavior of Intervention Image. | | - "autoOrientation" controls whether an imported image should be | automatically rotated according to any existing Exif data. | | - "decodeAnimation" decides whether a possibly animated image is | decoded as such or whether the animation is discarded. | | - "blendingColor" Defines the default blending color. | | - "strip" controls if meta data like exif tags should be removed when | encoding images. */ 'options' => [ 'autoOrientation' => true, 'decodeAnimation' => true, 'blendingColor' => 'ffffff', 'strip' => false, ] ];
php
MIT
2d55a29c191025f2e6433ad2558fd8e80695e3e2
2026-01-05T05:06:52.912739Z
false
coryetzkorn/php-store-hours
https://github.com/coryetzkorn/php-store-hours/blob/4d1ffaeb6485d04470d2871de4e223ff1b9f9479/StoreHours.class.php
StoreHours.class.php
<?php /** * ---------------------------------- * PHP STORE HOURS * ---------------------------------- * Version 3.1 * Written by Cory Etzkorn * https://github.com/coryetzkorn/php-store-hours * * DO NOT MODIFY THIS CLASS FILE */ class StoreHours { /** * * @var array */ private $hours; /** * * @var array */ private $exceptions; /** * * @var array */ private $config; /** * * @var boolean */ private $yesterdayFlag; /** * * @param array $hours * @param array $exceptions * @param array $config */ public function __construct($hours = array(), $exceptions = array(), $config = array()) { $this->exceptions = $exceptions; $this->config = $config; $this->yesterdayFlag = false; $weekdayToIndex = array( 'mon' => 1, 'tue' => 2, 'wed' => 3, 'thu' => 4, 'fri' => 5, 'sat' => 6, 'sun' => 7 ); $this->hours = array(); foreach ($hours as $key => $value) { $this->hours[$weekdayToIndex[$key]] = $value; } // Remove empty elements from values (backwards compatibility) foreach ($this->hours as $key => $value) { $this->hours[$key] = array_filter($value, function($element) { return (trim($element) !== ''); }); } // Remove empty elements from values (backwards compatibility) foreach ($this->exceptions as $key => $value) { $this->exceptions[$key] = array_filter($value, function($element) { return (trim($element) !== ''); }); } $defaultConfig = array( 'separator' => ' - ', 'join' => ' and ', 'format' => 'g:ia', 'overview_weekdays' => array( 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun' ) ); $this->config += $defaultConfig; } /** * * @param string $timestamp * @return boolean */ private function is_open_at($timestamp = null) { $timestamp = (null !== $timestamp) ? $timestamp : time(); $is_open = false; $this->yesterdayFlag = false; // Check whether shop's still open from day before $ts_yesterday = strtotime(date('Y-m-d H:i:s', $timestamp) . ' -1 day'); $yesterday = date('Y-m-d', $ts_yesterday); $hours_yesterday = $this->hours_today_array($ts_yesterday); foreach ($hours_yesterday as $range) { $range = explode('-', $range); $start = strtotime($yesterday . ' ' . $range[0]); $end = strtotime($yesterday . ' ' . $range[1]); if ($end <= $start) { $end = strtotime($yesterday . ' ' . $range[1] . ' +1 day'); } if ($start <= $timestamp && $timestamp <= $end) { $is_open = true; $this->yesterdayFlag = true; break; } } // Check today's hours if (!$is_open) { $day = date('Y-m-d', $timestamp); $hours_today_array = $this->hours_today_array($timestamp); foreach ($hours_today_array as $range) { $range = explode('-', $range); $start = strtotime($day . ' ' . $range[0]); $end = strtotime($day . ' ' . $range[1]); if ($end <= $start) { $end = strtotime($day . ' ' . $range[1] . ' +1 day'); } if ($start <= $timestamp && $timestamp <= $end) { $is_open = true; break; } } } return $is_open; } /** * * @param array $ranges * @return string */ private function format_hours(array $ranges) { $hoursparts = array(); foreach ($ranges as $range) { $day = '2016-01-01'; $range = explode('-', $range); $start = strtotime($day . ' ' . $range[0]); $end = strtotime($day . ' ' . $range[1]); $hoursparts[] = date($this->config['format'], $start) . $this->config['separator'] . date($this->config['format'], $end); } return implode($this->config['join'], $hoursparts); } /** * * @param string $timestamp * @return array today's hours as array */ private function hours_today_array($timestamp = null) { $timestamp = (null !== $timestamp) ? $timestamp : time(); $today = strtotime(date('Y-m-d', $timestamp) . ' midnight'); $weekday_short = date('N', $timestamp); $hours_today_array = array(); if (isset($this->hours[$weekday_short])) { $hours_today_array = $this->hours[$weekday_short]; } foreach ($this->exceptions as $ex_day => $ex_hours) { if (strtotime($ex_day) === $today) { // Today is an exception, use alternate hours instead $hours_today_array = $ex_hours; } } return $hours_today_array; } /** * * @return array */ private function hours_this_week_simple() { $lookup = array_combine(range(1, 7), $this->config['overview_weekdays']); $ret = array(); for ($i = 1; $i <= 7; $i++) { $hours_str = (isset($this->hours[$i]) && count($this->hours[$i]) > 0) ? $this->format_hours($this->hours[$i]) : '-'; $ret[$lookup[$i]] = $hours_str; } return $ret; } /** * * @return array */ private function hours_this_week_grouped() { $lookup = array_combine(range(1, 7), $this->config['overview_weekdays']); $blocks = array(); // Remove empty elements ("closed all day") $hours = array_filter($this->hours, function($element) { return (count($element) > 0); }); foreach ($hours as $weekday => $hours2) { foreach ($blocks as &$block) { if ($block['hours'] === $hours2) { $block['days'][] = $weekday; continue 2; } } unset($block); $blocks[] = array( 'days' => array( $weekday ), 'hours' => $hours2 ); } // Flatten $ret = array(); foreach ($blocks as $block) { // Format days $keyparts = array(); $keys = $block['days']; $buffer = array(); $lastIndex = null; $minGroupSize = 3; foreach ($keys as $index) { if ($lastIndex !== null && $index - 1 !== $lastIndex) { if (count($buffer) >= $minGroupSize) { $keyparts[] = $lookup[$buffer[0]] . '-' . $lookup[$buffer[count($buffer) - 1]]; } else { foreach ($buffer as $b) { $keyparts[] = $lookup[$b]; } } $buffer = array(); } $buffer[] = $index; $lastIndex = $index; } if (count($buffer) >= $minGroupSize) { $keyparts[] = $lookup[$buffer[0]] . '-' . $lookup[$buffer[count($buffer) - 1]]; } else { foreach ($buffer as $b) { $keyparts[] = $lookup[$b]; } } // Combine $ret[implode(', ', $keyparts)] = $this->format_hours($block['hours']); } return $ret; } /** * * @return string */ public function is_open() { return $this->is_open_at(); } /** * * @return string */ public function hours_today() { $hours_today = $this->hours_today_array(); return $this->format_hours($hours_today); } /** * * @return array */ public function hours_this_week($groupSameDays = false) { return (true === $groupSameDays) ? $this->hours_this_week_grouped() : $this->hours_this_week_simple(); } }
php
MIT
4d1ffaeb6485d04470d2871de4e223ff1b9f9479
2026-01-05T05:06:53.571614Z
false
coryetzkorn/php-store-hours
https://github.com/coryetzkorn/php-store-hours/blob/4d1ffaeb6485d04470d2871de4e223ff1b9f9479/StoreHours2.class.php
StoreHours2.class.php
<?php /** * ---------------------------------- * PHP STORE HOURS * ---------------------------------- * Version 3.1 * Written by Cory Etzkorn * https://github.com/coryetzkorn/php-store-hours * * DO NOT MODIFY THIS CLASS FILE */ class StoreHours { /** * * @var array */ private $hours; /** * * @var array */ private $exceptions; /** * * @var array */ private $templates; /** * * @var boolean */ private $yesterdayFlag; /** * * @param array $hours * @param array $exceptions * @param array $templates */ public function __construct($hours = array(), $exceptions = array(), $templates = array()) { $this->exceptions = $exceptions; $this->templates = $templates; $this->yesterdayFlag = false; $weekdayToIndex = array( 'mon' => 1, 'tue' => 2, 'wed' => 3, 'thu' => 4, 'fri' => 5, 'sat' => 6, 'sun' => 7 ); $this->hours = array(); foreach ($hours as $key => $value) { $this->hours[$weekdayToIndex[$key]] = $value; } // Remove empty elements from values (backwards compatibility) foreach ($this->hours as $key => $value) { $this->hours[$key] = array_filter($value, function ($element) { return (trim($element) !== ''); }); } // Remove empty elements from values (backwards compatibility) foreach ($this->exceptions as $key => $value) { $this->exceptions[$key] = array_filter($value, function ($element) { return (trim($element) !== ''); }); } $defaultTemplates = array( 'open' => '<h3>Yes, we\'re open! Today\'s hours are {%hours%}.</h3>', 'closed' => '<h3>Sorry, we\'re closed. Today\'s hours are {%hours%}.</h3>', 'closed_all_day' => '<h3>Sorry, we\'re closed.</h3>', 'separator' => ' - ', 'join' => ' and ', 'format' => 'g:ia', 'hours' => '{%open%}{%separator%}{%closed%}', 'overview_separator' => '-', 'overview_join' => ', ', 'overview_format' => 'g:ia', 'overview_weekdays' => array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun') ); $this->templates += $defaultTemplates; } /** * * @param string $timestamp * @return array Today's hours */ public function hours_today($timestamp = null) { $timestamp = (null !== $timestamp) ? $timestamp : time(); $today = strtotime(date('Y-m-d', $timestamp) . ' midnight'); $weekday_short = date('N', $timestamp); $hours_today = array(); if (isset($this->hours[$weekday_short])) { $hours_today = $this->hours[$weekday_short]; } foreach ($this->exceptions as $ex_day => $ex_hours) { if (strtotime($ex_day) === $today) { // Today is an exception, use alternate hours instead $hours_today = $ex_hours; } } return $hours_today; } /** * * @param string $timestamp * @return boolean */ public function is_open($timestamp = null) { $timestamp = (null !== $timestamp) ? $timestamp : time(); $is_open = false; $this->yesterdayFlag = false; // Check whether shop's still open from day before $ts_yesterday = strtotime(date('Y-m-d H:i:s', $timestamp) . ' -1 day'); $yesterday = date('Y-m-d', $ts_yesterday); $hours_yesterday = $this->hours_today($ts_yesterday); foreach ($hours_yesterday as $range) { $range = explode('-', $range); $start = strtotime($yesterday . ' ' . $range[0]); $end = strtotime($yesterday . ' ' . $range[1]); if ($end <= $start) { $end = strtotime($yesterday . ' ' . $range[1] . ' +1 day'); } if ($start <= $timestamp && $timestamp <= $end) { $is_open = true; $this->yesterdayFlag = true; break; } } // Check today's hours if (!$is_open) { $day = date('Y-m-d', $timestamp); $hours_today = $this->hours_today($timestamp); foreach ($hours_today as $range) { $range = explode('-', $range); $start = strtotime($day . ' ' . $range[0]); $end = strtotime($day . ' ' . $range[1]); if ($end <= $start) { $end = strtotime($day . ' ' . $range[1] . ' +1 day'); } if ($start <= $timestamp && $timestamp <= $end) { $is_open = true; break; } } } return $is_open; } /** * Prep HTML * * @param string $template_name * @param int $timestamp */ private function render_html($template_name, $timestamp) { $template = $this->templates; $hours_today = $this->hours_today($timestamp); $day = date('Y-m-d', $timestamp); $output = ''; if (count($hours_today) > 0) { $hours_template = ''; $first = true; foreach ($hours_today as $range) { $range = explode('-', $range); $start = strtotime($day . ' ' . $range[0]); $end = strtotime($day . ' ' . $range[1]); if (false === $first) { $hours_template .= $template['join']; } $hours_template .= $template['hours']; $hours_template = str_replace('{%open%}', date($template['format'], $start), $hours_template); $hours_template = str_replace('{%closed%}', date($template['format'], $end), $hours_template); $hours_template = str_replace('{%separator%}', $template['separator'], $hours_template); $first = false; } $output .= str_replace('{%hours%}', $hours_template, $template[$template_name]); } else { $output .= $template['closed_all_day']; } echo $output; } /** * Output HTML * * @param string $timestamp */ public function render($timestamp = null) { $timestamp = (null !== $timestamp) ? $timestamp : time(); if ($this->is_open($timestamp)) { // Print yesterday's hours if shop's still open from day before if ($this->yesterdayFlag) { $timestamp = strtotime(date('Y-m-d H:i:s', $timestamp) . ' -1 day'); } $this->render_html('open', $timestamp); } else { $this->render_html('closed', $timestamp); } } /** * * @param array $ranges * @return string */ private function hours_overview_format_hours(array $ranges) { $hoursparts = array(); foreach ($ranges as $range) { $day = '2016-01-01'; $range = explode('-', $range); $start = strtotime($day . ' ' . $range[0]); $end = strtotime($day . ' ' . $range[1]); $hoursparts[] = date($this->templates['overview_format'], $start) . $this->templates['overview_separator'] . date($this->templates['overview_format'], $end); } return implode($this->templates['overview_join'], $hoursparts); } /** * */ private function hours_this_week_simple() { $lookup = array_combine(range(1, 7), $this->templates['overview_weekdays']); $ret = array(); for ($i = 1; $i <= 7; $i++) { $hours_str = (isset($this->hours[$i]) && count($this->hours[$i]) > 0) ? $this->hours_overview_format_hours($this->hours[$i]) : '-'; $ret[$lookup[$i]] = $hours_str; } return $ret; } /** * * @return array */ private function hours_this_week_grouped() { $lookup = array_combine(range(1, 7), $this->templates['overview_weekdays']); $blocks = array(); // Remove empty elements ("closed all day") $hours = array_filter($this->hours, function ($element) { return (count($element) > 0); }); foreach ($hours as $weekday => $hours2) { foreach ($blocks as &$block) { if ($block['hours'] === $hours2) { $block['days'][] = $weekday; continue 2; } } unset($block); $blocks[] = array('days' => array($weekday), 'hours' => $hours2); } // Flatten $ret = array(); foreach ($blocks as $block) { // Format days $keyparts = array(); $keys = $block['days']; $buffer = array(); $lastIndex = null; $minGroupSize = 3; foreach ($keys as $index) { if ($lastIndex !== null && $index - 1 !== $lastIndex) { if (count($buffer) >= $minGroupSize) { $keyparts[] = $lookup[$buffer[0]] . '-' . $lookup[$buffer[count($buffer) - 1]]; } else { foreach ($buffer as $b) { $keyparts[] = $lookup[$b]; } } $buffer = array(); } $buffer[] = $index; $lastIndex = $index; } if (count($buffer) >= $minGroupSize) { $keyparts[] = $lookup[$buffer[0]] . '-' . $lookup[$buffer[count($buffer) - 1]]; } else { foreach ($buffer as $b) { $keyparts[] = $lookup[$b]; } } // Combine $ret[implode(', ', $keyparts)] = $this->hours_overview_format_hours($block['hours']); } return $ret; } /** * * @return array */ public function hours_this_week($groupSameDays = false) { return (true === $groupSameDays) ? $this->hours_this_week_grouped() : $this->hours_this_week_simple(); } }
php
MIT
4d1ffaeb6485d04470d2871de4e223ff1b9f9479
2026-01-05T05:06:53.571614Z
false
coryetzkorn/php-store-hours
https://github.com/coryetzkorn/php-store-hours/blob/4d1ffaeb6485d04470d2871de4e223ff1b9f9479/index.php
index.php
<!DOCTYPE html> <html lang="en" xml:lang="en"><head> <meta charset="utf-8"> <head> <title>PHP Store Hours</title> <style type="text/css"> body { font-family: 'Helvetica Neue', arial; text-align: center; } table { font-size: small; text-align: left; margin: 100px auto 0 auto; border-collapse: collapse; } td { padding: 2px 8px; border: 1px solid #ccc; } </style> </head> <body> <h1>Gadgets Inc.</h1> <h2>Store Hours</h2> <?php // REQUIRED // Set your default time zone (listed here: http://php.net/manual/en/timezones.php) date_default_timezone_set('America/New_York'); // Include the store hours class require __DIR__ . '/StoreHours.class.php'; // REQUIRED // Define daily open hours // Must be in 24-hour format, separated by dash // If closed for the day, leave blank (ex. sunday) // If open multiple times in one day, enter time ranges separated by a comma $hours = array( 'mon' => array('11:00-20:30'), 'tue' => array('11:00-13:00', '18:00-20:30'), 'wed' => array('11:00-13:00', '18:00-20:30'), 'thu' => array('11:00-1:30'), // Open late 'fri' => array('11:00-20:30'), 'sat' => array('11:00-20:00'), 'sun' => array('11:00-20:00') ); // OPTIONAL // Add exceptions (great for holidays etc.) // MUST be in a format month/day[/year] or [year-]month-day // Do not include the year if the exception repeats annually $exceptions = array( '2/24' => array('11:00-18:00'), '10/18' => array('11:00-16:00', '18:00-20:30') ); $config = array( 'separator' => ' - ', 'join' => ' and ', 'format' => 'g:ia', 'overview_weekdays' => array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun') ); // Instantiate class $store_hours = new StoreHours($hours, $exceptions, $config); // Display open / closed message if($store_hours->is_open()) { echo "Yes, we're open! Today's hours are " . $store_hours->hours_today() . "."; } else { echo "Sorry, we're closed. Today's hours are " . $store_hours->hours_today() . "."; } // Display full list of open hours (for a week without exceptions) echo '<table>'; foreach ($store_hours->hours_this_week() as $days => $hours) { echo '<tr>'; echo '<td>' . $days . '</td>'; echo '<td>' . $hours . '</td>'; echo '</tr>'; } echo '</table>'; // Same list, but group days with identical hours echo '<table>'; foreach ($store_hours->hours_this_week(true) as $days => $hours) { echo '<tr>'; echo '<td>' . $days . '</td>'; echo '<td>' . $hours . '</td>'; echo '</tr>'; } echo '</table>'; ?> </body> </html>
php
MIT
4d1ffaeb6485d04470d2871de4e223ff1b9f9479
2026-01-05T05:06:53.571614Z
false
coryetzkorn/php-store-hours
https://github.com/coryetzkorn/php-store-hours/blob/4d1ffaeb6485d04470d2871de4e223ff1b9f9479/StoreHoursTest.php
StoreHoursTest.php
<?php /** * */ class StoreHoursTest extends PHPUnit_Framework_TestCase { /** * */ protected function setUp() { require_once __DIR__ . '/StoreHours.class.php'; date_default_timezone_set('UTC'); } /** * * @return \StoreHours */ private function instantiateWithDefaultData() { $hours = array( 'mon' => array('11:00-20:30'), 'tue' => array('11:00-13:00', '18:00-20:30'), 'wed' => array('11:00-20:30'), 'thu' => array('11:00-1:30'), // Open late 'fri' => array('11:00-20:30'), 'sat' => array('11:00-20:00'), 'sun' => array('') // Closed all day ); $exceptions = array( '2/24' => array('11:00-18:00'), '10/18' => array('11:00-16:00', '18:00-20:30'), '2016-02-01' => array('09:00-11:00') ); return new StoreHours($hours, $exceptions); } /** * */ public function testHoursTodayMethod() { $sh = $this->instantiateWithDefaultData(); $this->assertEquals(array('11:00-20:30'), $sh->hours_today(strtotime('2016-02-08'))); // mon $this->assertEquals(array('11:00-13:00', '18:00-20:30'), $sh->hours_today(strtotime('2016-02-09'))); // tue $this->assertEquals(array('11:00-20:30'), $sh->hours_today(strtotime('2016-02-10'))); // wed $this->assertEquals(array('11:00-1:30'), $sh->hours_today(strtotime('2016-02-11'))); // thu $this->assertEquals(array('11:00-20:30'), $sh->hours_today(strtotime('2016-02-12'))); // fri $this->assertEquals(array('11:00-20:00'), $sh->hours_today(strtotime('2016-02-13'))); // sat $this->assertEquals(array(), $sh->hours_today(strtotime('2016-02-14'))); // sun // Exceptions (dates, not the PHP kind) $this->assertEquals(array('11:00-18:00'), $sh->hours_today(strtotime('2016-02-24'))); $this->assertEquals(array('11:00-16:00', '18:00-20:30'), $sh->hours_today(strtotime('2016-10-18'))); $this->assertEquals(array('09:00-11:00'), $sh->hours_today(strtotime('2016-02-01'))); $this->assertEquals(array('11:00-20:30'), $sh->hours_today(strtotime('2017-02-01'))); // wed } /** * */ public function testIsOpenMethod() { $sh = $this->instantiateWithDefaultData(); $this->assertEquals(false, $sh->is_open(strtotime('2016-02-08 10:59:59'))); // mon $this->assertEquals(true, $sh->is_open(strtotime('2016-02-08 11:00:00'))); $this->assertEquals(true, $sh->is_open(strtotime('2016-02-08 20:30:00'))); $this->assertEquals(false, $sh->is_open(strtotime('2016-02-08 20:30:01'))); $this->assertEquals(false, $sh->is_open(strtotime('2016-02-09 10:59:59'))); // tue $this->assertEquals(true, $sh->is_open(strtotime('2016-02-09 11:00:00'))); $this->assertEquals(true, $sh->is_open(strtotime('2016-02-09 13:00:00'))); $this->assertEquals(false, $sh->is_open(strtotime('2016-02-09 13:00:01'))); $this->assertEquals(false, $sh->is_open(strtotime('2016-02-09 17:59:59'))); $this->assertEquals(true, $sh->is_open(strtotime('2016-02-09 18:00:00'))); $this->assertEquals(true, $sh->is_open(strtotime('2016-02-09 20:30:00'))); $this->assertEquals(false, $sh->is_open(strtotime('2016-02-09 20:30:01'))); // "open late" $this->assertEquals(false, $sh->is_open(strtotime('2016-02-11 00:30:00'))); // thu $this->assertEquals(true, $sh->is_open(strtotime('2016-02-11 23:59:59'))); $this->assertEquals(true, $sh->is_open(strtotime('2016-02-12 00:00:00'))); // fri $this->assertEquals(true, $sh->is_open(strtotime('2016-02-12 01:30:00'))); $this->assertEquals(false, $sh->is_open(strtotime('2016-02-12 01:30:01'))); // Exceptions (dates, not the PHP kind) $this->assertEquals(false, $sh->is_open(strtotime('2016-02-24 10:59:59'))); $this->assertEquals(true, $sh->is_open(strtotime('2016-02-24 11:00:00'))); $this->assertEquals(true, $sh->is_open(strtotime('2016-02-24 18:00:00'))); $this->assertEquals(false, $sh->is_open(strtotime('2016-02-24 18:00:01'))); $this->assertEquals(false, $sh->is_open(strtotime('2016-10-18 10:59:59'))); $this->assertEquals(true, $sh->is_open(strtotime('2016-10-18 11:00:00'))); $this->assertEquals(true, $sh->is_open(strtotime('2016-10-18 16:00:00'))); $this->assertEquals(false, $sh->is_open(strtotime('2016-10-18 16:00:01'))); $this->assertEquals(false, $sh->is_open(strtotime('2016-10-18 17:59:59'))); $this->assertEquals(true, $sh->is_open(strtotime('2016-10-18 18:00:00'))); $this->assertEquals(true, $sh->is_open(strtotime('2016-10-18 20:30:00'))); $this->assertEquals(false, $sh->is_open(strtotime('2016-10-18 20:30:01'))); $this->assertEquals(false, $sh->is_open(strtotime('2016-02-01 08:59:59'))); $this->assertEquals(true, $sh->is_open(strtotime('2016-02-01 09:00:00'))); $this->assertEquals(true, $sh->is_open(strtotime('2016-02-01 11:00:00'))); $this->assertEquals(false, $sh->is_open(strtotime('2016-02-01 11:00:01'))); $this->assertEquals(false, $sh->is_open(strtotime('2017-02-01 10:59:59'))); // wed $this->assertEquals(true, $sh->is_open(strtotime('2017-02-01 11:00:00'))); $this->assertEquals(true, $sh->is_open(strtotime('2017-02-01 20:30:00'))); $this->assertEquals(false, $sh->is_open(strtotime('2017-02-01 20:30:01'))); } /** * */ public function testRenderMethod() { $sh = $this->instantiateWithDefaultData(); ob_start(); $sh->render(strtotime('2016-02-13 14:30:00')); // sat $this->assertEquals('<h3>Yes, we\'re open! Today\'s hours are 11:00am - 8:00pm.</h3>', ob_get_clean()); ob_start(); $sh->render(strtotime('2016-02-09 14:30:00')); // tue $this->assertEquals('<h3>Sorry, we\'re closed. Today\'s hours are 11:00am - 1:00pm and 6:00pm - 8:30pm.</h3>', ob_get_clean()); ob_start(); $sh->render(strtotime('2016-02-14 12:00:00')); // sun $this->assertEquals('<h3>Sorry, we\'re closed.</h3>', ob_get_clean()); // "open late" (if still open, display hours from yesterday) ob_start(); $sh->render(strtotime('2016-02-11 23:59:59')); // night from thu->fri, thursday's hours $this->assertEquals('<h3>Yes, we\'re open! Today\'s hours are 11:00am - 1:30am.</h3>', ob_get_clean()); ob_start(); $sh->render(strtotime('2016-02-12 00:30:00')); // night from thu->fri, thursday's hours $this->assertEquals('<h3>Yes, we\'re open! Today\'s hours are 11:00am - 1:30am.</h3>', ob_get_clean()); ob_start(); $sh->render(strtotime('2016-02-12 01:30:01')); // closed on friday morning, friday's hours $this->assertEquals('<h3>Sorry, we\'re closed. Today\'s hours are 11:00am - 8:30pm.</h3>', ob_get_clean()); // Exceptions (dates, not the PHP kind) ob_start(); $sh->render(strtotime('2016-02-24 19:00:00')); $this->assertEquals('<h3>Sorry, we\'re closed. Today\'s hours are 11:00am - 6:00pm.</h3>', ob_get_clean()); ob_start(); $sh->render(strtotime('2016-10-18 19:00:00')); $this->assertEquals('<h3>Yes, we\'re open! Today\'s hours are 11:00am - 4:00pm and 6:00pm - 8:30pm.</h3>', ob_get_clean()); ob_start(); $sh->render(strtotime('2016-02-01 09:00:00')); $this->assertEquals('<h3>Yes, we\'re open! Today\'s hours are 9:00am - 11:00am.</h3>', ob_get_clean()); ob_start(); $sh->render(strtotime('2016-02-01 12:00:00')); $this->assertEquals('<h3>Sorry, we\'re closed. Today\'s hours are 9:00am - 11:00am.</h3>', ob_get_clean()); ob_start(); $sh->render(strtotime('2017-02-01 12:00:00')); // wed $this->assertEquals('<h3>Yes, we\'re open! Today\'s hours are 11:00am - 8:30pm.</h3>', ob_get_clean()); } /** * */ public function testWithCustomTemplates() { $hours = array( 'mon' => array('09:00-17:00', '17:30-18:00', '19:00-02:30'), 'thu' => array('17:45-18:00') ); $exceptions = array( '2016-02-15' => array() ); $templates = array( 'open' => 'Open. Hours {%hours%}.', 'separator' => '-', 'format' => 'G.i' ); $sh = new StoreHours($hours, $exceptions, $templates); ob_start(); $sh->render(strtotime('2016-02-08 14:30:00')); // mon $this->assertEquals('Open. Hours 9.00-17.00 and 17.30-18.00 and 19.00-2.30.', ob_get_clean()); ob_start(); $sh->render(strtotime('2016-02-11 14:30:00')); // thu $this->assertEquals('<h3>Sorry, we\'re closed. Today\'s hours are 17.45-18.00.</h3>', ob_get_clean()); ob_start(); $sh->render(strtotime('2016-02-15 14:30:00')); // mon $this->assertEquals('<h3>Sorry, we\'re closed.</h3>', ob_get_clean()); } /** * */ public function testHoursOverviewSimple() { $sh = new StoreHours(array()); $this->assertEquals(array( 'Mon' => '-', 'Tue' => '-', 'Wed' => '-', 'Thu' => '-', 'Fri' => '-', 'Sat' => '-', 'Sun' => '-' ), $sh->hours_this_week()); $sh = new StoreHours(array('fri' => array(''))); $this->assertEquals(array( 'Mon' => '-', 'Tue' => '-', 'Wed' => '-', 'Thu' => '-', 'Fri' => '-', 'Sat' => '-', 'Sun' => '-' ), $sh->hours_this_week()); $sh = new StoreHours(array( 'mon' => array('08:00-12:00', '13:00-1:30'), 'tue' => array('08:00-12:00', '13:00-1:30'), 'thu' => array('08:00-12:00', '13:00-1:30'), 'fri' => array('08:00-12:00', '13:00-1:30'), 'sun' => array('08:00-1:30') )); $this->assertEquals(array( 'Mon' => '8:00am-12:00pm, 1:00pm-1:30am', 'Tue' => '8:00am-12:00pm, 1:00pm-1:30am', 'Wed' => '-', 'Thu' => '8:00am-12:00pm, 1:00pm-1:30am', 'Fri' => '8:00am-12:00pm, 1:00pm-1:30am', 'Sat' => '-', 'Sun' => '8:00am-1:30am' ), $sh->hours_this_week()); } /** * */ public function testHoursOverviewGrouped() { $sh = new StoreHours(array()); $this->assertEquals(array(), $sh->hours_this_week(true)); $sh = new StoreHours(array('fri' => array(''))); $this->assertEquals(array(), $sh->hours_this_week(true)); $sh = new StoreHours(array( 'sun' => array('08:00-12:00') )); $this->assertEquals(array( 'Sun' => '8:00am-12:00pm' ), $sh->hours_this_week(true)); $sh = new StoreHours(array( 'mon' => array('08:00-12:00', '13:00-1:30'), 'tue' => array('08:00-12:00', '13:00-1:30') )); $this->assertEquals(array( 'Mon, Tue' => '8:00am-12:00pm, 1:00pm-1:30am' ), $sh->hours_this_week(true)); $sh = new StoreHours(array( 'mon' => array('08:00-12:00', '13:00-1:30'), 'tue' => array('08:00-12:00', '13:00-1:30'), 'wed' => array('08:00-12:00', '13:00-1:30') )); $this->assertEquals(array( 'Mon-Wed' => '8:00am-12:00pm, 1:00pm-1:30am' ), $sh->hours_this_week(true)); $sh = new StoreHours(array( 'mon' => array('08:00-12:00', '13:00-1:30'), 'tue' => array('08:00-12:00', '13:00-1:30'), 'thu' => array('08:00-12:00', '13:00-1:30'), 'fri' => array('08:00-12:00', '13:00-1:30'), 'sun' => array('08:00-1:30') )); $this->assertEquals(array( 'Mon, Tue, Thu, Fri' => '8:00am-12:00pm, 1:00pm-1:30am', 'Sun' => '8:00am-1:30am' ), $sh->hours_this_week(true)); $sh = new StoreHours(array( 'mon' => array('08:00-12:00', '13:00-1:30'), 'tue' => array('08:00-12:00', '13:00-1:30'), 'wed' => array('08:00-12:00', '13:00-1:30'), 'fri' => array('08:00-12:00', '13:00-1:30'), 'sat' => array('08:00-12:00', '13:00-1:30'), 'sun' => array('08:00-12:00', '13:00-1:30') )); $this->assertEquals(array( 'Mon-Wed, Fri-Sun' => '8:00am-12:00pm, 1:00pm-1:30am' ), $sh->hours_this_week(true)); } }
php
MIT
4d1ffaeb6485d04470d2871de4e223ff1b9f9479
2026-01-05T05:06:53.571614Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/FormatResponse.php
src/FormatResponse.php
<?php namespace Edbizarro\LaravelFacebookAds; use FacebookAds\Cursor; use Illuminate\Support\Collection; use FacebookAds\Object\AbstractObject; trait FormatResponse { protected function format(Cursor $response) { $data = new Collection; switch (true) { case $response instanceof Cursor: while ($response->getNext()) { $response->fetchAfter(); } while ($response->valid()) { $data->push($response->current()->exportAllData()); $response->next(); } break; case $response instanceof AbstractObject: $data->push($response->getLastResponse()->getContent()['data']); break; } return $data; } }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/Insights.php
src/Insights.php
<?php namespace Edbizarro\LaravelFacebookAds; use FacebookAds\Object\Ad; use FacebookAds\Object\AdSet; use FacebookAds\Object\Campaign; use FacebookAds\Object\AdAccount; use FacebookAds\Object\Values\AdsInsightsLevelValues; class Insights { use FormatResponse; public function get( Period $period, $accountId, $level, array $params ) { $levelClass = $this->selectClassByLevel($level, $accountId); $fields = $params['fields']; $params['time_increment'] = $params['time_increment'] ?? '1'; $params['limit'] = $params['limit'] ?? 100; $params['level'] = $level; $params['time_range'] = [ 'since' => $period->startDate->format('Y-m-d'), 'until' => $period->endDate->format('Y-m-d'), ]; $apiResponse = $levelClass->getInsights($fields, $params); return $this->format($apiResponse); } /** * @param string $level * @param $accountId * * @return Ad|Campaign|AdSet|AdAccount */ protected function selectClassByLevel(string $level, string $accountId) { switch ($level) { case AdsInsightsLevelValues::AD: return (new Ad)->setId($accountId); case AdsInsightsLevelValues::CAMPAIGN: return (new Campaign)->setId($accountId); case AdsInsightsLevelValues::ADSET: return (new AdSet)->setId($accountId); case AdsInsightsLevelValues::ACCOUNT: return (new AdAccount)->setId($accountId); } } }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/FacebookAds.php
src/FacebookAds.php
<?php namespace Edbizarro\LaravelFacebookAds; use Illuminate\Support\Traits\Macroable; use Edbizarro\LaravelFacebookAds\Entities\Campaigns; use Edbizarro\LaravelFacebookAds\Entities\AdAccounts; use Edbizarro\LaravelFacebookAds\Entities\InstagramAccounts; class FacebookAds extends AbstractFacebookAds { use Macroable; /** * @param Period $period * @param $accountId * @param string $level [ad, adset, campaign, account] * @param array $params * * @see https://developers.facebook.com/docs/marketing-api/insights * * @return \Illuminate\Support\Collection */ public function insights( Period $period, $accountId, $level, array $params ) { return (new Insights)->get( $period, $accountId, $level, $params ); } /** * @return AdAccounts */ public function adAccounts(): AdAccounts { return new AdAccounts; } /** * @return InstagramAccounts */ public function instagramAccounts(): InstagramAccounts { return new InstagramAccounts; } /** * @return Campaigns */ public function campaigns(): Campaigns { return new Campaigns; } }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/AbstractFacebookAds.php
src/AbstractFacebookAds.php
<?php namespace Edbizarro\LaravelFacebookAds; use FacebookAds\Api; use Illuminate\Support\Traits\Macroable; use Edbizarro\LaravelFacebookAds\Contracts\LaravelFacebookAdsContract; /** * Class AbstractFacebookAds. */ abstract class AbstractFacebookAds implements LaravelFacebookAdsContract { use Macroable; /** * @var Api */ protected $adsApiInstance; public function init($accessToken): FacebookAds { Api::init( config('facebook-ads.app_id'), config('facebook-ads.app_secret'), $accessToken ); $this->adsApiInstance = Api::instance(); return $this; } /** * Get the Facebook Ads API instance. * * @return Api */ public function getFbApiInstance(): Api { return $this->adsApiInstance; } }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/Period.php
src/Period.php
<?php namespace Edbizarro\LaravelFacebookAds; use DateTime; use Carbon\Carbon; use Edbizarro\LaravelFacebookAds\Exceptions\InvalidPeriod; class Period { /** @var \DateTime */ public $startDate; /** @var \DateTime */ public $endDate; public static function create(DateTime $startDate, DateTime $endDate): self { return new static($startDate, $endDate); } public static function days(int $numberOfDays): self { $endDate = Carbon::today(); $startDate = Carbon::today()->subDays($numberOfDays)->startOfDay(); return new static($startDate, $endDate); } public static function months(int $numberOfMonths): self { $endDate = Carbon::today(); $startDate = Carbon::today()->subMonths($numberOfMonths)->startOfDay(); return new static($startDate, $endDate); } public static function years(int $numberOfYears): self { $endDate = Carbon::today(); $startDate = Carbon::today()->subYears($numberOfYears)->startOfDay(); return new static($startDate, $endDate); } public function __construct(DateTime $startDate, DateTime $endDate) { if ($startDate > $endDate) { throw InvalidPeriod::startDateCannotBeAfterEndDate($startDate, $endDate); } $this->startDate = $startDate; $this->endDate = $endDate; } }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/Exceptions/InvalidPeriod.php
src/Exceptions/InvalidPeriod.php
<?php namespace Edbizarro\LaravelFacebookAds\Exceptions; use DateTime; use Exception; class InvalidPeriod extends Exception { public static function startDateCannotBeAfterEndDate(DateTime $startDate, DateTime $endDate) { return new static("Start date `{$startDate->format('Y-m-d')}` cannot be after end date `{$endDate->format('Y-m-d')}`."); } }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/Exceptions/MissingEntityFormatter.php
src/Exceptions/MissingEntityFormatter.php
<?php namespace Edbizarro\LaravelFacebookAds\Exceptions; use Exception; class MissingEntityFormatter extends Exception { }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/Traits/AdAccountFormatter.php
src/Traits/AdAccountFormatter.php
<?php namespace Edbizarro\LaravelFacebookAds\Traits; use Edbizarro\LaravelFacebookAds\Entities\AdAccount; /** * Class AdAccountFormatter. */ trait AdAccountFormatter { use Formatter; protected $entity = AdAccount::class; }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/Traits/AdFormatter.php
src/Traits/AdFormatter.php
<?php namespace Edbizarro\LaravelFacebookAds\Traits; use Edbizarro\LaravelFacebookAds\Entities\Ad; /** * Class AdFormatter. */ trait AdFormatter { use Formatter; protected $entity = Ad::class; }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/Traits/Formatter.php
src/Traits/Formatter.php
<?php namespace Edbizarro\LaravelFacebookAds\Traits; use FacebookAds\Cursor; use Illuminate\Support\Collection; use FacebookAds\Object\AbstractObject; use Edbizarro\LaravelFacebookAds\Exceptions\MissingEntityFormatter; /** * Class Formatter. */ trait Formatter { /** * ProcessTransform a FacebookAds\Cursor object into a Collection. * * @param Cursor|AbstractObject $response * * @return Collection|AbstractObject * @throws MissingEntityFormatter */ protected function format($response) { if ($this->entity === null) { throw new MissingEntityFormatter('To use the FormatterTrait you must provide a entity'); } switch (true) { case $response instanceof Cursor: $data = new Collection; while ($response->current()) { $data->push(new $this->entity($response->current())); $response->next(); } return $data; case $response instanceof AbstractObject: return new $this->entity($response); } } }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/Traits/HasAccountUser.php
src/Traits/HasAccountUser.php
<?php namespace Edbizarro\LaravelFacebookAds\Traits; use FacebookAds\Object\User; trait HasAccountUser { /** * @param string|int $accountUserId * * @return User */ protected function accountUser($accountUserId = 'me'): User { return (new User)->setId($accountUserId); } }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/Contracts/LaravelFacebookAdsContract.php
src/Contracts/LaravelFacebookAdsContract.php
<?php namespace Edbizarro\LaravelFacebookAds\Contracts; use Edbizarro\LaravelFacebookAds\FacebookAds; /** * Interface LaravelFacebookAdsContract. */ interface LaravelFacebookAdsContract { /** * Initialize the Facebook Ads SDK. * * @param $accessToken * * @return FacebookAds */ public function init($accessToken): FacebookAds; }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/Entities/Campaigns.php
src/Entities/Campaigns.php
<?php namespace Edbizarro\LaravelFacebookAds\Entities; use FacebookAds\Object\AdAccount; use Illuminate\Support\Collection; use Edbizarro\LaravelFacebookAds\Traits\Formatter; /** * Class Campaigns. */ class Campaigns { use Formatter; protected $entity = Campaign::class; /** * List all campaigns. * * @param array $fields * @param string $accountId * * @return Collection * * @see https://developers.facebook.com/docs/marketing-api/reference/ad-account/campaigns * @throws \Edbizarro\LaravelFacebookAds\Exceptions\MissingEntityFormatter */ public function all(array $fields, string $accountId): Collection { return $this->format( (new AdAccount)->setId($accountId)->getCampaigns($fields) ); } }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/Entities/Campaign.php
src/Entities/Campaign.php
<?php namespace Edbizarro\LaravelFacebookAds\Entities; use Edbizarro\LaravelFacebookAds\Traits\Formatter; class Campaign extends AbstractEntity { use Formatter; }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/Entities/InstagramAccount.php
src/Entities/InstagramAccount.php
<?php namespace Edbizarro\LaravelFacebookAds\Entities; use Illuminate\Support\Collection; use Edbizarro\LaravelFacebookAds\Traits\AdFormatter; /** * Class AdAccount. */ class InstagramAccount extends AbstractEntity { use AdFormatter; /** * Get the account ads. * * @param array $fields * * @return Collection * * @see https://developers.facebook.com/docs/marketing-api/reference/adgroup#Reading * @throws \Edbizarro\LaravelFacebookAds\Exceptions\MissingEntityFormatter */ public function ads(array $fields = []): Collection { $ads = $this->response->getAds($fields); return $this->format($ads); } }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/Entities/Ad.php
src/Entities/Ad.php
<?php namespace Edbizarro\LaravelFacebookAds\Entities; use Edbizarro\LaravelFacebookAds\Traits\AdFormatter; /** * Class Ad. */ class Ad extends AbstractEntity { use AdFormatter; }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/Entities/Insights.php
src/Entities/Insights.php
<?php namespace Edbizarro\LaravelFacebookAds\Entities; use FacebookAds\Object\AdAccount; use Illuminate\Support\Collection; use Edbizarro\LaravelFacebookAds\Traits\Formatter; /** * Class Campaigns. */ class Insights { use Formatter; protected $entity = Campaign::class; /** * List all campaigns. * * @param array $fields * @param string $accountId * * * @return \FacebookAds\Object\AbstractObject|Collection * * @throws \Edbizarro\LaravelFacebookAds\Exceptions\MissingEntityFormatter * @see https://developers.facebook.com/docs/marketing-api/reference/ad-account/campaigns */ public function all(array $fields, string $accountId) { return $this->format( (new AdAccount)->setId($accountId)->getCampaigns($fields) ); } }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/Entities/AdAccounts.php
src/Entities/AdAccounts.php
<?php namespace Edbizarro\LaravelFacebookAds\Entities; use FacebookAds\Object\AdAccount; use Illuminate\Support\Collection; use Edbizarro\LaravelFacebookAds\Traits\HasAccountUser; use Edbizarro\LaravelFacebookAds\Traits\AdAccountFormatter; /** * Class AdAccounts. */ class AdAccounts { use AdAccountFormatter, HasAccountUser; /** * List all user's ads accounts. * * @param array $fields * @param string $accountId * * @return Collection * * @throws \Edbizarro\LaravelFacebookAds\Exceptions\MissingEntityFormatter * @see https://developers.facebook.com/docs/marketing-api/reference/ad-account */ public function all(array $fields = [], $accountId = 'me'): Collection { return $this->format( $this->accountUser($accountId)->getAdAccounts($fields) ); } /** * @param array $fields * @param $accountId * * @return Collection * @throws \Edbizarro\LaravelFacebookAds\Exceptions\MissingEntityFormatter * @see https://developers.facebook.com/docs/marketing-api/reference/ad-account */ public function get(array $fields, $accountId) { return $this->format( (new AdAccount($accountId))->getSelf($fields) ); } }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/Entities/AbstractEntity.php
src/Entities/AbstractEntity.php
<?php namespace Edbizarro\LaravelFacebookAds\Entities; use FacebookAds\Object\AbstractObject; use Illuminate\Contracts\Support\Arrayable; /** * Class Entity. */ abstract class AbstractEntity implements Arrayable { /** * @var AbstractObject|array */ protected $response; public function __construct($class = []) { $this->response = $class; } public function rawResponse() { return $this->response; } /** * @param $name * @return mixed */ public function __get($name) { if (method_exists($this->response, 'get_data') && array_key_exists($name, $this->response->getData()) ) { return $this->response->getData()[$name]; } return $this->response->{$name}; } /** * Get the instance as an array. * * @return array */ public function toArray(): array { if (method_exists($this->response, 'get_data')) { return $this->response->getData(); } return (array) $this->response; } }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/Entities/InstagramAccounts.php
src/Entities/InstagramAccounts.php
<?php namespace Edbizarro\LaravelFacebookAds\Entities; use Illuminate\Support\Collection; use FacebookAds\Object\AdAccount as FbAdAccount; use Edbizarro\LaravelFacebookAds\Traits\AdAccountFormatter; /** * Class AdAccounts. */ class InstagramAccounts { use AdAccountFormatter; /** * List all instagram accounts. * * @param array $fields * @param string $accountId * * @return Collection * * @throws \Edbizarro\LaravelFacebookAds\Exceptions\MissingEntityFormatter * @see https://developers.facebook.com/docs/marketing-api/guides/instagramads */ public function all(array $fields, string $accountId): Collection { return $this->format( (new FbAdAccount)->setId($accountId)->getInstagramAccounts($fields) ); } /** * @param array $fields * @param $accountId * * @return Collection * * @throws \Edbizarro\LaravelFacebookAds\Exceptions\MissingEntityFormatter * @see https://developers.facebook.com/docs/marketing-api/reference/ad-account */ public function get(array $fields, $accountId) { return $this->format( (new FbAdAccount($accountId))->getSelf($fields) ); } }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/Entities/AdAccount.php
src/Entities/AdAccount.php
<?php namespace Edbizarro\LaravelFacebookAds\Entities; use Illuminate\Support\Collection; use Edbizarro\LaravelFacebookAds\Traits\AdFormatter; /** * Class AdAccount. */ class AdAccount extends AbstractEntity { use AdFormatter; /** * Get the account ads. * * @param array $fields * * @return Collection * * @see https://developers.facebook.com/docs/marketing-api/reference/adgroup#Reading * @throws \Edbizarro\LaravelFacebookAds\Exceptions\MissingEntityFormatter */ public function ads(array $fields = []): Collection { return $this->format( $this->response->getAds($fields) ); } }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/Facades/FacebookAds.php
src/Facades/FacebookAds.php
<?php namespace Edbizarro\LaravelFacebookAds\Facades; use Illuminate\Support\Facades\Facade; class FacebookAds extends Facade { protected static function getFacadeAccessor() { return 'facebook-ads'; } }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/src/Providers/LaravelFacebookServiceProvider.php
src/Providers/LaravelFacebookServiceProvider.php
<?php namespace Edbizarro\LaravelFacebookAds\Providers; use Illuminate\Support\Str; use Illuminate\Support\ServiceProvider; use Edbizarro\LaravelFacebookAds\FacebookAds; use Edbizarro\LaravelFacebookAds\Contracts\LaravelFacebookAdsContract; /** * Class LaravelFacebookServiceProvider. */ class LaravelFacebookServiceProvider extends ServiceProvider { /** * Bootstrap the application services. */ public function boot(): void { $this->registerPublishing(); if ($this->isLumen()) { $this->app->configure('facebook-ads'); } } /** * Register the application services. */ public function register() { $this->mergeConfigFrom( __DIR__.'/../../config/facebook-ads.php', 'facebook-ads' ); $this->app->bind(LaravelFacebookAdsContract::class, function () { return $this->createInstance(); }); $this->app->singleton('facebook-ads', function () { return $this->createInstance(); }); } protected function registerPublishing(): void { if ($this->isLumen() === false) { $this->publishes([ __DIR__.'/../../config/facebook-ads.php' => config_path('facebook-ads.php'), ], 'facebook-ads'); } if ($this->app->runningInConsole()) { $this->publishes([ __DIR__.'/../../config/facebook-ads.php' => config_path('facebook-ads.php'), ], 'facebook-ads'); } } /** * @return FacebookAds */ protected function createInstance() { return new FacebookAds; } /** * Get the services provided by the provider. * * @return array */ public function provides(): array { return ['facebook-ads']; } /** * @return bool */ private function isLumen(): bool { return Str::contains($this->app->version(), 'Lumen'); } }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/tests/LaravelFacebookAds/BaseTest.php
tests/LaravelFacebookAds/BaseTest.php
<?php namespace LaravelFacebookAds\Tests; use Mockery as m; use Orchestra\Testbench\TestCase; use Edbizarro\LaravelFacebookAds\Providers\LaravelFacebookServiceProvider; /** * Class BaseTest. */ class BaseTest extends TestCase { public function tearDown(): void { parent::tearDown(); m::close(); } public function setUp(): void { parent::setUp(); } protected function getPackageProviders($app) { return [LaravelFacebookServiceProvider::class]; } }
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
edbizarro/laravel-facebook-ads
https://github.com/edbizarro/laravel-facebook-ads/blob/dc29ed4994598c6aa532ac14ce0d6444783b557f/config/facebook-ads.php
config/facebook-ads.php
<?php return [ /* |-------------------------------------------------------------------------- | Laravel Facebook Ads config |-------------------------------------------------------------------------- */ 'app_id' => env('FB_ADS_APP_ID'), 'app_secret' => env('FB_ADS_APP_SECRET'), ];
php
MIT
dc29ed4994598c6aa532ac14ce0d6444783b557f
2026-01-05T05:07:06.990899Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/.php-cs-fixer.php
.php-cs-fixer.php
<?php declare(strict_types=1); $finder = PhpCsFixer\Finder::create() ->files() ->name('*.php') ->in(__DIR__ . '/src') ->in(__DIR__ . '/tests') ; /** @var array $config */ $config = require __DIR__ . '/vendor/chubbyphp/chubbyphp-dev-helper/phpcs.php'; return (new PhpCsFixer\Config) ->setUnsupportedPhpVersionAllowed(true) ->setIndent($config['indent']) ->setLineEnding($config['lineEnding']) ->setRules($config['rules']) ->setRiskyAllowed($config['riskyAllowed']) ->setFinder($finder) ;
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Application.php
src/Application.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework; use Chubbyphp\Framework\Emitter\Emitter; use Chubbyphp\Framework\Emitter\EmitterInterface; use Chubbyphp\Framework\Middleware\PipeMiddleware; use Chubbyphp\Framework\RequestHandler\RouteRequestHandler; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; final class Application implements RequestHandlerInterface { private readonly PipeMiddleware $pipeMiddleware; /** * @param array<MiddlewareInterface> $middlewares */ public function __construct( array $middlewares, private readonly RequestHandlerInterface $routeRequestHandler = new RouteRequestHandler(), private readonly EmitterInterface $emitter = new Emitter() ) { $this->pipeMiddleware = new PipeMiddleware($middlewares); } public function __invoke(ServerRequestInterface $request): ResponseInterface { return $this->handle($request); } public function handle(ServerRequestInterface $request): ResponseInterface { return $this->pipeMiddleware->process($request, $this->routeRequestHandler); } public function emit(ResponseInterface $response): void { $this->emitter->emit($response); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/RequestHandler/LazyRequestHandler.php
src/RequestHandler/LazyRequestHandler.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\RequestHandler; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; final class LazyRequestHandler implements RequestHandlerInterface { public function __construct(private readonly ContainerInterface $container, private readonly string $id) {} public function handle(ServerRequestInterface $request): ResponseInterface { $requestHandler = $this->container->get($this->id); if (!$requestHandler instanceof RequestHandlerInterface) { throw new \TypeError( \sprintf( '%s() expects service with id "%s" to be %s, %s given', __METHOD__, $this->id, RequestHandlerInterface::class, get_debug_type($requestHandler) ) ); } return $requestHandler->handle($request); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/RequestHandler/CallbackRequestHandler.php
src/RequestHandler/CallbackRequestHandler.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\RequestHandler; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; final class CallbackRequestHandler implements RequestHandlerInterface { /** * @var callable */ private readonly mixed $callback; public function __construct(callable $callback) { $this->callback = $callback; } public function handle(ServerRequestInterface $request): ResponseInterface { return ($this->callback)($request); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/RequestHandler/SlimCallbackRequestHandler.php
src/RequestHandler/SlimCallbackRequestHandler.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\RequestHandler; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; final class SlimCallbackRequestHandler implements RequestHandlerInterface { private const string ATTRIBUTE_RESPONSE = 'response'; /** * @var callable */ private readonly mixed $slimCallable; public function __construct(callable $slimCallable, private readonly ResponseFactoryInterface $responseFactory) { $this->slimCallable = $slimCallable; } public function handle(ServerRequestInterface $request): ResponseInterface { return ($this->slimCallable)($request, $this->getResponse($request), $request->getAttributes()); } private function getResponse(ServerRequestInterface $request): ResponseInterface { /** @var null|ResponseInterface $response */ $response = $request->getAttribute(self::ATTRIBUTE_RESPONSE); if (null !== $response) { return $response; } return $this->responseFactory->createResponse(); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/RequestHandler/RouteRequestHandler.php
src/RequestHandler/RouteRequestHandler.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\RequestHandler; use Chubbyphp\Framework\Middleware\PipeMiddleware; use Chubbyphp\Framework\Router\Exceptions\MissingRouteAttributeOnRequestException; use Chubbyphp\Framework\Router\RouteInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; final class RouteRequestHandler implements RequestHandlerInterface { public function handle(ServerRequestInterface $request): ResponseInterface { $route = $request->getAttribute('route'); if (!$route instanceof RouteInterface) { throw MissingRouteAttributeOnRequestException::create($route); } return (new PipeMiddleware($route->getMiddlewares()))->process($request, $route->getRequestHandler()); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/RequestHandler/SlimLazyRequestHandler.php
src/RequestHandler/SlimLazyRequestHandler.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\RequestHandler; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; final class SlimLazyRequestHandler implements RequestHandlerInterface { public function __construct( private readonly ContainerInterface $container, private readonly string $id, private readonly ResponseFactoryInterface $responseFactory ) {} public function handle(ServerRequestInterface $request): ResponseInterface { $requestHandler = $this->container->get($this->id); if (!\is_callable($requestHandler)) { throw new \TypeError( \sprintf( '%s() expects service with id "%s" to be %s, %s given', __METHOD__, $this->id, 'callable', get_debug_type($requestHandler) ) ); } return (new SlimCallbackRequestHandler($requestHandler, $this->responseFactory))->handle($request); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Router/GroupInterface.php
src/Router/GroupInterface.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Router; interface GroupInterface { /** * @return array<RouteInterface> */ public function getRoutes(): array; }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Router/RoutesByNameInterface.php
src/Router/RoutesByNameInterface.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Router; interface RoutesByNameInterface { /** * @return array<string, RouteInterface> */ public function getRoutesByName(): array; }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Router/Route.php
src/Router/Route.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Router; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; final class Route implements RouteInterface { /** * @var array<string, string> */ private array $attributes = []; /** * @param array<MiddlewareInterface> $middlewares * @param array<string, mixed> $pathOptions */ private function __construct( private readonly string $method, private readonly string $path, private readonly string $name, private readonly RequestHandlerInterface $requestHandler, private readonly array $middlewares = [], private readonly array $pathOptions = [] ) {} /** * @param array<MiddlewareInterface> $middlewares * @param array<string, mixed> $pathOptions */ public static function create( string $method, string $path, string $name, RequestHandlerInterface $requestHandler, array $middlewares = [], array $pathOptions = [] ): self { return new self($method, $path, $name, $requestHandler, $middlewares, $pathOptions); } /** * @param array<MiddlewareInterface> $middlewares * @param array<string, mixed> $pathOptions */ public static function delete( string $path, string $name, RequestHandlerInterface $requestHandler, array $middlewares = [], array $pathOptions = [] ): self { return new self('DELETE', $path, $name, $requestHandler, $middlewares, $pathOptions); } /** * @param array<MiddlewareInterface> $middlewares * @param array<string, mixed> $pathOptions */ public static function get( string $path, string $name, RequestHandlerInterface $requestHandler, array $middlewares = [], array $pathOptions = [] ): self { return new self('GET', $path, $name, $requestHandler, $middlewares, $pathOptions); } /** * @param array<MiddlewareInterface> $middlewares * @param array<string, mixed> $pathOptions */ public static function head( string $path, string $name, RequestHandlerInterface $requestHandler, array $middlewares = [], array $pathOptions = [] ): self { return new self('HEAD', $path, $name, $requestHandler, $middlewares, $pathOptions); } /** * @param array<MiddlewareInterface> $middlewares * @param array<string, mixed> $pathOptions */ public static function options( string $path, string $name, RequestHandlerInterface $requestHandler, array $middlewares = [], array $pathOptions = [] ): self { return new self('OPTIONS', $path, $name, $requestHandler, $middlewares, $pathOptions); } /** * @param array<MiddlewareInterface> $middlewares * @param array<string, mixed> $pathOptions */ public static function patch( string $path, string $name, RequestHandlerInterface $requestHandler, array $middlewares = [], array $pathOptions = [] ): self { return new self('PATCH', $path, $name, $requestHandler, $middlewares, $pathOptions); } /** * @param array<MiddlewareInterface> $middlewares * @param array<string, mixed> $pathOptions */ public static function post( string $path, string $name, RequestHandlerInterface $requestHandler, array $middlewares = [], array $pathOptions = [] ): self { return new self('POST', $path, $name, $requestHandler, $middlewares, $pathOptions); } /** * @param array<MiddlewareInterface> $middlewares * @param array<string, mixed> $pathOptions */ public static function put( string $path, string $name, RequestHandlerInterface $requestHandler, array $middlewares = [], array $pathOptions = [] ): self { return new self('PUT', $path, $name, $requestHandler, $middlewares, $pathOptions); } public function getName(): string { return $this->name; } public function getMethod(): string { return $this->method; } public function getPath(): string { return $this->path; } /** * @return array<string, mixed> */ public function getPathOptions(): array { return $this->pathOptions; } /** * @return array<MiddlewareInterface> */ public function getMiddlewares(): array { return $this->middlewares; } public function getRequestHandler(): RequestHandlerInterface { return $this->requestHandler; } /** * @param array<string, string> $attributes */ public function withAttributes(array $attributes): RouteInterface { $clone = clone $this; $clone->attributes = $attributes; return $clone; } /** * @return array<string, string> */ public function getAttributes(): array { return $this->attributes; } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Router/RouteInterface.php
src/Router/RouteInterface.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Router; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; interface RouteInterface { public function getName(): string; public function getMethod(): string; public function getPath(): string; /** * @return array<string, mixed> */ public function getPathOptions(): array; /** * @return array<MiddlewareInterface> */ public function getMiddlewares(): array; public function getRequestHandler(): RequestHandlerInterface; /** * @param array<string, string> $attributes */ public function withAttributes(array $attributes): self; /** * @return array<string, string> */ public function getAttributes(): array; }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Router/RoutesByName.php
src/Router/RoutesByName.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Router; final class RoutesByName implements RoutesByNameInterface { /** * @var array<string, RouteInterface> */ private readonly array $routesByName; /** * @param array<RouteInterface> $routes */ public function __construct(array $routes) { $routesByName = []; foreach ($routes as $route) { $routesByName[$route->getName()] = $route; } $this->routesByName = $routesByName; } /** * @return array<string, RouteInterface> */ public function getRoutesByName(): array { return $this->routesByName; } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Router/UrlGeneratorInterface.php
src/Router/UrlGeneratorInterface.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Router; use Chubbyphp\Framework\Router\Exceptions\RouterException; use Psr\Http\Message\ServerRequestInterface; interface UrlGeneratorInterface { /** * @param array<string, string> $attributes * @param array<string, mixed> $queryParams * * @throws RouterException */ public function generateUrl( ServerRequestInterface $request, string $name, array $attributes = [], array $queryParams = [], ): string; /** * @param array<string, string> $attributes * @param array<string, mixed> $queryParams * * @throws RouterException */ public function generatePath(string $name, array $attributes = [], array $queryParams = []): string; }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Router/RouteMatcherInterface.php
src/Router/RouteMatcherInterface.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Router; use Chubbyphp\Framework\Router\Exceptions\RouterException; use Chubbyphp\HttpException\HttpException; use Psr\Http\Message\ServerRequestInterface; interface RouteMatcherInterface { /** * @throws HttpException|RouterException */ public function match(ServerRequestInterface $request): RouteInterface; }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Router/Group.php
src/Router/Group.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Router; use Psr\Http\Server\MiddlewareInterface; final class Group implements GroupInterface { /** * @param array<GroupInterface|RouteInterface> $children * @param array<MiddlewareInterface> $middlewares * @param array<string, mixed> $pathOptions */ private function __construct( private readonly string $path, private readonly array $children = [], private readonly array $middlewares = [], private readonly array $pathOptions = [] ) {} /** * @param array<GroupInterface|RouteInterface> $children * @param array<MiddlewareInterface> $middlewares * @param array<string, mixed> $pathOptions */ public static function create( string $path, array $children = [], array $middlewares = [], array $pathOptions = [] ): self { return new self($path, $children, $middlewares, $pathOptions); } /** * @return array<RouteInterface> */ public function getRoutes(): array { $routes = []; foreach ($this->children as $child) { if ($child instanceof GroupInterface) { foreach ($child->getRoutes() as $route) { $routes[] = $this->createRoute($route); } } else { $routes[] = $this->createRoute($child); } } return $routes; } private function createRoute(RouteInterface $route): RouteInterface { return Route::create( $route->getMethod(), $this->path.$route->getPath(), $route->getName(), $route->getRequestHandler(), array_merge($this->middlewares, $route->getMiddlewares()), array_merge_recursive($this->pathOptions, $route->getPathOptions()) ); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Router/Exceptions/MissingRouteAttributeOnRequestException.php
src/Router/Exceptions/MissingRouteAttributeOnRequestException.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Router\Exceptions; use Chubbyphp\Framework\Middleware\RouteMatcherMiddleware; final class MissingRouteAttributeOnRequestException extends RouterException { private function __construct(string $message, int $code, ?\Throwable $previous = null) { parent::__construct($message, $code, $previous); } public static function create(mixed $route): self { return new self( \sprintf( 'Request attribute "route" missing or wrong type "%s", please add the "%s" middleware', get_debug_type($route), RouteMatcherMiddleware::class ), 1 ); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Router/Exceptions/MissingRouteByNameException.php
src/Router/Exceptions/MissingRouteByNameException.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Router\Exceptions; final class MissingRouteByNameException extends RouterException { private function __construct(string $message, int $code, ?\Throwable $previous = null) { parent::__construct($message, $code, $previous); } public static function create(string $name): self { return new self(\sprintf('Missing route: "%s"', $name), 2); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Router/Exceptions/RouterException.php
src/Router/Exceptions/RouterException.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Router\Exceptions; abstract class RouterException extends \LogicException {}
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Router/Exceptions/RouteGenerationException.php
src/Router/Exceptions/RouteGenerationException.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Router\Exceptions; final class RouteGenerationException extends RouterException { private function __construct(string $message, int $code, ?\Throwable $previous = null) { parent::__construct($message, $code, $previous); } /** * @param array<string, string> $attributes */ public static function create(string $name, string $path, array $attributes, ?\Throwable $previous = null): self { return new self( \sprintf( 'Route generation for route "%s" with path "%s" with attributes "%s" failed.%s', $name, $path, json_encode([] !== $attributes ? $attributes : new \stdClass(), JSON_THROW_ON_ERROR), $previous instanceof \Throwable ? ' '.$previous->getMessage() : '', ), 3, $previous ); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Middleware/MiddlewareRequestHandler.php
src/Middleware/MiddlewareRequestHandler.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Middleware; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; final class MiddlewareRequestHandler implements RequestHandlerInterface { public function __construct(private readonly MiddlewareInterface $middleware, private readonly RequestHandlerInterface $handler) {} public function handle(ServerRequestInterface $request): ResponseInterface { return $this->middleware->process($request, $this->handler); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Middleware/PipeMiddleware.php
src/Middleware/PipeMiddleware.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Middleware; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; final class PipeMiddleware implements MiddlewareInterface { /** * @var array<MiddlewareInterface> */ private readonly array $middlewares; /** * @param array<MiddlewareInterface> $middlewares */ public function __construct(array $middlewares) { $this->middlewares = array_reverse($middlewares); } public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $reducedHandler = $handler; foreach ($this->middlewares as $middleware) { $reducedHandler = new MiddlewareRequestHandler($middleware, $reducedHandler); } return $reducedHandler->handle($request); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Middleware/LazyMiddleware.php
src/Middleware/LazyMiddleware.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Middleware; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; final class LazyMiddleware implements MiddlewareInterface { public function __construct(private readonly ContainerInterface $container, private readonly string $id) {} public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $middleware = $this->container->get($this->id); if (!$middleware instanceof MiddlewareInterface) { throw new \TypeError( \sprintf( '%s() expects service with id "%s" to be %s, %s given', __METHOD__, $this->id, MiddlewareInterface::class, get_debug_type($middleware) ) ); } return $middleware->process($request, $handler); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Middleware/SlimLazyMiddleware.php
src/Middleware/SlimLazyMiddleware.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Middleware; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; final class SlimLazyMiddleware implements MiddlewareInterface { public function __construct( private readonly ContainerInterface $container, private readonly string $id, private readonly ResponseFactoryInterface $responseFactory ) {} public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $middleware = $this->container->get($this->id); if (!\is_callable($middleware)) { throw new \TypeError( \sprintf( '%s() expects service with id "%s" to be %s, %s given', __METHOD__, $this->id, 'callable', get_debug_type($middleware) ) ); } return (new SlimCallbackMiddleware($middleware, $this->responseFactory))->process($request, $handler); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Middleware/RouteMatcherMiddleware.php
src/Middleware/RouteMatcherMiddleware.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Middleware; use Chubbyphp\Framework\Router\RouteMatcherInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; final class RouteMatcherMiddleware implements MiddlewareInterface { public function __construct(private readonly RouteMatcherInterface $routeMatcher) {} public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $route = $this->routeMatcher->match($request); $request = $request->withAttribute('route', $route); foreach ($route->getAttributes() as $attribute => $value) { $request = $request->withAttribute($attribute, $value); } return $handler->handle($request); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Middleware/SlimCallbackMiddleware.php
src/Middleware/SlimCallbackMiddleware.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Middleware; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; final class SlimCallbackMiddleware implements MiddlewareInterface { private const string ATTRIBUTE_RESPONSE = 'response'; /** * @var callable */ private readonly mixed $slimCallable; public function __construct(callable $slimCallable, private readonly ResponseFactoryInterface $responseFactory) { $this->slimCallable = $slimCallable; } public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { return ($this->slimCallable)( $request, $this->getResponse($request), static fn (ServerRequestInterface $request, ResponseInterface $response) => $handler->handle( $request->withAttribute(self::ATTRIBUTE_RESPONSE, $response) ) ); } private function getResponse(ServerRequestInterface $request): ResponseInterface { /** @var null|ResponseInterface $response */ $response = $request->getAttribute(self::ATTRIBUTE_RESPONSE); if (null !== $response) { return $response; } return $this->responseFactory->createResponse(); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Middleware/CallbackMiddleware.php
src/Middleware/CallbackMiddleware.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Middleware; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; final class CallbackMiddleware implements MiddlewareInterface { /** * @var callable */ private readonly mixed $callback; public function __construct(callable $callback) { $this->callback = $callback; } public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { return ($this->callback)($request, $handler); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Middleware/ExceptionMiddleware.php
src/Middleware/ExceptionMiddleware.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Middleware; use Chubbyphp\HttpException\HttpException; use Chubbyphp\HttpException\HttpExceptionInterface; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; use Psr\Log\LoggerInterface; use Psr\Log\NullLogger; final class ExceptionMiddleware implements MiddlewareInterface { private const string HTML = <<<'EOT' <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>__TITLE__</title> <style> html { font-family: Helvetica, Arial, Verdana, sans-serif; line-height: 1.5; tab-size: 4; } body { margin: 0; } * { border-width: 0; border-style: solid; } .container { width: 100% } .mx-auto { margin-left: auto; margin-right: auto; } .mt-12 { margin-top: 3rem; } .mb-12 { margin-bottom: 3rem; } .text-gray-400 { --tw-text-opacity: 1; color: rgba(156, 163, 175, var(--tw-text-opacity)); } .text-5xl { font-size: 3rem; line-height: 1; } .text-right { text-align: right; } .tracking-tighter { letter-spacing: -.05em; } .flex { display: flex; } .flex-row { flex-direction: row; } .basis-2\/12 { flex-basis: 16.666667%; } .basis-10\/12 { flex-basis: 83.333333%; } .space-x-8>:not([hidden])~:not([hidden]) { --tw-space-x-reverse: 0; margin-right: calc(2rem * var(--tw-space-x-reverse)); margin-left: calc(2rem * calc(1 - var(--tw-space-x-reverse))) } .gap-x-4 { column-gap: 1rem; } .gap-y-1\.5 { row-gap: 0.375rem; } .grid-cols-1 { grid-template-columns: repeat(1, minmax(0, 1fr)); } .grid { display: grid; } @media (min-width:640px) { .container { max-width: 640px } } @media (min-width:768px) { .container { max-width: 768px } .md\:grid-cols-8 { grid-template-columns: repeat(8, minmax(0, 1fr)); } .md\:col-span-7 { grid-column: span 7/span 7 } } @media (min-width:1024px) { .container { max-width: 1024px } } @media (min-width:1280px) { .container { max-width: 1280px } } @media (min-width:1536px) { .container { max-width: 1536px } } </style> </head> <body> <div class="container mx-auto tracking-tighter mt-12"> <div class="flex flex-row space-x-8"> <div class="basis-1/12 text-5xl text-gray-400 text-right">__STATUS__</div> <div class="basis-11/12"> <span class="text-5xl">__TITLE__</span>__BODY__ </div> </div> </div> </body> </html> EOT; private readonly LoggerInterface $logger; public function __construct( private readonly ResponseFactoryInterface $responseFactory, private readonly bool $debug = false, ?LoggerInterface $logger = null ) { $this->logger = $logger ?? new NullLogger(); } public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { try { return $handler->handle($request); } catch (\Throwable $exception) { return $this->handleException($exception); } } private function handleException(\Throwable $exception): ResponseInterface { $httpException = $this->exceptionToHttpException($exception); $data = $httpException->jsonSerialize(); $logMethod = $data['status'] < 500 ? 'info' : 'error'; $exceptions = $this->toExceptionsArray($httpException); $this->logger->{$logMethod}('Http Exception', [ 'data' => $data, 'exceptions' => $exceptions, ]); $lines = [ ...(isset($data['detail']) ? ['<p>'.$data['detail'].'</p>'] : []), ...(isset($data['instance']) ? ['<p>'.$data['instance'].'</p>'] : []), ...($this->debug ? [$this->addDebugToBody($exceptions)] : []), ]; $response = $this->responseFactory->createResponse($data['status']); $response = $response->withHeader('Content-Type', 'text/html'); $response->getBody()->write( str_replace( '__STATUS__', (string) $data['status'], str_replace( '__TITLE__', $data['title'], str_replace( '__BODY__', implode('', $lines), self::HTML ) ) ) ); return $response; } private function exceptionToHttpException(\Throwable $exception): HttpExceptionInterface { if ($exception instanceof HttpExceptionInterface) { return $exception; } return HttpException::createInternalServerError([ 'detail' => 'A website error has occurred. Sorry for the temporary inconvenience.', ], $exception); } /** * @return array<int, array<string, mixed>> */ private function toExceptionsArray(\Throwable $exception): array { $exceptions = []; do { $exceptions[] = [ 'class' => $exception::class, 'message' => $exception->getMessage(), 'code' => $exception->getCode(), 'file' => $exception->getFile(), 'line' => $exception->getLine(), 'trace' => $exception->getTraceAsString(), ]; } while ($exception = $exception->getPrevious()); return $exceptions; } /** * @param array<array<string, string>> $exceptionsData */ private function addDebugToBody(array $exceptionsData): string { $body = '<div class="mt-12">'; foreach ($exceptionsData as $exceptionData) { $body .= '<div class="mb-12 grid grid-cols-1 md:grid-cols-8 gap-4">'; foreach ($exceptionData as $key => $value) { $body .= \sprintf( '<div><strong>%s</strong></div><div class="md:col-span-7">%s</div>', ucfirst($key), nl2br((string) $value) ); } $body .= '</div>'; } $body .= '</div>'; return $body; } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Emitter/EmitterInterface.php
src/Emitter/EmitterInterface.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Emitter; use Psr\Http\Message\ResponseInterface; interface EmitterInterface { public function emit(ResponseInterface $response): void; }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/src/Emitter/Emitter.php
src/Emitter/Emitter.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Emitter; use Psr\Http\Message\ResponseInterface; final class Emitter implements EmitterInterface { public function emit(ResponseInterface $response): void { $statusCode = $response->getStatusCode(); header( \sprintf( 'HTTP/%s %s %s', $response->getProtocolVersion(), $statusCode, $response->getReasonPhrase() ), true, $statusCode ); foreach ($response->getHeaders() as $name => $values) { foreach ($values as $value) { header(\sprintf('%s: %s', $name, $value), false); } } $body = $response->getBody(); if ($body->isSeekable()) { $body->rewind(); } while (!$body->eof()) { echo $body->read(256); } } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Integration/RouteMatcherLessTest.php
tests/Integration/RouteMatcherLessTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Integration; use Chubbyphp\Framework\Application; use Chubbyphp\Framework\Middleware\ExceptionMiddleware; use Chubbyphp\Framework\Router\Exceptions\RouterException; use Http\Factory\Guzzle\ResponseFactory as GuzzleResponseFactory; use Http\Factory\Guzzle\ServerRequestFactory as GuzzleServerRequestFactory; use Laminas\Diactoros\ResponseFactory as LaminasResponseFactory; use Laminas\Diactoros\ServerRequestFactory as LaminasServerRequestFactory; use Nyholm\Psr7\Factory\Psr17Factory as NyholmResponseFactory; use Nyholm\Psr7\Factory\Psr17Factory as NyholmServerRequestFactory; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ServerRequestFactoryInterface; use Slim\Psr7\Factory\ResponseFactory as SlimResponseFactory; use Slim\Psr7\Factory\ServerRequestFactory as SlimServerRequestFactory; use Sunrise\Http\Message\ResponseFactory as SunriseResponseFactory; use Sunrise\Http\Message\ServerRequestFactory as SunriseServerRequestFactory; /** * @coversNothing * * @internal */ final class RouteMatcherLessTest extends TestCase { #[DataProvider('providePsr7Implementations')] public function testMissingRouteMatcherMiddleware( ResponseFactoryInterface $responseFactory, ServerRequestFactoryInterface $serverRequestFactory ): void { $app = new Application([ new ExceptionMiddleware($responseFactory, true), ]); $request = $serverRequestFactory->createServerRequest('GET', '/hello/test'); $response = $app->handle($request); self::assertSame(500, $response->getStatusCode()); $body = (string) $response->getBody(); self::assertStringContainsString( 'Request attribute "route" missing or wrong type "null"' .', please add the "Chubbyphp\Framework\Middleware\RouteMatcherMiddleware" middleware', $body ); } #[DataProvider('providePsr7Implementations')] public function testMissingRouteMatcherMiddlewareWithoutExceptionMiddleware( ResponseFactoryInterface $responseFactory, ServerRequestFactoryInterface $serverRequestFactory ): void { $this->expectException(RouterException::class); $this->expectExceptionMessage( 'Request attribute "route" missing or wrong type "null"' .', please add the "Chubbyphp\Framework\Middleware\RouteMatcherMiddleware" middleware' ); $app = new Application([]); $request = $serverRequestFactory->createServerRequest('GET', '/hello/test'); $app->handle($request); } public static function providePsr7Implementations(): iterable { return [ 'guzzle' => [ 'responseFactory' => new GuzzleResponseFactory(), 'serverRequestFactory' => new GuzzleServerRequestFactory(), ], 'nyholm' => [ 'responseFactory' => new NyholmResponseFactory(), 'serverRequestFactory' => new NyholmServerRequestFactory(), ], 'slim' => [ 'responseFactory' => new SlimResponseFactory(), 'serverRequestFactory' => new SlimServerRequestFactory(), ], 'sunrise' => [ 'responseFactory' => new SunriseResponseFactory(), 'serverRequestFactory' => new SunriseServerRequestFactory(), ], 'zend' => [ 'responseFactory' => new LaminasResponseFactory(), 'serverRequestFactory' => new LaminasServerRequestFactory(), ], ]; } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Integration/DocumentationTest.php
tests/Integration/DocumentationTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Integration; use PHPUnit\Framework\TestCase; /** * @internal * * @coversNothing */ final class DocumentationTest extends TestCase { public function testDocumentation(): void { $documentationFiles = $this->getDocumentationFiles(realpath(__DIR__.'/../../doc')); $documentationFiles[] = realpath(__DIR__.'/../../README.md'); $phpBlockCount = 0; foreach ($documentationFiles as $documentationFile) { foreach ($this->getPhpBlocks($documentationFile) as $phpBlock) { try { ++$phpBlockCount; \PhpToken::tokenize($phpBlock, TOKEN_PARSE); } catch (\Error $e) { self::fail( \sprintf( 'Cannot parse the following code in file "%s", error "%s" : "%s"', $documentationFile, $e->getMessage(), $phpBlock ) ); } } } self::assertSame(41, $phpBlockCount); } private function getDocumentationFiles(string $path): array { $files = []; foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($path)) as $file) { $file = (string) $file; if ('md' === pathinfo($file, PATHINFO_EXTENSION)) { $files[] = $file; } } sort($files); return $files; } private function getPhpBlocks(string $path): array { $blocks = []; $blockIndex = 0; $isBlock = false; foreach (explode(PHP_EOL, file_get_contents($path)) as $line) { if ('```php' === $line) { $isBlock = true; $blocks[$blockIndex] = ''; } elseif ('```' === $line && $isBlock) { $isBlock = false; ++$blockIndex; } elseif ($isBlock) { $blocks[$blockIndex] .= $line.PHP_EOL; } } return $blocks; } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Integration/PipeMiddlewareTest.php
tests/Integration/PipeMiddlewareTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Integration; use Chubbyphp\Framework\Middleware\CallbackMiddleware; use Chubbyphp\Framework\Middleware\PipeMiddleware; use Chubbyphp\Framework\Middleware\SlimCallbackMiddleware; use Chubbyphp\Framework\RequestHandler\CallbackRequestHandler; use Chubbyphp\Framework\RequestHandler\SlimCallbackRequestHandler; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; use Slim\Psr7\Factory\ResponseFactory as SlimResponseFactory; use Sunrise\Http\Message\ServerRequestFactory as SunriseServerRequestFactory; /** * @coversNothing * * @internal */ final class PipeMiddlewareTest extends TestCase { public function testCallback(): void { $responseFactory = new SlimResponseFactory(); $serverRequestFactory = new SunriseServerRequestFactory(); $pipeMiddleware = new PipeMiddleware([ new CallbackMiddleware( static fn (ServerRequestInterface $request, RequestHandlerInterface $handler) => $handler->handle($request->withHeader('req1', 'value1')) ), new CallbackMiddleware( static fn (ServerRequestInterface $request, RequestHandlerInterface $handler) => $handler->handle($request->withHeader('req2', 'value2')) ), new CallbackMiddleware( static fn (ServerRequestInterface $request, RequestHandlerInterface $handler) => $handler->handle($request->withHeader('req3', 'value3')) ), new CallbackMiddleware( static fn (ServerRequestInterface $request, RequestHandlerInterface $handler) => $handler->handle($request->withAttribute('req', 'value')) ), ]); $pipeMiddleware->process( $serverRequestFactory->createServerRequest('GET', '/hello/test'), new CallbackRequestHandler( static function (ServerRequestInterface $request) use ($responseFactory) { self::assertSame([ 'req1' => ['value1'], 'req2' => ['value2'], 'req3' => ['value3'], ], $request->getHeaders()); return $responseFactory->createResponse(); } ), ); } public function testSlim(): void { $responseFactory = new SlimResponseFactory(); $serverRequestFactory = new SunriseServerRequestFactory(); $pipeMiddleware = new PipeMiddleware([ new SlimCallbackMiddleware( static fn (ServerRequestInterface $req, ResponseInterface $res, callable $next) => $next($req->withHeader('req1', 'value1'), $res->withHeader('res1', 'value1')), $responseFactory ), new SlimCallbackMiddleware( static fn (ServerRequestInterface $req, ResponseInterface $res, callable $next) => $next($req->withHeader('req2', 'value2'), $res->withHeader('res2', 'value2')), $responseFactory ), new SlimCallbackMiddleware( static fn (ServerRequestInterface $req, ResponseInterface $res, callable $next) => $next($req->withHeader('req3', 'value3'), $res->withHeader('res3', 'value3')), $responseFactory ), new SlimCallbackMiddleware( static fn (ServerRequestInterface $req, ResponseInterface $res, callable $next) => $next($req->withAttribute('req', 'value'), $res), $responseFactory ), ]); $pipeMiddleware->process( $serverRequestFactory->createServerRequest('GET', '/hello/test'), new SlimCallbackRequestHandler( static function (ServerRequestInterface $req, ResponseInterface $res, array $args) { self::assertSame([ 'req1' => ['value1'], 'req2' => ['value2'], 'req3' => ['value3'], ], $req->getHeaders()); self::assertSame([ 'res1' => ['value1'], 'res2' => ['value2'], 'res3' => ['value3'], ], $res->getHeaders()); self::assertSame(['response', 'req'], array_keys($args)); self::assertSame('value', $args['req']); return $res; }, $responseFactory ), ); } public function testCallbackSlimMixed(): void { $responseFactory = new SlimResponseFactory(); $serverRequestFactory = new SunriseServerRequestFactory(); $pipeMiddleware = new PipeMiddleware([ new CallbackMiddleware( static fn (ServerRequestInterface $request, RequestHandlerInterface $handler) => $handler->handle($request->withHeader('req1', 'value1')) ), new SlimCallbackMiddleware( static fn (ServerRequestInterface $req, ResponseInterface $res, callable $next) => $next($req->withHeader('req2', 'value2'), $res->withHeader('res2', 'value2')), $responseFactory ), new CallbackMiddleware( static fn (ServerRequestInterface $request, RequestHandlerInterface $handler) => $handler->handle($request->withHeader('req3', 'value3')) ), new SlimCallbackMiddleware( static fn (ServerRequestInterface $req, ResponseInterface $res, callable $next) => $next($req->withAttribute('req', 'value'), $res), $responseFactory ), ]); $pipeMiddleware->process( $serverRequestFactory->createServerRequest('GET', '/hello/test'), new SlimCallbackRequestHandler( static function (ServerRequestInterface $req, ResponseInterface $res, array $args) { self::assertSame([ 'req1' => ['value1'], 'req2' => ['value2'], 'req3' => ['value3'], ], $req->getHeaders()); self::assertSame([ 'res2' => ['value2'], ], $res->getHeaders()); self::assertSame(['response', 'req'], array_keys($args)); self::assertSame('value', $args['req']); return $res; }, $responseFactory ), ); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Unit/ApplicationTest.php
tests/Unit/ApplicationTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Unit; use Chubbyphp\Framework\Application; use Chubbyphp\Framework\Emitter\EmitterInterface; use Chubbyphp\Framework\Router\RouteInterface; use Chubbyphp\Mock\MockMethod\WithCallback; use Chubbyphp\Mock\MockMethod\WithReturn; use Chubbyphp\Mock\MockObjectBuilder; use PHPUnit\Framework\Attributes\DoesNotPerformAssertions; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; /** * @covers \Chubbyphp\Framework\Application * * @internal */ final class ApplicationTest extends TestCase { public function testInvoke(): void { $builder = new MockObjectBuilder(); /** @var MockObject|ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, []); /** @var MiddlewareInterface $middleware */ $middleware = $builder->create(MiddlewareInterface::class, [ new WithCallback( 'process', static fn ( ServerRequestInterface $request, RequestHandlerInterface $requestHandler ) => $requestHandler->handle($request) ), ]); /** @var MockObject|RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, [ new WithCallback( 'handle', static fn ( ServerRequestInterface $request, ) => $response, ), ]); /** @var MockObject|RouteInterface $route */ $route = $builder->create(RouteInterface::class, [ new WithReturn('getMiddlewares', [], [$middleware]), new WithReturn('getRequestHandler', [], $handler), ]); /** @var MockObject|ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, [ new WithReturn('getAttribute', ['route', null], $route), ]); /** @var MiddlewareInterface $routeIndependentMiddleware */ $routeIndependentMiddleware = $builder->create(MiddlewareInterface::class, [ new WithCallback( 'process', static fn ( ServerRequestInterface $request, RequestHandlerInterface $requestHandler ) => $requestHandler->handle($request) ), ]); $application = new Application([ $routeIndependentMiddleware, ]); self::assertSame($response, $application($request)); } public function testHandle(): void { $builder = new MockObjectBuilder(); /** @var MockObject|ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, []); /** @var MiddlewareInterface $middleware */ $middleware = $builder->create(MiddlewareInterface::class, [ new WithCallback( 'process', static fn ( ServerRequestInterface $request, RequestHandlerInterface $requestHandler ) => $requestHandler->handle($request) ), ]); /** @var MockObject|RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, [ new WithCallback( 'handle', static fn ( ServerRequestInterface $request, ) => $response, ), ]); /** @var MockObject|RouteInterface $route */ $route = $builder->create(RouteInterface::class, [ new WithReturn('getMiddlewares', [], [$middleware]), new WithReturn('getRequestHandler', [], $handler), ]); /** @var MockObject|ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, [ new WithReturn('getAttribute', ['route', null], $route), ]); /** @var MiddlewareInterface $routeIndependentMiddleware */ $routeIndependentMiddleware = $builder->create(MiddlewareInterface::class, [ new WithCallback( 'process', static fn ( ServerRequestInterface $request, RequestHandlerInterface $requestHandler ) => $requestHandler->handle($request) ), ]); $application = new Application([ $routeIndependentMiddleware, ]); self::assertSame($response, $application->handle($request)); } #[DoesNotPerformAssertions] public function testEmit(): void { $builder = new MockObjectBuilder(); /** @var MockObject|ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, []); /** @var RequestHandlerInterface $routeRequestHandler */ $routeRequestHandler = $builder->create(RequestHandlerInterface::class, []); /** @var EmitterInterface $emitter */ $emitter = $builder->create(EmitterInterface::class, [ new WithReturn('emit', [$response], null), ]); $application = new Application([], $routeRequestHandler, $emitter); $application->emit($response); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Unit/RequestHandler/LazyRequestHandlerTest.php
tests/Unit/RequestHandler/LazyRequestHandlerTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Unit\RequestHandler; use Chubbyphp\Framework\RequestHandler\LazyRequestHandler; use Chubbyphp\Mock\MockMethod\WithReturn; use Chubbyphp\Mock\MockObjectBuilder; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; /** * @covers \Chubbyphp\Framework\RequestHandler\LazyRequestHandler * * @internal */ final class LazyRequestHandlerTest extends TestCase { public function testHandle(): void { $builder = new MockObjectBuilder(); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, []); /** @var ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, []); /** @var RequestHandlerInterface $originalRequestHandler */ $originalRequestHandler = $builder->create(RequestHandlerInterface::class, [ new WithReturn('handle', [$request], $response), ]); /** @var ContainerInterface $container */ $container = $builder->create(ContainerInterface::class, [ new WithReturn('get', ['serviceName'], $originalRequestHandler), ]); $requestHandler = new LazyRequestHandler($container, 'serviceName'); self::assertSame($response, $requestHandler->handle($request)); } public function testHandleWithWrongObject(): void { $this->expectException(\TypeError::class); $this->expectExceptionMessage( 'Chubbyphp\Framework\RequestHandler\LazyRequestHandler::handle() expects service with id "serviceName"' .' to be Psr\Http\Server\RequestHandlerInterface, stdClass given' ); $builder = new MockObjectBuilder(); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, []); $originalRequestHandler = new \stdClass(); /** @var ContainerInterface $container */ $container = $builder->create(ContainerInterface::class, [ new WithReturn('get', ['serviceName'], $originalRequestHandler), ]); $requestHandler = new LazyRequestHandler($container, 'serviceName'); $requestHandler->handle($request); } public function testHandleWithString(): void { $this->expectException(\TypeError::class); $this->expectExceptionMessage( 'Chubbyphp\Framework\RequestHandler\LazyRequestHandler::handle() expects service with id "serviceName"' .' to be Psr\Http\Server\RequestHandlerInterface, string given' ); $builder = new MockObjectBuilder(); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, []); $originalRequestHandler = ''; /** @var ContainerInterface $container */ $container = $builder->create(ContainerInterface::class, [ new WithReturn('get', ['serviceName'], $originalRequestHandler), ]); $requestHandler = new LazyRequestHandler($container, 'serviceName'); $requestHandler->handle($request); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Unit/RequestHandler/CallbackRequestHandlerTest.php
tests/Unit/RequestHandler/CallbackRequestHandlerTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Unit\RequestHandler; use Chubbyphp\Framework\RequestHandler\CallbackRequestHandler; use Chubbyphp\Mock\MockObjectBuilder; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; /** * @covers \Chubbyphp\Framework\RequestHandler\CallbackRequestHandler * * @internal */ final class CallbackRequestHandlerTest extends TestCase { public function testHandle(): void { $builder = new MockObjectBuilder(); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, []); /** @var ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, []); $requestHandler = new CallbackRequestHandler(static fn (ServerRequestInterface $request) => $response); self::assertSame($response, $requestHandler->handle($request)); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Unit/RequestHandler/SlimCallbackRequestHandlerTest.php
tests/Unit/RequestHandler/SlimCallbackRequestHandlerTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Unit\RequestHandler; use Chubbyphp\Framework\RequestHandler\SlimCallbackRequestHandler; use Chubbyphp\Mock\MockMethod\WithReturn; use Chubbyphp\Mock\MockObjectBuilder; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; /** * @covers \Chubbyphp\Framework\RequestHandler\SlimCallbackRequestHandler * * @internal */ final class SlimCallbackRequestHandlerTest extends TestCase { public function testHandleWithoutExistingResponse(): void { $builder = new MockObjectBuilder(); /** @var ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, []); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, [ new WithReturn('getAttribute', ['response', null], null), new WithReturn('getAttributes', [], ['key1' => 'value1', 'key2' => 'value2']), ]); /** @var ResponseFactoryInterface $responseFactory */ $responseFactory = $builder->create(ResponseFactoryInterface::class, [ new WithReturn('createResponse', [200, ''], $response), ]); $requestHandler = new SlimCallbackRequestHandler( static function ( ServerRequestInterface $req, ResponseInterface $res, array $args ) use ($request, $response) { self::assertSame($request, $req); self::assertSame($response, $res); self::assertSame(['key1' => 'value1', 'key2' => 'value2'], $args); return $res; }, $responseFactory ); self::assertSame($response, $requestHandler->handle($request)); } public function testHandleWithExistingResponse(): void { $builder = new MockObjectBuilder(); /** @var ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, []); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, [ new WithReturn('getAttribute', ['response', null], $response), new WithReturn( 'getAttributes', [], ['key1' => 'value1', 'key2' => 'value2', 'response' => $response] ), ]); /** @var ResponseFactoryInterface $responseFactory */ $responseFactory = $builder->create(ResponseFactoryInterface::class, []); $requestHandler = new SlimCallbackRequestHandler( static function ( ServerRequestInterface $req, ResponseInterface $res, array $args ) use ($request, $response) { self::assertSame($request, $req); self::assertSame($response, $res); self::assertSame(['key1' => 'value1', 'key2' => 'value2', 'response' => $response], $args); return $res; }, $responseFactory ); self::assertSame($response, $requestHandler->handle($request)); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Unit/RequestHandler/SlimLazyRequestHandlerTest.php
tests/Unit/RequestHandler/SlimLazyRequestHandlerTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Unit\RequestHandler; use Chubbyphp\Framework\RequestHandler\SlimLazyRequestHandler; use Chubbyphp\Mock\MockMethod\WithReturn; use Chubbyphp\Mock\MockObjectBuilder; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; /** * @covers \Chubbyphp\Framework\RequestHandler\SlimLazyRequestHandler * * @internal */ final class SlimLazyRequestHandlerTest extends TestCase { public function testHandle(): void { $builder = new MockObjectBuilder(); /** @var ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, []); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, [ new WithReturn('getAttribute', ['response', null], null), new WithReturn('getAttributes', [], ['key1' => 'value1', 'key2' => 'value2']), ]); $originalRequestHandler = static fn (ServerRequestInterface $req, ResponseInterface $res, array $args) => $res; /** @var ContainerInterface $container */ $container = $builder->create(ContainerInterface::class, [ new WithReturn('get', ['serviceName'], $originalRequestHandler), ]); /** @var ResponseFactoryInterface $responseFactory */ $responseFactory = $builder->create(ResponseFactoryInterface::class, [ new WithReturn('createResponse', [200, ''], $response), ]); $requestHandler = new SlimLazyRequestHandler($container, 'serviceName', $responseFactory); self::assertSame($response, $requestHandler->handle($request)); } public function testHandleWithWrongObject(): void { $this->expectException(\TypeError::class); $this->expectExceptionMessage( 'Chubbyphp\Framework\RequestHandler\SlimLazyRequestHandler::handle() expects service with id "serviceName"' .' to be callable, stdClass given' ); $builder = new MockObjectBuilder(); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, []); $originalRequestHandler = new \stdClass(); /** @var ContainerInterface $container */ $container = $builder->create(ContainerInterface::class, [ new WithReturn('get', ['serviceName'], $originalRequestHandler), ]); /** @var ResponseFactoryInterface $responseFactory */ $responseFactory = $builder->create(ResponseFactoryInterface::class, []); $requestHandler = new SlimLazyRequestHandler($container, 'serviceName', $responseFactory); $requestHandler->handle($request); } public function testHandleWithString(): void { $this->expectException(\TypeError::class); $this->expectExceptionMessage( 'Chubbyphp\Framework\RequestHandler\SlimLazyRequestHandler::handle() expects service with id "serviceName"' .' to be callable, string given' ); $builder = new MockObjectBuilder(); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, []); $originalRequestHandler = ''; /** @var ContainerInterface $container */ $container = $builder->create(ContainerInterface::class, [ new WithReturn('get', ['serviceName'], $originalRequestHandler), ]); /** @var ResponseFactoryInterface $responseFactory */ $responseFactory = $builder->create(ResponseFactoryInterface::class, []); $requestHandler = new SlimLazyRequestHandler($container, 'serviceName', $responseFactory); $requestHandler->handle($request); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Unit/RequestHandler/RouteRequestHandlerTest.php
tests/Unit/RequestHandler/RouteRequestHandlerTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Unit\RequestHandler; use Chubbyphp\Framework\RequestHandler\RouteRequestHandler; use Chubbyphp\Framework\Router\Exceptions\MissingRouteAttributeOnRequestException; use Chubbyphp\Framework\Router\RouteInterface; use Chubbyphp\Mock\MockMethod\WithCallback; use Chubbyphp\Mock\MockMethod\WithReturn; use Chubbyphp\Mock\MockObjectBuilder; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; /** * @covers \Chubbyphp\Framework\RequestHandler\RouteRequestHandler * * @internal */ final class RouteRequestHandlerTest extends TestCase { public function testHandleWithoutRoute(): void { $this->expectException(MissingRouteAttributeOnRequestException::class); $this->expectExceptionMessage( 'Request attribute "route" missing or wrong type "null", please add the' .' "Chubbyphp\Framework\Middleware\RouteMatcherMiddleware" middleware' ); $builder = new MockObjectBuilder(); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, [ new WithReturn('getAttribute', ['route', null], null), ]); /** @var ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, []); $requestHandler = new RouteRequestHandler(); self::assertSame($response, $requestHandler->handle($request)); } public function testHandleWithRoute(): void { $builder = new MockObjectBuilder(); /** @var ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, []); /** @var MiddlewareInterface $middleware */ $middleware = $builder->create(MiddlewareInterface::class, [ new WithCallback( 'process', static fn ( ServerRequestInterface $request, RequestHandlerInterface $requestHandler ) => $requestHandler->handle($request) ), ]); /** @var RequestHandlerInterface $innerRequestHandler */ $innerRequestHandler = $builder->create(RequestHandlerInterface::class, [ new WithCallback( 'handle', static fn ( ServerRequestInterface $request, ) => $response, ), ]); /** @var RouteInterface $route */ $route = $builder->create(RouteInterface::class, [ new WithReturn('getMiddlewares', [], [$middleware]), new WithReturn('getRequestHandler', [], $innerRequestHandler), ]); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, [ new WithReturn('getAttribute', ['route', null], $route), ]); $requestHandler = new RouteRequestHandler(); self::assertSame($response, $requestHandler->handle($request)); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Unit/Router/RouteTest.php
tests/Unit/Router/RouteTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Unit\Router; use Chubbyphp\Framework\Router\Route; use Chubbyphp\Mock\MockObjectBuilder; use PHPUnit\Framework\TestCase; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; /** * @covers \Chubbyphp\Framework\Router\Route * * @internal */ final class RouteTest extends TestCase { public function testMinimal(): void { $builder = new MockObjectBuilder(); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); $route = Route::create('GET', '/{id}', 'read', $handler); self::assertSame('read', $route->getName()); self::assertSame('GET', $route->getMethod()); self::assertSame('/{id}', $route->getPath()); self::assertSame([], $route->getPathOptions()); self::assertSame([], $route->getMiddlewares()); self::assertSame($handler, $route->getRequestHandler()); self::assertSame([], $route->getAttributes()); } public function testMaximal(): void { $builder = new MockObjectBuilder(); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); /** @var MiddlewareInterface $middleware1 */ $middleware1 = $builder->create(MiddlewareInterface::class, []); /** @var MiddlewareInterface $middleware2 */ $middleware2 = $builder->create(MiddlewareInterface::class, []); $route = Route::create( 'GET', '/{id}', 'read', $handler, [$middleware1, $middleware2], ['tokens' => ['id' => '\d+']] ); self::assertSame('read', $route->getName()); self::assertSame('GET', $route->getMethod()); self::assertSame('/{id}', $route->getPath()); self::assertSame(['tokens' => ['id' => '\d+']], $route->getPathOptions()); self::assertSame([$middleware1, $middleware2], $route->getMiddlewares()); self::assertSame($handler, $route->getRequestHandler()); self::assertSame([], $route->getAttributes()); } public function testDeleteMinimal(): void { $builder = new MockObjectBuilder(); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); $route = Route::delete('/{id}', 'delete', $handler); self::assertSame('delete', $route->getName()); self::assertSame('DELETE', $route->getMethod()); self::assertSame('/{id}', $route->getPath()); self::assertSame([], $route->getPathOptions()); self::assertSame([], $route->getMiddlewares()); self::assertSame($handler, $route->getRequestHandler()); self::assertSame([], $route->getAttributes()); } public function testDeleteMaximal(): void { $builder = new MockObjectBuilder(); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); /** @var MiddlewareInterface $middleware1 */ $middleware1 = $builder->create(MiddlewareInterface::class, []); /** @var MiddlewareInterface $middleware2 */ $middleware2 = $builder->create(MiddlewareInterface::class, []); $route = Route::delete('/{id}', 'delete', $handler, [$middleware1, $middleware2], ['tokens' => ['id' => '\d+']]); self::assertSame('delete', $route->getName()); self::assertSame('DELETE', $route->getMethod()); self::assertSame('/{id}', $route->getPath()); self::assertSame(['tokens' => ['id' => '\d+']], $route->getPathOptions()); self::assertSame([$middleware1, $middleware2], $route->getMiddlewares()); self::assertSame($handler, $route->getRequestHandler()); self::assertSame([], $route->getAttributes()); } public function testGetMinimal(): void { $builder = new MockObjectBuilder(); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); $route = Route::get('/{id}', 'read', $handler); self::assertSame('read', $route->getName()); self::assertSame('GET', $route->getMethod()); self::assertSame('/{id}', $route->getPath()); self::assertSame([], $route->getPathOptions()); self::assertSame([], $route->getMiddlewares()); self::assertSame($handler, $route->getRequestHandler()); self::assertSame([], $route->getAttributes()); } public function testGetMaximal(): void { $builder = new MockObjectBuilder(); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); /** @var MiddlewareInterface $middleware1 */ $middleware1 = $builder->create(MiddlewareInterface::class, []); /** @var MiddlewareInterface $middleware2 */ $middleware2 = $builder->create(MiddlewareInterface::class, []); $route = Route::get('/{id}', 'get', $handler, [$middleware1, $middleware2], ['tokens' => ['id' => '\d+']]); self::assertSame('get', $route->getName()); self::assertSame('GET', $route->getMethod()); self::assertSame('/{id}', $route->getPath()); self::assertSame(['tokens' => ['id' => '\d+']], $route->getPathOptions()); self::assertSame([$middleware1, $middleware2], $route->getMiddlewares()); self::assertSame($handler, $route->getRequestHandler()); self::assertSame([], $route->getAttributes()); } public function testHeadMinimal(): void { $builder = new MockObjectBuilder(); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); $route = Route::head('/{id}', 'read_header', $handler); self::assertSame('read_header', $route->getName()); self::assertSame('HEAD', $route->getMethod()); self::assertSame('/{id}', $route->getPath()); self::assertSame([], $route->getPathOptions()); self::assertSame([], $route->getMiddlewares()); self::assertSame($handler, $route->getRequestHandler()); self::assertSame([], $route->getAttributes()); } public function testHeadMaximal(): void { $builder = new MockObjectBuilder(); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); /** @var MiddlewareInterface $middleware1 */ $middleware1 = $builder->create(MiddlewareInterface::class, []); /** @var MiddlewareInterface $middleware2 */ $middleware2 = $builder->create(MiddlewareInterface::class, []); $route = Route::head('/{id}', 'head', $handler, [$middleware1, $middleware2], ['tokens' => ['id' => '\d+']]); self::assertSame('head', $route->getName()); self::assertSame('HEAD', $route->getMethod()); self::assertSame('/{id}', $route->getPath()); self::assertSame(['tokens' => ['id' => '\d+']], $route->getPathOptions()); self::assertSame([$middleware1, $middleware2], $route->getMiddlewares()); self::assertSame($handler, $route->getRequestHandler()); self::assertSame([], $route->getAttributes()); } public function testOptionsMinimal(): void { $builder = new MockObjectBuilder(); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); $route = Route::options('/{id}', 'options', $handler); self::assertSame('options', $route->getName()); self::assertSame('OPTIONS', $route->getMethod()); self::assertSame('/{id}', $route->getPath()); self::assertSame([], $route->getPathOptions()); self::assertSame([], $route->getMiddlewares()); self::assertSame($handler, $route->getRequestHandler()); self::assertSame([], $route->getAttributes()); } public function testOptionsMaximal(): void { $builder = new MockObjectBuilder(); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); /** @var MiddlewareInterface $middleware1 */ $middleware1 = $builder->create(MiddlewareInterface::class, []); /** @var MiddlewareInterface $middleware2 */ $middleware2 = $builder->create(MiddlewareInterface::class, []); $route = Route::options('/{id}', 'options', $handler, [$middleware1, $middleware2], ['tokens' => ['id' => '\d+']]); self::assertSame('options', $route->getName()); self::assertSame('OPTIONS', $route->getMethod()); self::assertSame('/{id}', $route->getPath()); self::assertSame(['tokens' => ['id' => '\d+']], $route->getPathOptions()); self::assertSame([$middleware1, $middleware2], $route->getMiddlewares()); self::assertSame($handler, $route->getRequestHandler()); self::assertSame([], $route->getAttributes()); } public function testPatchMinimal(): void { $builder = new MockObjectBuilder(); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); $route = Route::patch('/{id}', 'update', $handler); self::assertSame('update', $route->getName()); self::assertSame('PATCH', $route->getMethod()); self::assertSame('/{id}', $route->getPath()); self::assertSame([], $route->getPathOptions()); self::assertSame([], $route->getMiddlewares()); self::assertSame($handler, $route->getRequestHandler()); self::assertSame([], $route->getAttributes()); } public function testPatchMaximal(): void { $builder = new MockObjectBuilder(); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); /** @var MiddlewareInterface $middleware1 */ $middleware1 = $builder->create(MiddlewareInterface::class, []); /** @var MiddlewareInterface $middleware2 */ $middleware2 = $builder->create(MiddlewareInterface::class, []); $route = Route::patch('/{id}', 'patch', $handler, [$middleware1, $middleware2], ['tokens' => ['id' => '\d+']]); self::assertSame('patch', $route->getName()); self::assertSame('PATCH', $route->getMethod()); self::assertSame('/{id}', $route->getPath()); self::assertSame(['tokens' => ['id' => '\d+']], $route->getPathOptions()); self::assertSame([$middleware1, $middleware2], $route->getMiddlewares()); self::assertSame($handler, $route->getRequestHandler()); self::assertSame([], $route->getAttributes()); } public function testPostMinimal(): void { $builder = new MockObjectBuilder(); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); $route = Route::post('/{id}', 'create', $handler); self::assertSame('create', $route->getName()); self::assertSame('POST', $route->getMethod()); self::assertSame('/{id}', $route->getPath()); self::assertSame([], $route->getPathOptions()); self::assertSame([], $route->getMiddlewares()); self::assertSame($handler, $route->getRequestHandler()); self::assertSame([], $route->getAttributes()); } public function testPostMaximal(): void { $builder = new MockObjectBuilder(); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); /** @var MiddlewareInterface $middleware1 */ $middleware1 = $builder->create(MiddlewareInterface::class, []); /** @var MiddlewareInterface $middleware2 */ $middleware2 = $builder->create(MiddlewareInterface::class, []); $route = Route::post('/{id}', 'post', $handler, [$middleware1, $middleware2], ['tokens' => ['id' => '\d+']]); self::assertSame('post', $route->getName()); self::assertSame('POST', $route->getMethod()); self::assertSame('/{id}', $route->getPath()); self::assertSame(['tokens' => ['id' => '\d+']], $route->getPathOptions()); self::assertSame([$middleware1, $middleware2], $route->getMiddlewares()); self::assertSame($handler, $route->getRequestHandler()); self::assertSame([], $route->getAttributes()); } public function testPutMinimal(): void { $builder = new MockObjectBuilder(); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); $route = Route::put('/{id}', 'replace', $handler); self::assertSame('replace', $route->getName()); self::assertSame('PUT', $route->getMethod()); self::assertSame('/{id}', $route->getPath()); self::assertSame([], $route->getPathOptions()); self::assertSame([], $route->getMiddlewares()); self::assertSame($handler, $route->getRequestHandler()); self::assertSame([], $route->getAttributes()); } public function testPutMaximal(): void { $builder = new MockObjectBuilder(); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); /** @var MiddlewareInterface $middleware1 */ $middleware1 = $builder->create(MiddlewareInterface::class, []); /** @var MiddlewareInterface $middleware2 */ $middleware2 = $builder->create(MiddlewareInterface::class, []); $route = Route::put('/{id}', 'put', $handler, [$middleware1, $middleware2], ['tokens' => ['id' => '\d+']]); self::assertSame('put', $route->getName()); self::assertSame('PUT', $route->getMethod()); self::assertSame('/{id}', $route->getPath()); self::assertSame(['tokens' => ['id' => '\d+']], $route->getPathOptions()); self::assertSame([$middleware1, $middleware2], $route->getMiddlewares()); self::assertSame($handler, $route->getRequestHandler()); self::assertSame([], $route->getAttributes()); } public function testWithAttributes(): void { $builder = new MockObjectBuilder(); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); $route = Route::create('GET', '/{id}', 'read', $handler); $routeClone = $route->withAttributes(['id' => 5]); self::assertNotSame($route, $routeClone); self::assertSame(['id' => 5], $routeClone->getAttributes()); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Unit/Router/RoutesByNameTest.php
tests/Unit/Router/RoutesByNameTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Unit\Router; use Chubbyphp\Framework\Router\RouteInterface; use Chubbyphp\Framework\Router\RoutesByName; use Chubbyphp\Mock\MockMethod\WithReturn; use Chubbyphp\Mock\MockObjectBuilder; use PHPUnit\Framework\TestCase; /** * @covers \Chubbyphp\Framework\Router\RoutesByName * * @internal */ final class RoutesByNameTest extends TestCase { public function testGetRoutes(): void { $builder = new MockObjectBuilder(); $route1 = $builder->create(RouteInterface::class, [ new WithReturn('getName', [], 'name1'), ]); $route2 = $builder->create(RouteInterface::class, [ new WithReturn('getName', [], 'name2'), ]); $routes = new RoutesByName([$route1, $route2]); self::assertSame(['name1' => $route1, 'name2' => $route2], $routes->getRoutesByName()); } public function testWithoutRoutes(): void { $routes = new RoutesByName([]); self::assertSame([], $routes->getRoutesByName()); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Unit/Router/GroupTest.php
tests/Unit/Router/GroupTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Unit\Router; use Chubbyphp\Framework\Router\Group; use Chubbyphp\Framework\Router\Route; use Chubbyphp\Framework\Router\RouteInterface; use Chubbyphp\Mock\MockObjectBuilder; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; /** * @covers \Chubbyphp\Framework\Router\Group * * @internal */ final class GroupTest extends TestCase { public function testMinimal(): void { $group = Group::create(''); self::assertSame([], $group->getRoutes()); } public function testMaximal(): void { $builder = new MockObjectBuilder(); /** @var MiddlewareInterface $middleware1 */ $middleware1 = $builder->create(MiddlewareInterface::class, []); /** @var MiddlewareInterface $middleware2 */ $middleware2 = $builder->create(MiddlewareInterface::class, []); /** @var MiddlewareInterface $middleware3 */ $middleware3 = $builder->create(MiddlewareInterface::class, []); /** @var MockObject|RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); $group = Group::create('/{id}', [ Route::get('/{slug}', 'element_read', $handler, [$middleware2], ['tokens' => ['slug' => '[a-z]+']]), Group::create('/{slug}', [ Route::get('/{key}', 'another_route', $handler, [$middleware3], ['tokens' => ['key' => '[a-z]+']]), ], [$middleware2], ['tokens' => ['slug' => '[a-z]+']]), Route::get( '/{slug}/{key}/{subKey}', 'yet_another_route', $handler, [$middleware2], ['tokens' => ['slug' => '[a-z]+', 'key' => '[a-z]+', 'subKey' => '[a-z]+']] ), ], [$middleware1], ['tokens' => ['id' => '\d+']]); $routes = $group->getRoutes(); self::assertCount(3, $routes); /** @var RouteInterface $route1 */ $route1 = $routes[0]; self::assertSame('element_read', $route1->getName()); self::assertSame('GET', $route1->getMethod()); self::assertSame('/{id}/{slug}', $route1->getPath()); self::assertSame(['tokens' => ['id' => '\d+', 'slug' => '[a-z]+']], $route1->getPathOptions()); self::assertSame([$middleware1, $middleware2], $route1->getMiddlewares()); self::assertSame($handler, $route1->getRequestHandler()); /** @var RouteInterface $route2 */ $route2 = $routes[1]; self::assertSame('another_route', $route2->getName()); self::assertSame('GET', $route2->getMethod()); self::assertSame('/{id}/{slug}/{key}', $route2->getPath()); self::assertSame( ['tokens' => ['id' => '\d+', 'slug' => '[a-z]+', 'key' => '[a-z]+']], $route2->getPathOptions() ); self::assertSame([$middleware1, $middleware2, $middleware3], $route2->getMiddlewares()); self::assertSame($handler, $route2->getRequestHandler()); /** @var RouteInterface $route3 */ $route3 = $routes[2]; self::assertSame('yet_another_route', $route3->getName()); self::assertSame('GET', $route3->getMethod()); self::assertSame('/{id}/{slug}/{key}/{subKey}', $route3->getPath()); self::assertSame( ['tokens' => ['id' => '\d+', 'slug' => '[a-z]+', 'key' => '[a-z]+', 'subKey' => '[a-z]+']], $route3->getPathOptions() ); self::assertSame([$middleware1, $middleware2], $route3->getMiddlewares()); self::assertSame($handler, $route3->getRequestHandler()); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Unit/Router/Exceptions/MissingRouteAttributeOnRequestExceptionTest.php
tests/Unit/Router/Exceptions/MissingRouteAttributeOnRequestExceptionTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Unit\Router\Exceptions; use Chubbyphp\Framework\Router\Exceptions\MissingRouteAttributeOnRequestException; use PHPUnit\Framework\TestCase; /** * @covers \Chubbyphp\Framework\Router\Exceptions\MissingRouteAttributeOnRequestException * * @internal */ final class MissingRouteAttributeOnRequestExceptionTest extends TestCase { public function testConstruct(): void { $this->expectException(\Error::class); $this->expectExceptionMessage('Call to private'); new MissingRouteAttributeOnRequestException('test', 0); } public function testCreateWithNull(): void { $route = null; $exception = MissingRouteAttributeOnRequestException::create($route); self::assertSame( 'Request attribute "route" missing or wrong type "null", please add the' .' "Chubbyphp\Framework\Middleware\RouteMatcherMiddleware" middleware', $exception->getMessage() ); self::assertSame(1, $exception->getCode()); } public function testCreateWithObject(): void { $route = new \stdClass(); $exception = MissingRouteAttributeOnRequestException::create($route); self::assertSame( 'Request attribute "route" missing or wrong type "stdClass", please add the' .' "Chubbyphp\Framework\Middleware\RouteMatcherMiddleware" middleware', $exception->getMessage() ); self::assertSame(1, $exception->getCode()); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Unit/Router/Exceptions/MissingRouteByNameExceptionTest.php
tests/Unit/Router/Exceptions/MissingRouteByNameExceptionTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Unit\Router\Exceptions; use Chubbyphp\Framework\Router\Exceptions\MissingRouteByNameException; use PHPUnit\Framework\TestCase; /** * @covers \Chubbyphp\Framework\Router\Exceptions\MissingRouteByNameException * * @internal */ final class MissingRouteByNameExceptionTest extends TestCase { public function testConstruct(): void { $this->expectException(\Error::class); $this->expectExceptionMessage('Call to private'); new MissingRouteByNameException('test', 0); } public function testCreate(): void { $exception = MissingRouteByNameException::create('name'); self::assertSame('Missing route: "name"', $exception->getMessage()); self::assertSame(2, $exception->getCode()); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Unit/Router/Exceptions/RouteGenerationExceptionTest.php
tests/Unit/Router/Exceptions/RouteGenerationExceptionTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Unit\Router\Exceptions; use Chubbyphp\Framework\Router\Exceptions\RouteGenerationException; use PHPUnit\Framework\TestCase; /** * @covers \Chubbyphp\Framework\Router\Exceptions\RouteGenerationException * * @internal */ final class RouteGenerationExceptionTest extends TestCase { public function testConstruct(): void { $this->expectException(\Error::class); $this->expectExceptionMessage('Call to private'); new RouteGenerationException('test', 0); } public function testCreate(): void { $previous = new \RuntimeException('Something went wrong'); $exception = RouteGenerationException::create('name', '/name/{name}', ['name' => 'name'], $previous); self::assertSame( 'Route generation for route "name" with path "/name/{name}" with attributes "{"name":"name"}" failed. Something went wrong', $exception->getMessage() ); self::assertSame(3, $exception->getCode()); self::assertSame($previous, $exception->getPrevious()); } public function testCreateWithEmptyAttributes(): void { $exception = RouteGenerationException::create('name', '/name/{name}', []); self::assertSame( 'Route generation for route "name" with path "/name/{name}" with attributes "{}" failed.', $exception->getMessage() ); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Unit/Middleware/ExceptionMiddlewareTest.php
tests/Unit/Middleware/ExceptionMiddlewareTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Unit\Middleware; use Chubbyphp\Framework\Middleware\ExceptionMiddleware; use Chubbyphp\HttpException\HttpException; use Chubbyphp\Mock\MockMethod\WithCallback; use Chubbyphp\Mock\MockMethod\WithException; use Chubbyphp\Mock\MockMethod\WithReturn; use Chubbyphp\Mock\MockMethod\WithReturnSelf; use Chubbyphp\Mock\MockObjectBuilder; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Message\StreamInterface; use Psr\Http\Server\RequestHandlerInterface; use Psr\Log\LoggerInterface; /** * @covers \Chubbyphp\Framework\Middleware\ExceptionMiddleware * * @internal */ final class ExceptionMiddlewareTest extends TestCase { public function testProcess(): void { $builder = new MockObjectBuilder(); /** @var MockObject|ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, []); /** @var MockObject|ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, []); /** @var MockObject|RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, [ new WithReturn('handle', [$request], $response), ]); /** @var MockObject|ResponseFactoryInterface $responseFactory */ $responseFactory = $builder->create(ResponseFactoryInterface::class, []); $middleware = new ExceptionMiddleware($responseFactory); self::assertSame($response, $middleware->process($request, $handler)); } public function testProcessWithClientHttpExceptionWithoutLogger(): void { $httpException = HttpException::createImateapot([ 'key1' => 'value1', 'key2' => 'value2', ], new \LogicException('logic exception', 42)); $builder = new MockObjectBuilder(); /** @var MockObject|ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, []); $expectedBody = <<<'EOT' <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>I'm a teapot</title> <style> html { font-family: Helvetica, Arial, Verdana, sans-serif; line-height: 1.5; tab-size: 4; } body { margin: 0; } * { border-width: 0; border-style: solid; } .container { width: 100% } .mx-auto { margin-left: auto; margin-right: auto; } .mt-12 { margin-top: 3rem; } .mb-12 { margin-bottom: 3rem; } .text-gray-400 { --tw-text-opacity: 1; color: rgba(156, 163, 175, var(--tw-text-opacity)); } .text-5xl { font-size: 3rem; line-height: 1; } .text-right { text-align: right; } .tracking-tighter { letter-spacing: -.05em; } .flex { display: flex; } .flex-row { flex-direction: row; } .basis-2\/12 { flex-basis: 16.666667%; } .basis-10\/12 { flex-basis: 83.333333%; } .space-x-8>:not([hidden])~:not([hidden]) { --tw-space-x-reverse: 0; margin-right: calc(2rem * var(--tw-space-x-reverse)); margin-left: calc(2rem * calc(1 - var(--tw-space-x-reverse))) } .gap-x-4 { column-gap: 1rem; } .gap-y-1\.5 { row-gap: 0.375rem; } .grid-cols-1 { grid-template-columns: repeat(1, minmax(0, 1fr)); } .grid { display: grid; } @media (min-width:640px) { .container { max-width: 640px } } @media (min-width:768px) { .container { max-width: 768px } .md\:grid-cols-8 { grid-template-columns: repeat(8, minmax(0, 1fr)); } .md\:col-span-7 { grid-column: span 7/span 7 } } @media (min-width:1024px) { .container { max-width: 1024px } } @media (min-width:1280px) { .container { max-width: 1280px } } @media (min-width:1536px) { .container { max-width: 1536px } } </style> </head> <body> <div class="container mx-auto tracking-tighter mt-12"> <div class="flex flex-row space-x-8"> <div class="basis-1/12 text-5xl text-gray-400 text-right">418</div> <div class="basis-11/12"> <span class="text-5xl">I'm a teapot</span> </div> </div> </div> </body> </html> EOT; /** @var MockObject|StreamInterface $responseBody */ $responseBody = $builder->create(StreamInterface::class, [ new WithReturn('write', [$expectedBody], \strlen($expectedBody)), ]); /** @var MockObject|ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, [ new WithReturnSelf('withHeader', ['Content-Type', 'text/html']), new WithReturn('getBody', [], $responseBody), ]); /** @var MockObject|RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, [ new WithException('handle', [$request], $httpException), ]); /** @var MockObject|ResponseFactoryInterface $responseFactory */ $responseFactory = $builder->create(ResponseFactoryInterface::class, [ new WithReturn('createResponse', [418, ''], $response), ]); $middleware = new ExceptionMiddleware($responseFactory); self::assertSame($response, $middleware->process($request, $handler)); } public function testProcessWithClientHttpExceptionWithLogger(): void { $httpException = HttpException::createNotFound([ 'detail' => 'Could not found route "/unknown"', 'instance' => 'instance-1234', ], new \LogicException('logic exception', 42)); $builder = new MockObjectBuilder(); /** @var MockObject|ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, []); $expectedBody = <<<'EOT' <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Not Found</title> <style> html { font-family: Helvetica, Arial, Verdana, sans-serif; line-height: 1.5; tab-size: 4; } body { margin: 0; } * { border-width: 0; border-style: solid; } .container { width: 100% } .mx-auto { margin-left: auto; margin-right: auto; } .mt-12 { margin-top: 3rem; } .mb-12 { margin-bottom: 3rem; } .text-gray-400 { --tw-text-opacity: 1; color: rgba(156, 163, 175, var(--tw-text-opacity)); } .text-5xl { font-size: 3rem; line-height: 1; } .text-right { text-align: right; } .tracking-tighter { letter-spacing: -.05em; } .flex { display: flex; } .flex-row { flex-direction: row; } .basis-2\/12 { flex-basis: 16.666667%; } .basis-10\/12 { flex-basis: 83.333333%; } .space-x-8>:not([hidden])~:not([hidden]) { --tw-space-x-reverse: 0; margin-right: calc(2rem * var(--tw-space-x-reverse)); margin-left: calc(2rem * calc(1 - var(--tw-space-x-reverse))) } .gap-x-4 { column-gap: 1rem; } .gap-y-1\.5 { row-gap: 0.375rem; } .grid-cols-1 { grid-template-columns: repeat(1, minmax(0, 1fr)); } .grid { display: grid; } @media (min-width:640px) { .container { max-width: 640px } } @media (min-width:768px) { .container { max-width: 768px } .md\:grid-cols-8 { grid-template-columns: repeat(8, minmax(0, 1fr)); } .md\:col-span-7 { grid-column: span 7/span 7 } } @media (min-width:1024px) { .container { max-width: 1024px } } @media (min-width:1280px) { .container { max-width: 1280px } } @media (min-width:1536px) { .container { max-width: 1536px } } </style> </head> <body> <div class="container mx-auto tracking-tighter mt-12"> <div class="flex flex-row space-x-8"> <div class="basis-1/12 text-5xl text-gray-400 text-right">404</div> <div class="basis-11/12"> <span class="text-5xl">Not Found</span><p>Could not found route "/unknown"</p><p>instance-1234</p> </div> </div> </div> </body> </html> EOT; /** @var MockObject|StreamInterface $responseBody */ $responseBody = $builder->create(StreamInterface::class, [ new WithReturn('write', [$expectedBody], \strlen($expectedBody)), ]); /** @var MockObject|ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, [ new WithReturnSelf('withHeader', ['Content-Type', 'text/html']), new WithReturn('getBody', [], $responseBody), ]); /** @var MockObject|RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, [ new WithException('handle', [$request], $httpException), ]); /** @var MockObject|ResponseFactoryInterface $responseFactory */ $responseFactory = $builder->create(ResponseFactoryInterface::class, [ new WithReturn('createResponse', [404, ''], $response), ]); /** @var LoggerInterface|MockObject $logger */ $logger = $builder->create(LoggerInterface::class, [ new WithCallback('info', static function (string $message, array $context): void { self::assertSame('Http Exception', $message); self::assertArrayHasKey('data', $context); $data = $context['data']; self::assertSame([ 'type' => 'https://datatracker.ietf.org/doc/html/rfc2616#section-10.4.5', 'status' => 404, 'title' => 'Not Found', 'detail' => 'Could not found route "/unknown"', 'instance' => 'instance-1234', ], $data); self::assertArrayHasKey('exceptions', $context); $exceptions = $context['exceptions']; self::assertCount(2, $exceptions); $exception1 = $exceptions[0]; self::assertArrayHasKey('message', $exception1); self::assertArrayHasKey('code', $exception1); self::assertArrayHasKey('file', $exception1); self::assertArrayHasKey('line', $exception1); self::assertArrayHasKey('trace', $exception1); self::assertSame(HttpException::class, $exception1['class']); self::assertSame('Not Found', $exception1['message']); self::assertSame(404, $exception1['code']); $exception2 = $exceptions[1]; self::assertArrayHasKey('message', $exception2); self::assertArrayHasKey('code', $exception2); self::assertArrayHasKey('file', $exception2); self::assertArrayHasKey('line', $exception2); self::assertArrayHasKey('trace', $exception2); self::assertSame('LogicException', $exception2['class']); self::assertSame('logic exception', $exception2['message']); self::assertSame(42, $exception2['code']); }), ]); $middleware = new ExceptionMiddleware($responseFactory, false, $logger); self::assertSame($response, $middleware->process($request, $handler)); } public function testProcessWithServerHttpExceptionWithDebugWithLogger(): void { $httpException = HttpException::createInternalServerError([], new \LogicException('logic exception', 42)); $builder = new MockObjectBuilder(); /** @var MockObject|ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, []); $expectedBody = <<<'EOT' <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>Internal Server Error</title> <style> html { font-family: Helvetica, Arial, Verdana, sans-serif; line-height: 1.5; tab-size: 4; } body { margin: 0; } * { border-width: 0; border-style: solid; } .container { width: 100% } .mx-auto { margin-left: auto; margin-right: auto; } .mt-12 { margin-top: 3rem; } .mb-12 { margin-bottom: 3rem; } .text-gray-400 { --tw-text-opacity: 1; color: rgba(156, 163, 175, var(--tw-text-opacity)); } .text-5xl { font-size: 3rem; line-height: 1; } .text-right { text-align: right; } .tracking-tighter { letter-spacing: -.05em; } .flex { display: flex; } .flex-row { flex-direction: row; } .basis-2\/12 { flex-basis: 16.666667%; } .basis-10\/12 { flex-basis: 83.333333%; } .space-x-8>:not([hidden])~:not([hidden]) { --tw-space-x-reverse: 0; margin-right: calc(2rem * var(--tw-space-x-reverse)); margin-left: calc(2rem * calc(1 - var(--tw-space-x-reverse))) } .gap-x-4 { column-gap: 1rem; } .gap-y-1\.5 { row-gap: 0.375rem; } .grid-cols-1 { grid-template-columns: repeat(1, minmax(0, 1fr)); } .grid { display: grid; } @media (min-width:640px) { .container { max-width: 640px } } @media (min-width:768px) { .container { max-width: 768px } .md\:grid-cols-8 { grid-template-columns: repeat(8, minmax(0, 1fr)); } .md\:col-span-7 { grid-column: span 7/span 7 } } @media (min-width:1024px) { .container { max-width: 1024px } } @media (min-width:1280px) { .container { max-width: 1280px } } @media (min-width:1536px) { .container { max-width: 1536px } } </style> </head> <body> <div class="container mx-auto tracking-tighter mt-12"> <div class="flex flex-row space-x-8"> <div class="basis-1/12 text-5xl text-gray-400 text-right">500</div> <div class="basis-11/12"> <span class="text-5xl">Internal Server Error</span> </div> </div> </div> </body> </html> EOT; /** @var MockObject|StreamInterface $responseBody */ $responseBody = $builder->create(StreamInterface::class, [ new WithReturn('write', [$expectedBody], \strlen($expectedBody)), ]); /** @var MockObject|ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, [ new WithReturnSelf('withHeader', ['Content-Type', 'text/html']), new WithReturn('getBody', [], $responseBody), ]); /** @var MockObject|RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, [ new WithException('handle', [$request], $httpException), ]); /** @var MockObject|ResponseFactoryInterface $responseFactory */ $responseFactory = $builder->create(ResponseFactoryInterface::class, [ new WithReturn('createResponse', [500, ''], $response), ]); /** @var LoggerInterface|MockObject $logger */ $logger = $builder->create(LoggerInterface::class, [ new WithCallback('error', static function (string $message, array $context): void { self::assertSame('Http Exception', $message); self::assertArrayHasKey('data', $context); $data = $context['data']; self::assertSame([ 'type' => 'https://datatracker.ietf.org/doc/html/rfc2616#section-10.5.1', 'status' => 500, 'title' => 'Internal Server Error', 'detail' => null, 'instance' => null, ], $data); self::assertArrayHasKey('exceptions', $context); $exceptions = $context['exceptions']; self::assertCount(2, $exceptions); $runtimeException = $exceptions[0]; self::assertArrayHasKey('message', $runtimeException); self::assertArrayHasKey('code', $runtimeException); self::assertArrayHasKey('file', $runtimeException); self::assertArrayHasKey('line', $runtimeException); self::assertArrayHasKey('trace', $runtimeException); self::assertSame(HttpException::class, $runtimeException['class']); self::assertSame('Internal Server Error', $runtimeException['message']); self::assertSame(500, $runtimeException['code']); $logicException = $exceptions[1]; self::assertArrayHasKey('message', $logicException); self::assertArrayHasKey('code', $logicException); self::assertArrayHasKey('file', $logicException); self::assertArrayHasKey('line', $logicException); self::assertArrayHasKey('trace', $logicException); self::assertSame('LogicException', $logicException['class']); self::assertSame('logic exception', $logicException['message']); self::assertSame(42, $logicException['code']); }), ]); $middleware = new ExceptionMiddleware($responseFactory, false, $logger); self::assertSame($response, $middleware->process($request, $handler)); } public function testProcessWithExceptionWithDebugWithLogger(): void { $exception = new \RuntimeException('runtime exception', 418, new \LogicException('logic exception', 42)); $builder = new MockObjectBuilder(); /** @var MockObject|ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, []); /** @var MockObject|StreamInterface $responseBody */ $responseBody = $builder->create(StreamInterface::class, [ new WithCallback('write', static function (string $html): int { self::assertStringContainsString( '<p>A website error has occurred. Sorry for the temporary inconvenience.</p>', $html ); self::assertStringContainsString('<div><strong>Class</strong></div>', $html); self::assertStringContainsString('<div class="md:col-span-7">RuntimeException</div>', $html); self::assertStringContainsString('<div><strong>Message</strong></div>', $html); self::assertStringContainsString('<div class="md:col-span-7">runtime exception</div>', $html); self::assertStringContainsString('<div><strong>Code</strong></div>', $html); self::assertStringContainsString('<div class="md:col-span-7">418</div>', $html); self::assertStringContainsString('<div><strong>Class</strong></div>', $html); self::assertStringContainsString('<div class="md:col-span-7">LogicException</div>', $html); self::assertStringContainsString('<div><strong>Message</strong></div>', $html); self::assertStringContainsString('<div class="md:col-span-7">logic exception</div>', $html); self::assertStringContainsString('<div><strong>Code</strong></div>', $html); self::assertStringContainsString('<div class="md:col-span-7">42</div>', $html); return \strlen($html); }), ]); /** @var MockObject|ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, [ new WithReturnSelf('withHeader', ['Content-Type', 'text/html']), new WithReturn('getBody', [], $responseBody), ]); /** @var MockObject|RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, [ new WithException('handle', [$request], $exception), ]); /** @var MockObject|ResponseFactoryInterface $responseFactory */ $responseFactory = $builder->create(ResponseFactoryInterface::class, [ new WithReturn('createResponse', [500, ''], $response), ]); /** @var LoggerInterface|MockObject $logger */ $logger = $builder->create(LoggerInterface::class, [ new WithCallback('error', static function (string $message, array $context): void { self::assertSame('Http Exception', $message); self::assertArrayHasKey('data', $context); $data = $context['data']; self::assertSame([ 'type' => 'https://datatracker.ietf.org/doc/html/rfc2616#section-10.5.1', 'status' => 500, 'title' => 'Internal Server Error', 'detail' => 'A website error has occurred. Sorry for the temporary inconvenience.', 'instance' => null, ], $data); self::assertArrayHasKey('exceptions', $context); $exceptions = $context['exceptions']; self::assertCount(3, $exceptions); $exception1 = $exceptions[0]; self::assertArrayHasKey('message', $exception1); self::assertArrayHasKey('code', $exception1); self::assertArrayHasKey('file', $exception1); self::assertArrayHasKey('line', $exception1); self::assertArrayHasKey('trace', $exception1); self::assertSame(HttpException::class, $exception1['class']); self::assertSame('Internal Server Error', $exception1['message']); self::assertSame(500, $exception1['code']); $exception2 = $exceptions[1]; self::assertArrayHasKey('message', $exception2); self::assertArrayHasKey('code', $exception2); self::assertArrayHasKey('file', $exception2); self::assertArrayHasKey('line', $exception2); self::assertArrayHasKey('trace', $exception2); self::assertSame('RuntimeException', $exception2['class']); self::assertSame('runtime exception', $exception2['message']); self::assertSame(418, $exception2['code']); $exception3 = $exceptions[2]; self::assertArrayHasKey('message', $exception3); self::assertArrayHasKey('code', $exception3); self::assertArrayHasKey('file', $exception3); self::assertArrayHasKey('line', $exception3); self::assertArrayHasKey('trace', $exception3); self::assertSame('LogicException', $exception3['class']); self::assertSame('logic exception', $exception3['message']); self::assertSame(42, $exception3['code']); }), ]); $middleware = new ExceptionMiddleware($responseFactory, true, $logger); self::assertSame($response, $middleware->process($request, $handler)); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Unit/Middleware/MiddlewareRequestHandlerTest.php
tests/Unit/Middleware/MiddlewareRequestHandlerTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Unit\Middleware; use Chubbyphp\Framework\Middleware\MiddlewareRequestHandler; use Chubbyphp\Mock\MockMethod\WithCallback; use Chubbyphp\Mock\MockMethod\WithReturn; use Chubbyphp\Mock\MockObjectBuilder; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; /** * @covers \Chubbyphp\Framework\Middleware\MiddlewareRequestHandler * * @internal */ final class MiddlewareRequestHandlerTest extends TestCase { public function testHandle(): void { $builder = new MockObjectBuilder(); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, []); /** @var ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, []); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, [ new WithReturn('handle', [$request], $response), ]); /** @var MiddlewareInterface $middleware */ $middleware = $builder->create(MiddlewareInterface::class, [ new WithCallback( 'process', static fn (ServerRequestInterface $request, RequestHandlerInterface $requestHandler) => $requestHandler->handle($request) ), ]); $middlewareRequestHandler = new MiddlewareRequestHandler($middleware, $handler); self::assertSame($response, $middlewareRequestHandler->handle($request)); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Unit/Middleware/RouteMatcherMiddlewareTest.php
tests/Unit/Middleware/RouteMatcherMiddlewareTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Unit\Middleware; use Chubbyphp\Framework\Middleware\RouteMatcherMiddleware; use Chubbyphp\Framework\Router\RouteInterface; use Chubbyphp\Framework\Router\RouteMatcherInterface; use Chubbyphp\HttpException\HttpException; use Chubbyphp\Mock\MockMethod\WithException; use Chubbyphp\Mock\MockMethod\WithReturn; use Chubbyphp\Mock\MockMethod\WithReturnSelf; use Chubbyphp\Mock\MockObjectBuilder; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; /** * @covers \Chubbyphp\Framework\Middleware\RouteMatcherMiddleware * * @internal */ final class RouteMatcherMiddlewareTest extends TestCase { public function testProcess(): void { $builder = new MockObjectBuilder(); /** @var RouteInterface $route */ $route = $builder->create(RouteInterface::class, [ new WithReturn('getAttributes', [], ['key' => 'value']), ]); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, [ new WithReturnSelf('withAttribute', ['route', $route]), new WithReturnSelf('withAttribute', ['key', 'value']), ]); /** @var ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, []); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, [ new WithReturn('handle', [$request], $response), ]); /** @var RouteMatcherInterface $router */ $router = $builder->create(RouteMatcherInterface::class, [ new WithReturn('match', [$request], $route), ]); $middleware = new RouteMatcherMiddleware($router); self::assertSame($response, $middleware->process($request, $handler)); } public function testProcessWithException(): void { $httpException = HttpException::createNotFound([ 'detail' => 'The page "/" you are looking for could not be found. Check the address bar to ensure your URL is spelled correctly.', ]); $this->expectExceptionObject($httpException); $builder = new MockObjectBuilder(); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, []); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); /** @var RouteMatcherInterface $router */ $router = $builder->create(RouteMatcherInterface::class, [ new WithException('match', [$request], $httpException), ]); $middleware = new RouteMatcherMiddleware($router); $middleware->process($request, $handler); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Unit/Middleware/LazyMiddlewareTest.php
tests/Unit/Middleware/LazyMiddlewareTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Unit\Middleware; use Chubbyphp\Framework\Middleware\LazyMiddleware; use Chubbyphp\Mock\MockMethod\WithReturn; use Chubbyphp\Mock\MockObjectBuilder; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; /** * @covers \Chubbyphp\Framework\Middleware\LazyMiddleware * * @internal */ final class LazyMiddlewareTest extends TestCase { public function testProcess(): void { $builder = new MockObjectBuilder(); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, []); /** @var ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, []); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); /** @var MiddlewareInterface $originalMiddleware */ $originalMiddleware = $builder->create(MiddlewareInterface::class, [ new WithReturn('process', [$request, $handler], $response), ]); /** @var ContainerInterface $container */ $container = $builder->create(ContainerInterface::class, [ new WithReturn('get', ['serviceName'], $originalMiddleware), ]); $middleware = new LazyMiddleware($container, 'serviceName'); self::assertSame($response, $middleware->process($request, $handler)); } public function testProcessWithWrongObject(): void { $this->expectException(\TypeError::class); $this->expectExceptionMessage( 'Chubbyphp\Framework\Middleware\LazyMiddleware::process() expects service with id "serviceName"' .' to be Psr\Http\Server\MiddlewareInterface, stdClass given' ); $builder = new MockObjectBuilder(); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, []); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); $originalMiddleware = new \stdClass(); /** @var ContainerInterface $container */ $container = $builder->create(ContainerInterface::class, [ new WithReturn('get', ['serviceName'], $originalMiddleware), ]); $middleware = new LazyMiddleware($container, 'serviceName'); $middleware->process($request, $handler); } public function testProcessWithString(): void { $this->expectException(\TypeError::class); $this->expectExceptionMessage( 'Chubbyphp\Framework\Middleware\LazyMiddleware::process() expects service with id "serviceName"' .' to be Psr\Http\Server\MiddlewareInterface, string given' ); $builder = new MockObjectBuilder(); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, []); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); $originalMiddleware = ''; /** @var ContainerInterface $container */ $container = $builder->create(ContainerInterface::class, [ new WithReturn('get', ['serviceName'], $originalMiddleware), ]); $middleware = new LazyMiddleware($container, 'serviceName'); $middleware->process($request, $handler); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Unit/Middleware/SlimLazyMiddlewareTest.php
tests/Unit/Middleware/SlimLazyMiddlewareTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Unit\Middleware; use Chubbyphp\Framework\Middleware\SlimLazyMiddleware; use Chubbyphp\Mock\MockMethod\WithReturn; use Chubbyphp\Mock\MockMethod\WithReturnSelf; use Chubbyphp\Mock\MockObjectBuilder; use PHPUnit\Framework\TestCase; use Psr\Container\ContainerInterface; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; /** * @covers \Chubbyphp\Framework\Middleware\SlimLazyMiddleware * * @internal */ final class SlimLazyMiddlewareTest extends TestCase { public function testProcess(): void { $builder = new MockObjectBuilder(); /** @var ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, []); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, [ new WithReturn('getAttribute', ['response', null], null), new WithReturnSelf('withAttribute', ['response', $response]), ]); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, [ new WithReturn('handle', [$request], $response), ]); $originalMiddleware = static fn ( ServerRequestInterface $req, ResponseInterface $res, callable $next ): ResponseInterface => $next($req, $res); /** @var ContainerInterface $container */ $container = $builder->create(ContainerInterface::class, [ new WithReturn('get', ['serviceName'], $originalMiddleware), ]); /** @var ResponseFactoryInterface $responseFactory */ $responseFactory = $builder->create(ResponseFactoryInterface::class, [ new WithReturn('createResponse', [200, ''], $response), ]); $middleware = new SlimLazyMiddleware($container, 'serviceName', $responseFactory); self::assertSame($response, $middleware->process($request, $handler)); } public function testProcessWithWrongObject(): void { $this->expectException(\TypeError::class); $this->expectExceptionMessage( 'Chubbyphp\Framework\Middleware\SlimLazyMiddleware::process() expects service with id "serviceName"' .' to be callable, stdClass given' ); $builder = new MockObjectBuilder(); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, []); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); $originalMiddleware = new \stdClass(); /** @var ContainerInterface $container */ $container = $builder->create(ContainerInterface::class, [ new WithReturn('get', ['serviceName'], $originalMiddleware), ]); /** @var ResponseFactoryInterface $responseFactory */ $responseFactory = $builder->create(ResponseFactoryInterface::class, []); $middleware = new SlimLazyMiddleware($container, 'serviceName', $responseFactory); $middleware->process($request, $handler); } public function testProcessWithString(): void { $this->expectException(\TypeError::class); $this->expectExceptionMessage( 'Chubbyphp\Framework\Middleware\SlimLazyMiddleware::process() expects service with id "serviceName"' .' to be callable, string given' ); $builder = new MockObjectBuilder(); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, []); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, []); $originalMiddleware = ''; /** @var ContainerInterface $container */ $container = $builder->create(ContainerInterface::class, [ new WithReturn('get', ['serviceName'], $originalMiddleware), ]); /** @var ResponseFactoryInterface $responseFactory */ $responseFactory = $builder->create(ResponseFactoryInterface::class, []); $middleware = new SlimLazyMiddleware($container, 'serviceName', $responseFactory); $middleware->process($request, $handler); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Unit/Middleware/SlimCallbackMiddlewareTest.php
tests/Unit/Middleware/SlimCallbackMiddlewareTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Unit\Middleware; use Chubbyphp\Framework\Middleware\SlimCallbackMiddleware; use Chubbyphp\Mock\MockMethod\WithReturn; use Chubbyphp\Mock\MockMethod\WithReturnSelf; use Chubbyphp\Mock\MockObjectBuilder; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseFactoryInterface; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; /** * @covers \Chubbyphp\Framework\Middleware\SlimCallbackMiddleware * * @internal */ final class SlimCallbackMiddlewareTest extends TestCase { public function testProcessWithoutExistingResponse(): void { $builder = new MockObjectBuilder(); /** @var ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, []); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, [ new WithReturn('getAttribute', ['response', null], null), new WithReturnSelf('withAttribute', ['response', $response]), ]); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, [ new WithReturn('handle', [$request], $response), ]); /** @var ResponseFactoryInterface $responseFactory */ $responseFactory = $builder->create(ResponseFactoryInterface::class, [ new WithReturn('createResponse', [200, ''], $response), ]); $middleware = new SlimCallbackMiddleware( static function ( ServerRequestInterface $req, ResponseInterface $res, callable $next ) use ($request, $response) { self::assertSame($request, $req); self::assertSame($response, $res); return $next($req, $res); }, $responseFactory ); self::assertSame($response, $middleware->process($request, $handler)); } public function testProcessWithExistingResponse(): void { $builder = new MockObjectBuilder(); /** @var ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, []); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, [ new WithReturn('getAttribute', ['response', null], $response), new WithReturnSelf('withAttribute', ['response', $response]), ]); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, [ new WithReturn('handle', [$request], $response), ]); /** @var ResponseFactoryInterface $responseFactory */ $responseFactory = $builder->create(ResponseFactoryInterface::class, []); $middleware = new SlimCallbackMiddleware( static function ( ServerRequestInterface $req, ResponseInterface $res, callable $next ) use ($request, $response) { self::assertSame($request, $req); self::assertSame($response, $res); return $next($req, $res); }, $responseFactory ); self::assertSame($response, $middleware->process($request, $handler)); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Unit/Middleware/PipeMiddlewareTest.php
tests/Unit/Middleware/PipeMiddlewareTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Unit\Middleware; use Chubbyphp\Framework\Middleware\PipeMiddleware; use Chubbyphp\Mock\MockMethod\WithCallback; use Chubbyphp\Mock\MockMethod\WithReturn; use Chubbyphp\Mock\MockMethod\WithReturnSelf; use Chubbyphp\Mock\MockObjectBuilder; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\MiddlewareInterface; use Psr\Http\Server\RequestHandlerInterface; /** * @covers \Chubbyphp\Framework\Middleware\PipeMiddleware * * @internal */ final class PipeMiddlewareTest extends TestCase { public function testWithoutMiddlewares(): void { $builder = new MockObjectBuilder(); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, []); /** @var ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, []); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, [ new WithReturn('handle', [$request], $response), ]); $pipeMiddleware = new PipeMiddleware([]); self::assertSame($response, $pipeMiddleware->process($request, $handler)); } public function testWithMiddlewares(): void { $builder = new MockObjectBuilder(); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, [ new WithReturnSelf('withAttribute', ['middleware', 1]), new WithReturnSelf('withAttribute', ['middleware', 2]), ]); /** @var ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, []); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, [ new WithReturn('handle', [$request], $response), ]); /** @var MiddlewareInterface $middleware1 */ $middleware1 = $builder->create(MiddlewareInterface::class, [ new WithCallback( 'process', static function ( ServerRequestInterface $request, RequestHandlerInterface $requestHandler ) { $request = $request->withAttribute('middleware', 1); return $requestHandler->handle($request); }, ), ]); /** @var MiddlewareInterface $middleware2 */ $middleware2 = $builder->create(MiddlewareInterface::class, [ new WithCallback( 'process', static function ( ServerRequestInterface $request, RequestHandlerInterface $requestHandler ) { $request = $request->withAttribute('middleware', 2); return $requestHandler->handle($request); }, ), ]); $pipeMiddleware = new PipeMiddleware([$middleware1, $middleware2]); self::assertSame( $response, $pipeMiddleware->process($request, $handler) ); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Unit/Middleware/CallbackMiddlewareTest.php
tests/Unit/Middleware/CallbackMiddlewareTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Tests\Framework\Unit\Middleware; use Chubbyphp\Framework\Middleware\CallbackMiddleware; use Chubbyphp\Mock\MockMethod\WithReturn; use Chubbyphp\Mock\MockObjectBuilder; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; /** * @covers \Chubbyphp\Framework\Middleware\CallbackMiddleware * * @internal */ final class CallbackMiddlewareTest extends TestCase { public function testHandle(): void { $builder = new MockObjectBuilder(); /** @var ServerRequestInterface $request */ $request = $builder->create(ServerRequestInterface::class, []); /** @var ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, []); /** @var RequestHandlerInterface $handler */ $handler = $builder->create(RequestHandlerInterface::class, [ new WithReturn('handle', [$request], $response), ]); $middleware = new CallbackMiddleware( static fn (ServerRequestInterface $request, RequestHandlerInterface $handler) => $handler->handle($request) ); self::assertSame($response, $middleware->process($request, $handler)); } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
chubbyphp/chubbyphp-framework
https://github.com/chubbyphp/chubbyphp-framework/blob/46a3537f5c7cdecb3adedb50cabe2ed277b54954/tests/Unit/Emitter/EmitterTest.php
tests/Unit/Emitter/EmitterTest.php
<?php declare(strict_types=1); namespace Chubbyphp\Framework\Emitter { final class TestHeader { private static array $headers = []; public static function add(string $header, bool $replace = true, ?int $http_response_code = null): void { self::$headers[] = [ 'header' => $header, 'replace' => $replace, 'http_response_code' => $http_response_code, ]; } public static function all(): array { return self::$headers; } public static function reset(): void { self::$headers = []; } } function header(string $header, bool $replace = true, ?int $http_response_code = null): void { TestHeader::add($header, $replace, $http_response_code); } } namespace Chubbyphp\Tests\Framework\Unit\Emitter { use Chubbyphp\Framework\Emitter\Emitter; use Chubbyphp\Framework\Emitter\TestHeader; use Chubbyphp\Mock\MockMethod\WithCallback; use Chubbyphp\Mock\MockMethod\WithReturn; use Chubbyphp\Mock\MockObjectBuilder; use PHPUnit\Framework\TestCase; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\StreamInterface; /** * @covers \Chubbyphp\Framework\Emitter\Emitter * * @internal */ final class EmitterTest extends TestCase { public function testEmit(): void { $builder = new MockObjectBuilder(); /** @var StreamInterface $responseBody */ $responseBody = $builder->create(StreamInterface::class, [ new WithReturn('isSeekable', [], true), new WithCallback('rewind', static fn () => null), new WithReturn('eof', [], false), new WithReturn('read', [256], 'sample body'), new WithReturn('eof', [], true), ]); /** @var ResponseInterface $response */ $response = $builder->create(ResponseInterface::class, [ new WithReturn('getStatusCode', [], 200), new WithReturn('getProtocolVersion', [], '1.1'), new WithReturn('getReasonPhrase', [], 'OK'), new WithReturn('getHeaders', [], ['X-Name' => ['value1', 'value2']]), new WithReturn('getBody', [], $responseBody), ]); $emitter = new Emitter(); TestHeader::reset(); ob_start(); $emitter->emit($response); self::assertEquals([ [ 'header' => 'HTTP/1.1 200 OK', 'replace' => true, 'http_response_code' => 200, ], [ 'header' => 'X-Name: value1', 'replace' => false, 'http_response_code' => null, ], [ 'header' => 'X-Name: value2', 'replace' => false, 'http_response_code' => null, ], ], TestHeader::all()); self::assertSame('sample body', ob_get_clean()); } } }
php
MIT
46a3537f5c7cdecb3adedb50cabe2ed277b54954
2026-01-05T05:07:21.808454Z
false
nubs/random-name-generator
https://github.com/nubs/random-name-generator/blob/50abf24519badc5795a43c831f1d2a1faa45cb77/build.php
build.php
#!/usr/bin/env php <?php require 'vendor/autoload.php'; $phpcsCLI = new PHP_CodeSniffer_CLI(); $phpcsViolations = $phpcsCLI->process(['standard' => ['PSR1'], 'files' => ['src', 'tests', 'build.php']]); if ($phpcsViolations > 0) { exit(1); } $phpunitConfiguration = PHPUnit_Util_Configuration::getInstance(__DIR__ . '/phpunit.xml'); $phpunitArguments = ['coverageHtml' => __DIR__ . '/coverage', 'configuration' => $phpunitConfiguration]; $testRunner = new PHPUnit_TextUI_TestRunner(); $result = $testRunner->doRun($phpunitConfiguration->getTestSuiteConfiguration(), $phpunitArguments, false); if (!$result->wasSuccessful()) { exit(1); } $coverageReport = $result->getCodeCoverage()->getReport(); if ($coverageReport->getNumExecutedLines() !== $coverageReport->getNumExecutableLines()) { file_put_contents('php://stderr', "Code coverage was NOT 100%\n"); exit(1); } file_put_contents('php://stderr', "Code coverage was 100%\n");
php
MIT
50abf24519badc5795a43c831f1d2a1faa45cb77
2026-01-05T05:07:30.227583Z
false
nubs/random-name-generator
https://github.com/nubs/random-name-generator/blob/50abf24519badc5795a43c831f1d2a1faa45cb77/src/AbstractGenerator.php
src/AbstractGenerator.php
<?php namespace Nubs\RandomNameGenerator; abstract class AbstractGenerator implements Generator { /** * Alias for getName so that the generator can be directly stringified. * * Note that this will return a different name everytime it is cast to a * string. * * @api * @return string A random name. */ public function __toString() { return $this->getName(); } }
php
MIT
50abf24519badc5795a43c831f1d2a1faa45cb77
2026-01-05T05:07:30.227583Z
false
nubs/random-name-generator
https://github.com/nubs/random-name-generator/blob/50abf24519badc5795a43c831f1d2a1faa45cb77/src/Alliteration.php
src/Alliteration.php
<?php namespace Nubs\RandomNameGenerator; use Cinam\Randomizer\Randomizer; /** * Defines an alliterative name generator. */ class Alliteration extends AbstractGenerator implements Generator { /** @type array The definition of the potential adjectives. */ protected $_adjectives; /** @type array The definition of the potential nouns. */ protected $_nouns; /** @type Cinam\Randomizer\Randomizer The random number generator. */ protected $_randomizer; /** * Initializes the Alliteration Generator with the default word lists. * * @api * @param \Cinam\Randomizer\Randomizer $randomizer The random number generator. */ public function __construct(Randomizer $randomizer = null) { $this->_randomizer = $randomizer; $this->_adjectives = file(__DIR__ . '/adjectives.txt', FILE_IGNORE_NEW_LINES); $this->_nouns = file(__DIR__ . '/nouns.txt', FILE_IGNORE_NEW_LINES); } /** * Gets a randomly generated alliterative name. * * @api * @return string A random alliterative name. */ public function getName() { $adjective = $this->_getRandomWord($this->_adjectives); $noun = $this->_getRandomWord($this->_nouns, $adjective[0]); return ucwords("{$adjective} {$noun}"); } /** * Get a random word from the list of words, optionally filtering by starting letter. * * @param array $words An array of words to choose from. * @param string $startingLetter The desired starting letter of the word. * @return string The random word. */ protected function _getRandomWord(array $words, $startingLetter = null) { $wordsToSearch = $startingLetter === null ? $words : preg_grep("/^{$startingLetter}/", $words); return $this->_randomizer ? $this->_randomizer->getArrayValue($wordsToSearch) : $wordsToSearch[array_rand($wordsToSearch)]; } }
php
MIT
50abf24519badc5795a43c831f1d2a1faa45cb77
2026-01-05T05:07:30.227583Z
false
nubs/random-name-generator
https://github.com/nubs/random-name-generator/blob/50abf24519badc5795a43c831f1d2a1faa45cb77/src/Vgng.php
src/Vgng.php
<?php namespace Nubs\RandomNameGenerator; use Cinam\Randomizer\Randomizer; /** * Defines a video game name generator based off of * https://github.com/nullpuppy/vgng which in turn is based off of * http://videogamena.me/vgng.js. */ class Vgng extends AbstractGenerator implements Generator { /** @type array The definition of the potential names. */ protected $_definitionSets; /** @type Cinam\Randomizer\Randomizer The random number generator. */ protected $_randomizer; /** * Initializes the Video Game Name Generator from the default word list. * * @api * @param \Cinam\Randomizer\Randomizer $randomizer The random number generator. */ public function __construct(Randomizer $randomizer = null) { $this->_randomizer = $randomizer; $this->_definitionSets = array_map( [$this, '_parseSection'], $this->_getSections($this->_getFileContents()) ); } /** * Gets a randomly generated video game name. * * @api * @return string A random video game name. */ public function getName() { $similarWords = []; $words = []; foreach ($this->_definitionSets as $definitionSet) { $word = $this->_getUniqueWord($definitionSet, $similarWords); $words[] = $word['word']; $similarWords[] = $word['word']; $similarWords = array_merge($similarWords, $word['similarWords']); } return implode(' ', $words); } /** * Get a definition from the definitions that does not exist already. * * @param array $definitions The word list to pick from. * @param array $existingWords The already-chosen words to avoid. * @return array The definition of a previously unchosen word. */ protected function _getUniqueWord(array $definitions, array $existingWords) { $definition = $this->_randomizer ? $this->_randomizer->getArrayValue($definitions) : $definitions[array_rand($definitions)]; if (array_search($definition['word'], $existingWords) === false) { return $definition; } return $this->_getUniqueWord($definitions, $existingWords); } /** * Gets the file contents of the video_game_names.txt file. * * @return string The video_game_names.txt contents. */ protected function _getFileContents() { return file_get_contents(__DIR__ . '/video_game_names.txt'); } /** * Separates the contents into each of the word list sections. * * This builder operates by picking a random word from each of a consecutive * list of word lists. These separate lists are separated by a line * consisting of four hyphens in the file. * * @param string $contents The file contents. * @return array Each section split into its own string. */ protected function _getSections($contents) { return array_map('trim', explode('----', $contents)); } /** * Parses the given section into the final definitions. * * @param string $section The newline-separated list of words in a section. * @return array The parsed section into its final form. */ protected function _parseSection($section) { return array_map( [$this, '_parseDefinition'], $this->_getDefinitionsFromSection($section) ); } /** * Gets the separate definitions from the given section. * * @param string $section The newline-separated list of words in a section. * @return array Each word split out, but unparsed. */ protected function _getDefinitionsFromSection($section) { return array_map('trim', explode("\n", $section)); } /** * Parses a single definition into its component pieces. * * The format of a definition in a file is word[^similarWord|...]. * * @param string $definition The definition. * @return array The formatted definition. */ protected function _parseDefinition($definition) { $word = strtok($definition, '^'); $similarWords = array_filter(explode('|', strtok('^'))); return ['word' => $word, 'similarWords' => $similarWords]; } }
php
MIT
50abf24519badc5795a43c831f1d2a1faa45cb77
2026-01-05T05:07:30.227583Z
false
nubs/random-name-generator
https://github.com/nubs/random-name-generator/blob/50abf24519badc5795a43c831f1d2a1faa45cb77/src/All.php
src/All.php
<?php namespace Nubs\RandomNameGenerator; use Cinam\Randomizer\Randomizer; /** * A generator that uses all of the other generators randomly. */ class All extends AbstractGenerator implements Generator { /** @type array The other generators to use. */ protected $_generators; /** @type Cinam\Randomizer\Randomizer The random number generator. */ protected $_randomizer; /** * Initializes the All Generator with the list of generators to choose from. * * @api * @param array $generators The random generators to use. * @param \Cinam\Randomizer\Randomizer $randomizer The random number generator. */ public function __construct(array $generators, Randomizer $randomizer = null) { $this->_generators = $generators; $this->_randomizer = $randomizer; } /** * Constructs an All Generator using the default list of generators. * * @api * @param \Cinam\Randomizer\Randomizer $randomizer The random number generator. * @return \Nubs\RandomNameGenerator\All The constructed generator. */ public static function create(Randomizer $randomizer = null) { return new self([new Alliteration($randomizer), new Vgng($randomizer)], $randomizer); } /** * Gets a randomly generated name using the configured generators. * * @api * @return string A random name. */ public function getName() { return $this->_getRandomGenerator()->getName(); } /** * Get a random generator from the list of generators. * * @return \Nubs\RandomNameGenerator\Generator A random generator. */ protected function _getRandomGenerator() { return $this->_randomizer ? $this->_randomizer->getArrayValue($this->_generators) : $this->_generators[array_rand($this->_generators)]; } }
php
MIT
50abf24519badc5795a43c831f1d2a1faa45cb77
2026-01-05T05:07:30.227583Z
false
nubs/random-name-generator
https://github.com/nubs/random-name-generator/blob/50abf24519badc5795a43c831f1d2a1faa45cb77/src/Generator.php
src/Generator.php
<?php namespace Nubs\RandomNameGenerator; /** * Defines the standard interface for all the random name generators. */ interface Generator { /** * Gets a randomly generated name. * * @api * @return string A random name. */ public function getName(); }
php
MIT
50abf24519badc5795a43c831f1d2a1faa45cb77
2026-01-05T05:07:30.227583Z
false
nubs/random-name-generator
https://github.com/nubs/random-name-generator/blob/50abf24519badc5795a43c831f1d2a1faa45cb77/tests/VgngTest.php
tests/VgngTest.php
<?php namespace Nubs\RandomNameGenerator; use PHPUnit\Framework\TestCase; use Cinam\Randomizer\Randomizer; /** * @coversDefaultClass \Nubs\RandomNameGenerator\Vgng * @covers ::<protected> */ class VgngTest extends TestCase { /** * Verify that getName returns the expected name. * * @test * @covers ::__construct * @covers ::getName */ public function getNameBasic() { $numberGenerator = $this->createMock('\Cinam\Randomizer\NumberGenerator'); $numberGenerator->expects($this->exactly(3))->method('getInt')->will($this->returnValue(1)); $randomizer = new Randomizer($numberGenerator); $vgng = new Vgng($randomizer); $this->assertSame('8-Bit Acid - 3rd Strike', $vgng->getName()); } /** * Verify that getName returns a name without similar strings. * * @test * @covers ::__construct * @covers ::getName */ public function getNameSimilarName() { $numberGenerator = $this->createMock('\Cinam\Randomizer\NumberGenerator'); $numberGenerator->expects($this->exactly(4))->method('getInt')->will($this->onConsecutiveCalls(0, 0, 2, 10)); $randomizer = new Randomizer($numberGenerator); $vgng = new Vgng($randomizer); $this->assertSame('3D Aerobics Academy', $vgng->getName()); } /** * Verify that toString returns the expected name. * * @test * @covers ::__construct * @covers ::__toString * @covers ::getName */ public function toStringBasic() { $numberGenerator = $this->createMock('\Cinam\Randomizer\NumberGenerator'); $numberGenerator->expects($this->exactly(3))->method('getInt')->will($this->returnValue(1)); $randomizer = new Randomizer($numberGenerator); $vgng = new Vgng($randomizer); $this->assertSame('8-Bit Acid - 3rd Strike', (string)$vgng); } }
php
MIT
50abf24519badc5795a43c831f1d2a1faa45cb77
2026-01-05T05:07:30.227583Z
false
nubs/random-name-generator
https://github.com/nubs/random-name-generator/blob/50abf24519badc5795a43c831f1d2a1faa45cb77/tests/AllTest.php
tests/AllTest.php
<?php namespace Nubs\RandomNameGenerator; use PHPUnit\Framework\TestCase; use Cinam\Randomizer\Randomizer; /** * @coversDefaultClass \Nubs\RandomNameGenerator\All * @covers ::<protected> */ class AllTest extends TestCase { /** * Verify basic behavior of getName(). * * @test * @covers ::__construct * @covers ::create * @covers ::getName * @uses \Nubs\RandomNameGenerator\Alliteration * @uses \Nubs\RandomNameGenerator\Vgng * * @return void */ public function getNameBasic() { $generator = All::create(); $name = $generator->getName(); $this->assertRegexp('/.+/', $name); } /** * Verify basic behavior of getName() with a forced random generator. * * @test * @covers ::__construct * @covers ::create * @covers ::getName * @uses \Nubs\RandomNameGenerator\Alliteration * * @return void */ public function getNameForced() { $numberGenerator = $this->createMock('\Cinam\Randomizer\NumberGenerator'); $numberGenerator->expects($this->exactly(2))->method('getInt')->will($this->onConsecutiveCalls(20, 5)); $randomizer = new Randomizer($numberGenerator); $generator = new All([new Alliteration($randomizer)]); $this->assertSame('Black Bear', $generator->getName()); } /** * Verify basic behavior of __toString(). * * @test * @covers ::__construct * @covers ::create * @covers ::__toString * @covers ::getName * @uses \Nubs\RandomNameGenerator\Alliteration * @uses \Nubs\RandomNameGenerator\Vgng * * @return void */ public function toStringBasic() { $generator = All::create(); $name = (string)$generator; $this->assertRegexp('/.+/', $name); } }
php
MIT
50abf24519badc5795a43c831f1d2a1faa45cb77
2026-01-05T05:07:30.227583Z
false
nubs/random-name-generator
https://github.com/nubs/random-name-generator/blob/50abf24519badc5795a43c831f1d2a1faa45cb77/tests/AlliterationTest.php
tests/AlliterationTest.php
<?php namespace Nubs\RandomNameGenerator; use PHPUnit\Framework\TestCase; use Cinam\Randomizer\Randomizer; use Cinam\Randomizer\NumberGenerator; /** * @coversDefaultClass \Nubs\RandomNameGenerator\Alliteration * @covers ::<protected> */ class AlliterationTest extends TestCase { /** * Verify basic behavior of getName(). * * @test * @covers ::__construct * @covers ::getName * * @return void */ public function getNameBasic() { $generator = new Alliteration(); $parts = explode(' ', $generator->getName()); $this->assertCount(2, $parts); $this->assertSame($parts[0][0], $parts[1][0]); } /** * Verify basic behavior of getName() with a forced random generator. * * @test * @covers ::__construct * @covers ::getName * * @return void */ public function getNameForced() { $numberGenerator = $this->createMock(NumberGenerator::class); $numberGenerator->expects($this->exactly(2))->method('getInt')->will($this->onConsecutiveCalls(20, 5)); $randomizer = new Randomizer($numberGenerator); $generator = new Alliteration($randomizer); $this->assertSame('Black Bear', $generator->getName()); } /** * Verify basic behavior of __toString(). * * @test * @covers ::__construct * @covers ::__toString * @covers ::getName * * @return void */ public function toStringBasic() { $generator = new Alliteration(); $parts = explode(' ', (string)$generator); $this->assertCount(2, $parts); $this->assertSame($parts[0][0], $parts[1][0]); } }
php
MIT
50abf24519badc5795a43c831f1d2a1faa45cb77
2026-01-05T05:07:30.227583Z
false