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
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Handler/Pcntl/WaitResult.php
src/Handler/Pcntl/WaitResult.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Handler\Pcntl; /** * A result object returned from Pcntl::wait. * * This encapsulates the "was the process successful?" question as well as provides * a way to access the exit code of the process. * * @since 4.1 * @internal */ final class WaitResult { private $exitCode; public function __construct(int $exitCode) { $this->exitCode = $exitCode; } public function successful() : bool { return 0 === $this->exitCode; } public function getExitCode() : int { return $this->exitCode; } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Handler/Pcntl/Pcntl.php
src/Handler/Pcntl/Pcntl.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Handler\Pcntl; use PMG\Queue\Exception\AbnormalExit; /** * A very thin wrapper around the the `pcntl_*` functions and `exit` to deal * with forking processes. This exists simply so we can mock it and validate that * `PcntlForkingHandler` works. * * @since 3.1 * @internal */ class Pcntl { public function __construct() { // @codeCoverageIgnoreStart if (!function_exists('pcntl_fork')) { throw new \RuntimeException(sprintf('%s can only be used if the pcntl extension is loaded', __CLASS__)); } // @codeCoverageIgnoreEnd } /** * Fork a new process and return the current processes ID. In the parent thead * this will be the child process' ID and the child thread will see a `0`. * * @return int */ public function fork() : int { return @pcntl_fork(); } /** * Wait for the child process to finish and report wether its exit status * was successful or not. If the child process exits normally this is * will return a bool. If there was a non-normal exit (like a segfault) * this will throw. * * @return bool True if the child existed successfully. */ public function wait($child) : WaitResult { pcntl_waitpid($child, $status, WUNTRACED); if (pcntl_wifexited($status)) { return new WaitResult(pcntl_wexitstatus($status)); } throw AbnormalExit::fromWaitStatus($status); } /** * Quit the current process by calling `exit`. The exit code is defined by * whather the $succesful value is true. * * @param bool $successful If true `exit(0)` otherwise `exit(1)` * @return void */ public function quit($successful) : void { exit($successful ? 0 : 1); } /** * Deliver a signal to a process. * * @param $child The process to signal * @param $sig The signal to send. * @return void */ public function signal(int $child, int $sig) : void { posix_kill($child, $sig); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Exception/AbnormalExit.php
src/Exception/AbnormalExit.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Exception; use PMG\Queue\QueueException; /** * Thrown by the `Pcntl` utility when a child process does not have a * normal exit. When this happens it's treated as a message handling failure, * just like an unsuccessful exit would be. * * @since 3.2.0 */ final class AbnormalExit extends \RuntimeException implements QueueException { public static function fromWaitStatus($status) { if (pcntl_wifstopped($status)) { return new self(sprintf( 'Child process was stopped with %s signal', pcntl_wstopsig($status) )); } if (pcntl_wifsignaled($status)) { return new self(sprintf( 'Child process was terminated with %s signal', pcntl_wtermsig($status) )); } return new self(sprintf( 'Child process exited abnormally (wait status: %s)', $status )); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Exception/MissingSignature.php
src/Exception/MissingSignature.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Exception; /** * Thrown when a serializer is asked to unserialize a message that does not have * a signature to authenticate it. * * @since 4.0 */ final class MissingSignature extends SerializationError { // noop }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Exception/QueueNotFound.php
src/Exception/QueueNotFound.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Exception; use PMG\Queue\QueueException; /** * Thrown when a queue cannot be located for a message. * * @since 2.0 */ final class QueueNotFound extends \RuntimeException implements QueueException { // noop }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Exception/DriverError.php
src/Exception/DriverError.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Exception; use PMG\Queue\QueueException; /** * Marker interface for errors from drivers. When this is thrown the queue system * assumes something is wrong with the driver itself and so every job should be * retried. * * @since 2.0 */ interface DriverError extends QueueException { }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Exception/InvalidSignature.php
src/Exception/InvalidSignature.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Exception; /** * Throw by serializers when the signature of a message cannot be verified. * * @since 4.0 */ final class InvalidSignature extends SerializationError { // noop }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Exception/ForkedProcessCancelled.php
src/Exception/ForkedProcessCancelled.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Exception; /** * Thrown by the `PcntlForkingHandler` when the child process is cancelled. * * @since 4.0 */ final class ForkedProcessCancelled extends \RuntimeException implements ShouldReleaseMessage { // noop }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Exception/SerializationError.php
src/Exception/SerializationError.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Exception; use PMG\Queue\QueueException; /** * Thrown when there's some trouble serializing or unserializing messages. * * @since 2.0 */ class SerializationError extends \RuntimeException implements DriverError { }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Exception/SimpleMustStop.php
src/Exception/SimpleMustStop.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Exception; /** * A simple must stop exception. Uses in tests. * * @since 2.0 */ final class SimpleMustStop extends \RuntimeException implements MustStop { // noop }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Exception/ForkedProcessFailed.php
src/Exception/ForkedProcessFailed.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Exception; use PMG\Queue\QueueException; /** * Thrown by the `PcntlForkingHandler` when the child process exits unsuccessfully. * * @since 4.0 */ final class ForkedProcessFailed extends \RuntimeException implements QueueException { public static function withExitCode(int $exitCode) : self { return new self(sprintf('exit code %d', $exitCode), $exitCode); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Exception/InvalidEnvelope.php
src/Exception/InvalidEnvelope.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Exception; /** * Thrown when an envelope for a driver isn't of the expected type. * * @since 2.0 */ final class InvalidEnvelope extends \InvalidArgumentException implements DriverError { // noop }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Exception/NotAnEnvelope.php
src/Exception/NotAnEnvelope.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Exception; /** * Thrown when a serializer unserializes something other than an envelope. This * can happen simply because `unserialize` (which is what `NativeSerializer` uses) * can end up unserializing anything. * * @since 4.0 */ final class NotAnEnvelope extends SerializationError { // noop }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Exception/ShouldReleaseMessage.php
src/Exception/ShouldReleaseMessage.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Exception; use PMG\Queue\QueueException; /** * A marker interface for exceptions that instructs consumers to release the * message that causes the error. * * This is useful for async handlers which may cancel things and need a way to * tell the consumers that the exception thrown from `Promise::wait` was intentional * in some way. * * @since 4.0 */ interface ShouldReleaseMessage extends QueueException { // noop }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Exception/CouldNotFork.php
src/Exception/CouldNotFork.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Exception; /** * Thrown by the `PcntlForkingHandler` when a call to `pcntl_fork` fails. This is * a `MustStop` exception that tells the consumer to unsuccessfully exit. Since a * failure to fork likely means some sort of resource exhausting the exit should * clean things up and hopefully do better the next time. * * @since 3.1.0 */ final class CouldNotFork extends \RuntimeException implements MustStop { public static function fromLastError() { $err = error_get_last(); return new self(sprintf( 'Could not fork child process to execute message: %s', isset($err['message']) ? $err['message'] : 'Unknown error' ), 1); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Exception/InvalidArgumentException.php
src/Exception/InvalidArgumentException.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Exception; use PMG\Queue\QueueException; /** * Extend `InvalidArgumentException` so we can marker interface it. * * @since 2.0 */ final class InvalidArgumentException extends \InvalidArgumentException implements QueueException { public static function assertNotEmpty($value, string $message) { if (empty($value)) { throw new self($message); } } public static function assert(bool $ok, string $message, int $code=0) : void { if (!$ok) { throw new self($message, $code); } } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/src/Exception/MustStop.php
src/Exception/MustStop.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Exception; use PMG\Queue\QueueException; /** * A marker interface for exceptions thrown to indicate the consumer must exit * when it's running. * * These are a way to gracefully stop a queue. For example, if you've updated * code, putting a job in the queue that throws a MustStop would be a way to * stop the queue and have its process manager automatically restart it. * * @since 2.0 */ interface MustStop extends QueueException { // noop }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/bootstrap.php
test/bootstrap.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) 2014 PMG Worldwide * * @package PMGQueue * @copyright 2014 PMG Worldwide * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ $loader = require __DIR__.'/../vendor/autoload.php'; $loader->addPsr4('PMG\\Queue\\', __DIR__.'/unit'); $loader->addPsr4('PMG\\Queue\\', __DIR__.'/integration');
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/integration/ProducerOtelIntTest.php
test/integration/ProducerOtelIntTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; use LogicException; use OpenTelemetry\API\Trace\SpanKind; use OpenTelemetry\API\Trace\StatusCode; use OpenTelemetry\SemConv\TraceAttributes; use PMG\Queue\Otel\PmgQueueInstrumentation; use PMG\Queue\Exception\SimpleMustStop; /** * @requires extension opentelemetry */ class ProducerOtelIntTest extends OtelIntegrationTestCase { const Q = 'test'; private Driver $driver; private Producer $producer; public function testSendingMessagesProducesSpans() : void { $this->producer->send(new SimpleMessage('test')); $this->assertCount(1, $this->spans); $span = $this->spans[0]; $this->assertSame(self::Q.' publish', $span->getName()); $status = $span->getStatus(); $this->assertSame(StatusCode::STATUS_UNSET, $status->getCode()); $attr = $span->getAttributes(); $this->assertSame(self::Q, $attr->get(TraceAttributes::MESSAGING_DESTINATION_NAME)); $this->assertSame('publish', $attr->get(PmgQueueInstrumentation::OPERATION_TYPE)); $this->assertSame('enqueue', $attr->get(PmgQueueInstrumentation::OPERATION_NAME)); } public function testErrorsDuringSendMarkSpansAsErrored() : void { $driver = $this->createMock(Driver::class); $driver->expects($this->once()) ->method('enqueue') ->willThrowException(new LogicException('ope')); $producer = new DefaultProducer( $driver, new Router\SimpleRouter(self::Q) ); $e = null; try { $producer->send(new SimpleMessage('test')); } catch (LogicException $e) { } $this->assertInstanceOf(LogicException::class, $e); $this->assertCount(1, $this->spans); $span = $this->spans[0]; $this->assertSame(self::Q.' publish', $span->getName()); $status = $span->getStatus(); $this->assertSame(StatusCode::STATUS_ERROR, $status->getCode()); $this->assertSame('ope', $status->getDescription()); } protected function setUp() : void { parent::setUp(); $this->driver = new Driver\MemoryDriver(); $this->producer = new DefaultProducer( $this->driver, new Router\SimpleRouter(self::Q) ); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/integration/ConsumerOtelIntTest.php
test/integration/ConsumerOtelIntTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; use OpenTelemetry\API\Trace\SpanKind; use OpenTelemetry\API\Trace\StatusCode; use OpenTelemetry\SemConv\TraceAttributes; use PMG\Queue\Otel\PmgQueueInstrumentation; use PMG\Queue\Exception\SimpleMustStop; /** * @requires extension opentelemetry */ class ConsumerOtelIntTest extends OtelIntegrationTestCase { const Q = 'test'; private Driver $driver; private Producer $producer; public function testConsumerOnceEmitsSpansWhenNoMessagesAreHandled() : void { $called = false; $consumer = $this->createConsumer(function () use (&$called) { $called = true; return false; }); $result = $consumer->once(self::Q); $this->assertNull($result); $this->assertFalse($called); $this->assertCount(1, $this->spans); $span = $this->spans[0]; $this->assertSame(self::Q.' empty-receive', $span->getName()); $attr = $span->getAttributes(); $this->assertSame(self::Q, $attr->get(TraceAttributes::MESSAGING_DESTINATION_NAME)); $this->assertSame('receive', $attr->get(PmgQueueInstrumentation::OPERATION_TYPE)); $this->assertSame('once', $attr->get(PmgQueueInstrumentation::OPERATION_NAME)); } public function testSuccessfullyHandledMessagesDoNotSetSpanStatusCode() : void { // this will produce a span $this->producer->send(new SimpleMessage('test')); $called = false; $consumer = $this->createConsumer(function () use (&$called) : bool { $called = true; return true; }); $result = $consumer->once(self::Q); $this->assertTrue($result); $this->assertTrue($called); $this->assertCount(2, $this->spans, 'one span for the enqueue one for consume'); $span = $this->spans[1]; $this->assertSame(self::Q.' receive', $span->getName()); $status = $span->getStatus(); $this->assertSame(StatusCode::STATUS_UNSET, $status->getCode()); } public function testUnsuccessfulMessagesSetSpanStatusAsErrored() : void { $this->producer->send(new SimpleMessage('test')); $called = false; $consumer = $this->createConsumer(function () use (&$called) : bool { $called = true; return false; }); $result = $consumer->once(self::Q); $this->assertFalse($result); $this->assertTrue($called); $this->assertCount(2, $this->spans, 'one span for the enqueue one for consume'); $span = $this->spans[1]; $this->assertSame(self::Q.' receive', $span->getName()); $status = $span->getStatus(); $this->assertSame(StatusCode::STATUS_ERROR, $status->getCode()); $this->assertStringContainsStringIgnoringCase( 'not handled successfully', $status->getDescription() ); } public function testErrorsDuringOnceMarkSpanAsErrored() : void { // this will produce a span $this->producer->send(new SimpleMessage('test')); $consumer = $this->createConsumer(function () { throw new SimpleMustStop('oh noz'); }); $e = null; try { $consumer->once(self::Q); } catch (SimpleMustStop $e) { } $this->assertInstanceOf(SimpleMustStop::class, $e); $this->assertCount(2, $this->spans, 'one span for the enqueue one for consume'); $span = $this->spans[1]; $this->assertSame(self::Q.' receive', $span->getName()); $status = $span->getStatus(); $this->assertSame(StatusCode::STATUS_ERROR, $status->getCode()); $this->assertSame('oh noz', $status->getDescription()); } protected function setUp() : void { parent::setUp(); $this->driver = new Driver\MemoryDriver(); $this->producer = new DefaultProducer( $this->driver, new Router\SimpleRouter(self::Q) ); } private function createConsumer(callable $handler) : DefaultConsumer { return new DefaultConsumer( $this->driver, new Handler\CallableHandler($handler), new Retry\NeverSpec() ); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/integration/OtelIntegrationTestCase.php
test/integration/OtelIntegrationTestCase.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; use ArrayObject; use OpenTelemetry\API\Instrumentation\Configurator; use OpenTelemetry\API\Trace\Propagation\TraceContextPropagator; use OpenTelemetry\API\Baggage\Propagation\BaggagePropagator; use OpenTelemetry\Context\ScopeInterface; use OpenTelemetry\Context\Propagation\MultiTextMapPropagator; use OpenTelemetry\SDK\Trace\ImmutableSpan; use OpenTelemetry\SDK\Trace\SpanExporter\InMemoryExporter; use OpenTelemetry\SDK\Trace\SpanProcessor\SimpleSpanProcessor; use OpenTelemetry\SDK\Trace\TracerProvider; abstract class OtelIntegrationTestCase extends IntegrationTestCase { private ScopeInterface $scope; /** * @var ArrayObject<int, ImmutableSpan> $storage */ protected ArrayObject $spans; protected function setUp(): void { $this->spans = new ArrayObject(); $tracerProvider = new TracerProvider( new SimpleSpanProcessor( new InMemoryExporter($this->spans) ) ); $propagator = new MultiTextMapPropagator([ TraceContextPropagator::getInstance(), BaggagePropagator::getInstance(), ]); $this->scope = Configurator::create() ->withTracerProvider($tracerProvider) ->withPropagator($propagator) ->activate(); } protected function tearDown(): void { $this->scope->detach(); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/integration/ForkingHandlerIntTest.php
test/integration/ForkingHandlerIntTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; /** * @requires function pcntl_async_signals */ class ForkingHandlerIntTest extends IntegrationTestCase { private $driver, $producer; /** * @group slow */ public function testMessagesCanBeCancelledWhileInProgressFromConsumerStop() { $this->producer->send(new SimpleMessage('TestMessage')); $consumer = $this->createConsumer(function () { sleep(100); }); pcntl_signal(SIGALRM, function () use ($consumer) { $consumer->stop(1); }); pcntl_alarm(5); $exitCode = $consumer->run('q'); $this->assertSame(1, $exitCode); } protected function setUp() : void { pcntl_signal(SIGALRM, SIG_DFL); pcntl_async_signals(true); $this->driver = new Driver\MemoryDriver(); $this->producer = new DefaultProducer( $this->driver, new Router\SimpleRouter('q') ); } private function createConsumer(callable $handler) : DefaultConsumer { return new DefaultConsumer( $this->driver, new Handler\PcntlForkingHandler(new Handler\CallableHandler($handler)), new Retry\NeverSpec() ); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/integration/IntegrationTestCase.php
test/integration/IntegrationTestCase.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; abstract class IntegrationTestCase extends \PHPUnit\Framework\TestCase { // noop }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/integration/Serializer/SodiumCryptoAuthNativeSerializerTest.php
test/integration/Serializer/SodiumCryptoAuthNativeSerializerTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Serializer; use PMG\Queue\Envelope; use PMG\Queue\DefaultEnvelope; use PMG\Queue\SimpleMessage; use PMG\Queue\Exception\SerializationError; use PMG\Queue\Signer\SodiumCryptoAuth; class SodiumCryptoAuthNativeSerializerTest extends SerializerIntegrationTestCase { protected function createSerializer() : Serializer { return new NativeSerializer(new SodiumCryptoAuth(str_repeat('test', 8))); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/integration/Serializer/SerializerIntegrationTestCase.php
test/integration/Serializer/SerializerIntegrationTestCase.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Serializer; use PMG\Queue\Envelope; use PMG\Queue\DefaultEnvelope; use PMG\Queue\SimpleMessage; use PMG\Queue\Exception\SerializationError; use PMG\Queue\Signer\HmacSha256; /** * Covers the basic cases serializers. This exists so we can test they they * play nice with the various signers. */ abstract class SerializerIntegrationTestCase extends \PMG\Queue\IntegrationTestCase { protected Serializer $serializer; protected DefaultEnvelope $env; public function testSerializeReturnsAStringThatCanBeUnserialized() { $s = $this->serializer->serialize($this->env); $this->assertIsString($s); $env = $this->serializer->unserialize($s); $this->assertEquals($this->env, $env); } public function testUnserializeErrorsWhenAnUnsignedStringIsGiven() { $this->expectException(SerializationError::class); $this->expectExceptionMessage('does not have a signature'); $this->serializer->unserialize(base64_encode(serialize($this->env))); } public function testUnserializeErrorsWhenTheMessageDataHasBeenTamperedWith() { $this->expectException(SerializationError::class); $this->expectExceptionMessage('Invalid Message Signature'); $s = explode('|', $this->serializer->serialize($this->env), 2); $s[1] = base64_encode(serialize(new \stdClass)); $str = implode('|', $s); $this->serializer->unserialize($str); } protected function setUp() : void { $this->serializer = $this->createSerializer(); $this->env = new DefaultEnvelope(new SimpleMessage('t')); } abstract protected function createSerializer() : Serializer; }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/integration/Serializer/HmacSha256NativeSerializerTest.php
test/integration/Serializer/HmacSha256NativeSerializerTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Serializer; use PMG\Queue\Envelope; use PMG\Queue\DefaultEnvelope; use PMG\Queue\SimpleMessage; use PMG\Queue\Exception\SerializationError; use PMG\Queue\Signer\HmacSha256; class HmacSha256NativeSerializerTest extends SerializerIntegrationTestCase { const KEY = 'SuperSecretKey'; public static function notStrings() { return [ [['an array']], [new \stdClass], [1], [1.0], [null], [false], ]; } /** * @group regression * @dataProvider notStrings */ public function testSerializersCannotBeCreatedWithANonStringKey($key) { $this->expectException(\TypeError::class); NativeSerializer::fromSigningKey($key); } public function testSerializersCannotBeCreatedWithEmptyKeys() { $this->expectException(\InvalidArgumentException::class); $this->expectExceptionMessage('$key cannot be empty'); NativeSerializer::fromSigningKey(''); } /** * @group regresion */ public function testMessagesSerializedInVersion2xCanStillBeUnserialized() { $oldMessage = 'bbb07fc3841b8114978c60bddcf61d3f0d167887250696a7974502f8ce42d136|TzoyNToiUE1HXFF1ZXVlXERlZmF1bHRFbnZlbG9wZSI6Mjp7czoxMDoiACoAbWVzc2FnZSI7TzoyMzoiUE1HXFF1ZXVlXFNpbXBsZU1lc3NhZ2UiOjI6e3M6Mjk6IgBQTUdcUXVldWVcU2ltcGxlTWVzc2FnZQBuYW1lIjtzOjE6InQiO3M6MzI6IgBQTUdcUXVldWVcU2ltcGxlTWVzc2FnZQBwYXlsb2FkIjtOO31zOjExOiIAKgBhdHRlbXB0cyI7aTowO30='; $env = $this->serializer->unserialize($oldMessage); $this->assertEquals($this->env, $env); } protected function createSerializer() : Serializer { return NativeSerializer::fromSigningKey(self::KEY); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/DefaultProducerTest.php
test/unit/DefaultProducerTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; use PMG\Queue\Exception\QueueNotFound; class DefaultProducerTest extends UnitTestCase { private $router, $driver, $producer; public function testProducerRoutesMessageAndPutsItIntoAQueue() { $msg = new SimpleMessage('test'); $this->router->expects($this->once()) ->method('queueFor') ->with($this->identicalTo($msg)) ->willReturn('testq'); $this->driver->expects($this->once()) ->method('enqueue') ->with('testq', $this->identicalTo($msg)); $this->producer->send($msg); } public function testProducerErrorsWhenNoQueueIsFound() { $this->expectException(QueueNotFound::class); $msg = new SimpleMessage('test'); $this->router->expects($this->once()) ->method('queueFor') ->with($this->identicalTo($msg)) ->willReturn(null); $this->driver->expects($this->never()) ->method('enqueue'); $this->producer->send($msg); } public function testProducerUnwrapsEnvelopsToDetermineRouteThenPassesEnvelopeToTheDriver() { $msg = new SimpleMessage('test'); $env = new DefaultEnvelope($msg); $this->router->expects($this->once()) ->method('queueFor') ->with($this->identicalTo($msg)) ->willReturn('q'); $this->driver->expects($this->once()) ->method('enqueue') ->with('q', $this->identicalTo($env)); $this->producer->send($env); } public function testEnvelopeWithMessageMissingQueueCausesError() { $this->expectException(QueueNotFound::class); $msg = new SimpleMessage('test'); $env = new DefaultEnvelope($msg); $this->router->expects($this->once()) ->method('queueFor') ->with($this->identicalTo($msg)) ->willReturn(null); $this->driver->expects($this->never()) ->method('enqueue'); $this->producer->send($env); } protected function setUp() : void { $this->router = $this->createMock(Router::class); $this->driver = $this->createMock(Driver::class); $this->producer = new DefaultProducer($this->driver, $this->router); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/CollectingLogger.php
test/unit/CollectingLogger.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; final class CollectingLogger extends \Psr\Log\AbstractLogger { private $messages = []; public function log($level, $msg, array $context=array()) : void { $this->messages[$level][] = strtr($msg, $this->makeReplacements($context)); } /** * @return string[] */ public function getMessages($level=null) : array { if (null === $level) { return array_merge(...$this->messages); } return isset($this->messages[$level]) ? $this->messages[$level] : []; } /** * @param array<string, mixed> $context * @return array<string, string> */ private function makeReplacements(array $context) { $rv = []; foreach ($context as $name => $replace) { $rv[sprintf('{%s}', $name)] = $replace; } return $rv; } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/DefaultConsumerTest.php
test/unit/DefaultConsumerTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; use PHPUnit\Framework\MockObject\MockObject; use GuzzleHttp\Promise\FulfilledPromise; use Psr\Log\LogLevel; use PMG\Queue\Exception\SimpleMustStop; class DefaultConsumerTest extends UnitTestCase { const Q = 'TestQueue'; /** * @var Driver&MockObject */ private Driver $driver; /** * @var MessageHandler&MockObject */ private MessageHandler $handler; /** * @var RetrySpec&MockObject */ private RetrySpec $retries; private CollectingLogger $logger; private DefaultConsumer $consumer; private SimpleMessage $message; private DefaultEnvelope $envelope; public function testOnceDoesNothingWhenTheQueueIsEmpty() { $this->driver->expects($this->once()) ->method('dequeue') ->with(self::Q) ->willReturn(null); $this->handler->expects($this->never()) ->method('handle'); $this->assertNull($this->consumer->once(self::Q)); } public function testOnceExecutesTheMessageAndAcknowledgesIt() { $this->withMessage(); $this->driver->expects($this->once()) ->method('ack') ->with(self::Q, $this->identicalTo($this->envelope)); $this->handler->expects($this->once()) ->method('handle') ->with($this->identicalTo($this->message)) ->willReturn(self::promise(true)); $this->assertTrue($this->consumer->once(self::Q)); } public function testPlainObjectMessagesCanBeHandled() { $message = new class {}; $envelope = new DefaultEnvelope($message); $this->driver->expects($this->once()) ->method('dequeue') ->with(self::Q) ->willReturn($envelope); $this->driver->expects($this->once()) ->method('ack') ->with(self::Q, $this->identicalTo($envelope)); $this->handler->expects($this->once()) ->method('handle') ->with($this->identicalTo($message)) ->willReturn(self::promise(true)); $this->assertTrue($this->consumer->once(self::Q)); } public function testOnceWithAFailedMessageAndValidRetryPutsTheMessageBackInTheQueue() { $this->withMessage(); $this->willRetry(); $this->driver->expects($this->once()) ->method('retry') ->with(self::Q, $this->envelope->retry()); $this->handler->expects($this->once()) ->method('handle') ->with($this->identicalTo($this->message)) ->willReturn(self::promise(false)); $this->assertFalse($this->consumer->once(self::Q)); } public function testFailedMessageThatCannotBeRetriedIsNotPutBackInTheQueue() { $this->withMessage(); $this->retries->expects($this->once()) ->method('canRetry') ->willReturn(false); $this->driver->expects($this->never()) ->method('retry'); $this->handler->expects($this->once()) ->method('handle') ->with($this->identicalTo($this->message)) ->willReturn(self::promise(false)); $this->assertFalse($this->consumer->once(self::Q)); } public function testOnceWithAExceptionThrownFromHandlerAndValidRetryRetriesJobAndThrows() { $this->withMessage(); $this->willRetry(); $this->driver->expects($this->once()) ->method('retry') ->with(self::Q, $this->envelope->retry()); $this->handler->expects($this->once()) ->method('handle') ->with($this->identicalTo($this->message)) ->willThrowException(new \Exception('oops')); $this->assertFalse($this->consumer->once(self::Q)); $messages = $this->logger->getMessages(LogLevel::CRITICAL); $this->assertCount(1, $messages); $this->assertStringContainsString('oops', $messages[0]); $this->assertStringContainsString('TestMessage', $messages[0]); } public function testFailureWithMustStopAcksMessagesAndRethrows() { $this->expectException(Exception\MustStop::class); $this->withMessage(); $this->driver->expects($this->once()) ->method('ack') ->with(self::Q, $this->envelope); $this->handler->expects($this->once()) ->method('handle') ->with($this->identicalTo($this->message)) ->willThrowException(new SimpleMustStop('oops')); $this->consumer->once(self::Q); } public function testFailureWithShouldReleaseReleasesMessageBackIntoDriver() { $this->withMessage(); $this->driver->expects($this->once()) ->method('release') ->with(self::Q, $this->envelope); $this->handler->expects($this->once()) ->method('handle') ->with($this->identicalTo($this->message)) ->willThrowException(new Exception\ForkedProcessCancelled('oops')); $result = $this->consumer->once(self::Q); } /** * @group https://github.com/AgencyPMG/Queue/issues/61 * @group lifecycles */ public function testLifecycleOfSuccessfulMessageCallsExpectedLifecycleMethods() { $lifecycle = $this->createMock(MessageLifecycle::class); $lifecycle->expects($this->once()) ->method('starting') ->with($this->identicalTo($this->message), $this->identicalTo($this->consumer)); $lifecycle->expects($this->once()) ->method('completed') ->with($this->identicalTo($this->message), $this->identicalTo($this->consumer)); $lifecycle->expects($this->once()) ->method('succeeded') ->with($this->identicalTo($this->message), $this->identicalTo($this->consumer)); $this->withMessage(); $this->handler->expects($this->once()) ->method('handle') ->with($this->identicalTo($this->message)) ->willReturn(self::promise(true)); $result = $this->consumer->once(self::Q, $lifecycle); $this->assertTrue($result); } /** * @group https://github.com/AgencyPMG/Queue/issues/61 * @group lifecycles */ public function testLifecycleOnFailedMessageCallsExpectedLifecycleMethods() { $lifecycle = $this->createMock(MessageLifecycle::class); $lifecycle->expects($this->once()) ->method('starting') ->with($this->identicalTo($this->message), $this->identicalTo($this->consumer)); $lifecycle->expects($this->once()) ->method('completed') ->with($this->identicalTo($this->message), $this->identicalTo($this->consumer)); $lifecycle->expects($this->once()) ->method('failed') ->with($this->identicalTo($this->message), $this->identicalTo($this->consumer)); $this->withMessage(); $this->retries->expects($this->atLeastOnce()) ->method('canRetry') ->willReturn(false); $this->handler->expects($this->once()) ->method('handle') ->with($this->identicalTo($this->message)) ->willReturn(self::promise(false)); $result = $this->consumer->once(self::Q, $lifecycle); $this->assertFalse($result); } /** * @group https://github.com/AgencyPMG/Queue/issues/69 * @group lifecycles */ public function testLifecycleOnRetryingMessageCallsExpectedLifecycleMethods() { $lifecycle = $this->createMock(MessageLifecycle::class); $lifecycle->expects($this->once()) ->method('starting') ->with($this->identicalTo($this->message), $this->identicalTo($this->consumer)); $lifecycle->expects($this->once()) ->method('completed') ->with($this->identicalTo($this->message), $this->identicalTo($this->consumer)); $lifecycle->expects($this->once()) ->method('retrying') ->with($this->identicalTo($this->message), $this->identicalTo($this->consumer)); $this->withMessage(); $this->willRetry(); $this->handler->expects($this->once()) ->method('handle') ->with($this->identicalTo($this->message)) ->willReturn(self::promise(false)); $result = $this->consumer->once(self::Q, $lifecycle); $this->assertFalse($result); } /** * @group https://github.com/AgencyPMG/Queue/issues/58 */ public function testRetriedMessagesUseTheDelayFromTheRetrySpec() { $this->withMessage(); $this->willRetry(); $this->retries->expects($this->once()) ->method('retryDelay') ->with($this->envelope) ->willReturn(10); $this->driver->expects($this->once()) ->method('retry') ->with(self::Q, $this->envelope->retry(10)); $this->handler->expects($this->once()) ->method('handle') ->with($this->identicalTo($this->message)) ->willReturn(self::promise(false)); $this->consumer->once(self::Q); } protected function setUp() : void { $this->driver = $this->createMock(Driver::class); $this->handler = $this->createMock(MessageHandler::class); $this->retries = $this->createMock(RetrySpec::class); $this->logger = new CollectingLogger(); $this->consumer = new DefaultConsumer($this->driver, $this->handler, $this->retries, $this->logger); $this->message = new SimpleMessage('TestMessage'); $this->envelope = new DefaultEnvelope($this->message); } private function withMessage() { $this->driver->expects($this->once()) ->method('dequeue') ->with(self::Q) ->willReturn($this->envelope); } private function willRetry() { $this->retries->expects($this->atLeastOnce()) ->method('canRetry') ->willReturn(true); } private static function promise(bool $result) : FulfilledPromise { return new FulfilledPromise($result); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/AbstractConsumerTest.php
test/unit/AbstractConsumerTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; use Psr\Log\LogLevel; class AbstractConsumerTest extends UnitTestCase { const Q = 'TestQueue'; private $logger, $consumer, $message, $envelope; /** * This is a bad test: lots of stuff going on, but because we * don't want to block forever, it's the best we have. */ public function testRunConsumesMessagesUntilConsumerIsStopped() { $this->consumer->expects($this->exactly(2)) ->method('once') ->with(self::Q) ->will($this->onConsecutiveCalls( true, // successful :tada: $this->throwException(new Exception\SimpleMustStop('oops', 1)) )); $this->assertEquals(1, $this->consumer->run(self::Q)); } public function testRunStopsWhenADriverErrorIsThrown() { $this->consumer->expects($this->exactly(2)) ->method('once') ->with(self::Q) ->will($this->onConsecutiveCalls( true, // successful :tada: $this->throwException(new Exception\SerializationError('broke')) )); $result = $this->consumer->run(self::Q); $messages = $this->logger->getMessages(LogLevel::EMERGENCY); $this->assertEquals(DefaultConsumer::EXIT_ERROR, $result); $this->assertCount(1, $messages); $this->assertStringContainsString('broke', $messages[0]); } /** * @group https://github.com/AgencyPMG/Queue/issues/31 */ public function testRunStopsWhenAThrowableisCaught() { $this->consumer->expects($this->exactly(2)) ->method('once') ->with(self::Q) ->will($this->onConsecutiveCalls( true, // successful :tada: $this->throwException(new \Error('oops')) )); $result = $this->consumer->run(self::Q); $messages = $this->logger->getMessages(LogLevel::EMERGENCY); $this->assertEquals(DefaultConsumer::EXIT_ERROR, $result); $this->assertCount(1, $messages); $this->assertStringContainsString('oops', $messages[0]); } public function testConsumerWithoutLoggerPassedInCreatesANullLoggerOnDemand() { $consumer = $this->getMockForAbstractClass(AbstractConsumer::class); $consumer->expects($this->once()) ->method('once') ->with(self::Q) ->willThrowException(new Exception\SerializationError('broke')); $result = $consumer->run(self::Q); $this->assertEquals(DefaultConsumer::EXIT_ERROR, $result); } /** * @group https://github.com/AgencyPMG/Queue/issues/61 */ public function testRunPassesGivenMessageLifecycleToOnce() { $lifecycle = $this->createMock(MessageLifecycle::class); $this->consumer->expects($this->exactly(2)) ->method('once') ->with(self::Q, $this->identicalTo($lifecycle)) ->will($this->onConsecutiveCalls( true, // successful :tada: $this->throwException(new Exception\SimpleMustStop('oops', 1)) )); $this->assertEquals(1, $this->consumer->run(self::Q, $lifecycle)); } protected function setUp() : void { $this->logger = new CollectingLogger(); $this->consumer = $this->getMockForAbstractClass(AbstractConsumer::class, [$this->logger]); $this->message = new SimpleMessage('TestMessage'); $this->envelope = new DefaultEnvelope($this->message); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/UnitTestCase.php
test/unit/UnitTestCase.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; abstract class UnitTestCase extends \PHPUnit\Framework\TestCase { // noop }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/DefaultEnvelopeTest.php
test/unit/DefaultEnvelopeTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; use PMG\Queue\Exception\InvalidArgumentException as InvalidArg; class DefaultEnvelopeTest extends UnitTestCase { private $message; public function testEnvelopeCannotBeCreatedWithAttempsLessThanZero() { $this->expectException(InvalidArg::class); new DefaultEnvelope($this->message, -1); } public function testEnvelopeCannotBeCreatedWithDelayLessThanZero() { $this->expectException(InvalidArg::class); new DefaultEnvelope($this->message, 0, -1); } public function testRetrySetsTheDelayProvidedOnTheNewEnvelope() { $e = new DefaultEnvelope($this->message); $retry = $e->retry(10); $this->assertEquals(10, $retry->delay()); } public function testMessageCannotBeRetriedWithADelayLessThanZero() { $this->expectException(InvalidArg::class); $e = new DefaultEnvelope($this->message); $e->retry(-1); } protected function setUp() : void { $this->message = new SimpleMessage('test'); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/MessageNamesTest.php
test/unit/MessageNamesTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue; class _NamesTestMsg { // noop } class MessageNamesTest extends UnitTestCase { use MessageNames; public function testNameOfReturnsTheValueOfMessageGetName() { $msg = $this->createMock(Message::class); $msg->expects($this->once()) ->method('getName') ->willReturn('test'); $this->assertSame('test', self::nameOf($msg)); } public function testNameOfReturnsTheFullyQualifiedClassNameOfAWhenNotImplementingMessage() { $name = self::nameOf(new _NamesTestMsg()); $this->assertSame(_NamesTestMsg::class, $name); } public function testAnyObjectCanBePassedAndNameOfReturnsFqcn() { $name = self::nameOf($this); $this->assertSame(__CLASS__, $name); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/Driver/MemoryDriverTest.php
test/unit/Driver/MemoryDriverTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Driver; use PMG\Queue\DefaultEnvelope; use PMG\Queue\Envelope; use PMG\Queue\SimpleMessage; class MemoryDriverTest extends \PMG\Queue\UnitTestCase { const Q = 'TestQueue'; private $driver; public function testEmptyQueueReturnsNullWhenDequeued() { $this->assertNull($this->driver->dequeue(self::Q)); } public function testEnvelopesCanBeEnqueuedAndDequeued() { $m = new DefaultEnvelope(new SimpleMessage('test')); $result = $this->driver->enqueue(self::Q, $m); $this->assertSame($m, $result); $this->assertSame($m, $this->driver->dequeue(self::Q)); } public function testMessagesCanBeEnqueuedAndDequeued() { $m = new SimpleMessage('test'); $this->assertInstanceOf(Envelope::class, $this->driver->enqueue(self::Q, $m)); $e = $this->driver->dequeue(self::Q); $this->assertSame($m, $e->unwrap()); $this->driver->retry(self::Q, $e); $e = $this->driver->dequeue(self::Q); $this->assertSame($m, $e->unwrap()); } public function testMessagesCanBeEnqueuedDequeuedAndReleased() { $m = new SimpleMessage('test'); $this->assertInstanceOf(Envelope::class, $this->driver->enqueue(self::Q, $m)); $e = $this->driver->dequeue(self::Q); $this->assertSame($m, $e->unwrap()); $this->driver->release(self::Q, $e); $e2 = $this->driver->dequeue(self::Q); $this->assertSame($e, $e2); } protected function setUp() : void { $this->driver = new MemoryDriver(); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/Driver/AbstractPersistanceDriverTest.php
test/unit/Driver/AbstractPersistanceDriverTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Driver; use PMG\Queue\Envelope; use PMG\Queue\DefaultEnvelope; use PMG\Queue\SimpleMessage; use PMG\Queue\Serializer\Serializer; // mostly a dirty hack to expose the `serialize` and `unserialize` methods // as public. Also makes the serializer optional in the constructor so we can // verify that the ABC errors when `parent::__construct($someSerializer)` is // not called abstract class _DriverAbc extends AbstractPersistanceDriver { public function __construct(?Serializer $serializer=null) { if ($serializer) { parent::__construct($serializer); } } public function serialize(Envelope $env) { return parent::serialize($env); } public function unserialize($str) { return parent::unserialize($str); } } class AbstractPersistanceDriverTest extends \PMG\Queue\UnitTestCase { private $envelope; public function testDriversSerializeMethodsWorksWhenGivenASerializer() { list($serializer, $driver) = $this->createDriver(); $serializer->expects($this->once()) ->method('serialize') ->with($this->envelope) ->willReturn($envstr = serialize($this->envelope)); $this->assertEquals($envstr, $driver->serialize($this->envelope)); } public function testDriversUnserializeMethodsWorksWhenWhenASerializer() { list($serializer, $driver) = $this->createDriver(); $serializer->expects($this->once()) ->method('unserialize') ->with(serialize($this->envelope)) ->willReturn($this->envelope); $this->assertEquals($this->envelope, $driver->unserialize(serialize($this->envelope))); } public function testSerializeErrorsWhenNoSerializerWasGivenToTheConstructor() { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('does not have a serializer set'); $this->createInvalidDriver()->serialize($this->envelope); } public function testUnserializeErrorsWhenNoSerializerWasGivenToTheConstructor() { $this->expectException(\RuntimeException::class); $this->expectExceptionMessage('does not have a serializer set'); $this->createInvalidDriver()->unserialize(serialize($this->envelope)); } protected function setUp() : void { $this->envelope = new DefaultEnvelope(new SimpleMessage('Test')); } private function createDriver() { $serializer = $this->createMock(Serializer::class); $driver = $this->getMockForAbstractClass(_DriverAbc::class, [$serializer]); return [$serializer, $driver]; } private function createInvalidDriver() { return $this->getMockForAbstractClass(_DriverAbc::class); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/Signer/SodiumCryptoAuthTest.php
test/unit/Signer/SodiumCryptoAuthTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Signer; use PMG\Queue\Exception\InvalidArgumentException; class SodiumCryptoAuthTest extends SignerTestCase { public function testSignerCannotBeCreatedWithEmptyKey() { $this->expectException(InvalidArgumentException::class); new SodiumCryptoAuth(''); } public static function invalidKeys() { return [ 'too short' => ['test'], 'too long' => [str_repeat('test', 100)], ]; } /** * @dataProvider invalidKeys */ public function testSignerCannotBeCreatedWithInvalidKey(string $key) { $this->expectException(InvalidArgumentException::class); new SodiumCryptoAuth($key); } protected function createSigner() { return new SodiumCryptoAuth(str_repeat('test', 8)); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/Signer/HmacSha256Test.php
test/unit/Signer/HmacSha256Test.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Signer; use PMG\Queue\Exception\InvalidArgumentException; class HmacSha256Test extends SignerTestCase { public function testSignerCannotBeCreatedWithEmptyKey() { $this->expectException(InvalidArgumentException::class); new HmacSha256(''); } protected function createSigner() { return new HmacSha256('superSecretShhhh'); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/Signer/SignerTestCase.php
test/unit/Signer/SignerTestCase.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Signer; use PMG\Queue\Exception\InvalidArgumentException; abstract class SignerTestCase extends \PMG\Queue\UnitTestCase { protected $signer; public function testSignReturnsAMacString() { $mac = $this->signer->sign('hello, world'); $this->assertIsString($mac); $this->assertNotEmpty($mac); } public function testVerifyReturnsTrueWhenTheMessageIsTheSame() { $mac = $this->signer->sign('hello, world'); $result = $this->signer->verify($mac, 'hello, world'); $this->assertTrue($result); } public function testVerifyReturnsFalseWhenTheMessageIsNotTheSame() { $mac = $this->signer->sign('hello, world'); $result = $this->signer->verify($mac, 'goodbye, world'); $this->assertFalse($result); } protected function setUp() : void { $this->signer = $this->createSigner(); } abstract protected function createSigner(); }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/Lifecycle/MappingLifecycleTest.php
test/unit/Lifecycle/MappingLifecycleTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Lifecycle; use PMG\Queue\MessageNames; use PMG\Queue\SimpleMessage; use PMG\Queue\Exception\InvalidArgumentException; /** * @group lifecycles */ class MappingLifecycleTest extends LifecycleTestCase { use MessageNames; private $child, $fallback, $lifecycle; public static function badMappings() : array { return [ ['one'], [1], [true], [null], [new \stdClass], ]; } /** * @dataProvider badMappings */ public function testLifecyclesCannotBeCreatedWithNonArrayishObjects($mapping) { $this->expectException(InvalidArgumentException::class); new MappingLifecycle($mapping); } public function validMappings() : array { return [ [['one' => new NullLifecycle()]], [new \ArrayObject(['one' => new NullLifecycle()])], ]; } /** * @dataProvider validMappings */ public function testLifecycleCanBeCreatedFromArrayishObject($mapping) { $lc = new MappingLifecycle($mapping); $this->assertTrue($lc->has('one')); $this->assertFalse($lc->has('two')); } public static function methods() : array { return [ ['starting'], ['completed'], ['retrying'], ['failed'], ['succeeded'], ]; } /** * @dataProvider methods */ public function testLifecycleCallsFallbackIfMessageIsNotInMapping(string $method) { $message = new SimpleMessage('noope'); $this->child->expects($this->never()) ->method($method); $this->fallback->expects($this->once()) ->method($method) ->with($this->identicalTo($message), $this->isConsumer()); call_user_func([$this->lifecycle, $method], $message, $this->consumer); } /** * @dataProvider methods */ public function testLifecycleCanBeCreatedWithoutAFallbackAndStillWorksWithUnmappedMessages(string $method) { $message = new SimpleMessage('noope'); $this->child->expects($this->never()) ->method($method); $lc = new MappingLifecycle([ self::nameOf($this->message) => $this->child, ]); call_user_func([$lc, $method], $message, $this->consumer); } /** * @dataProvider methods */ public function testLifecycleCallsChildLifecycleIfMappingHasMessage(string $method) { $this->child->expects($this->once()) ->method($method) ->with($this->isMessage(), $this->isConsumer()); call_user_func([$this->lifecycle, $method], $this->message, $this->consumer); } protected function setUp() : void { parent::setUp(); $this->child = $this->mockLifecycle(); $this->fallback = $this->mockLifecycle(); $this->lifecycle = new MappingLifecycle([ self::nameOf($this->message) => $this->child, ], $this->fallback); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/Lifecycle/DelegatingLifecycleTest.php
test/unit/Lifecycle/DelegatingLifecycleTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Lifecycle; /** * @group lifecycles */ class DelegatingLifecycleTest extends LifecycleTestCase { public static function methods() : array { return [ ['starting'], ['completed'], ['retrying'], ['failed'], ['succeeded'], ]; } /** * @dataProvider methods */ public function testLifecycleCallsChildLifecyclesWithProvidedArguments(string $method) { $lc = $this->mockLifecycle(); $lc->expects($this->once()) ->method($method) ->with($this->isMessage(), $this->isConsumer()); $dl = new DelegatingLifecycle($lc); call_user_func([$dl, $method], $this->message, $this->consumer); } public function testDelegatingLifecyclesCanBeCreatedFromIterables() { $dl = DelegatingLifecycle::fromIterable((function () { foreach (range(1, 3) as $i) { yield $this->mockLifecycle(); } })()); $this->assertCount(3, $dl, 'should have three child lifecycles'); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/Lifecycle/LifecycleTestCase.php
test/unit/Lifecycle/LifecycleTestCase.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Lifecycle; use PMG\Queue\MessageLifecycle; use PMG\Queue\Consumer; use PMG\Queue\SimpleMessage; abstract class LifecycleTestCase extends \PMG\Queue\UnitTestCase { protected $consumer, $message; protected function setUp() : void { $this->consumer = $this->createMock(Consumer::class); $this->message = new SimpleMessage('example'); } protected function mockLifecycle() : MessageLifecycle { return $this->createMock(MessageLifecycle::class); } protected function isConsumer() { return $this->identicalTo($this->consumer); } protected function isMessage() { return $this->identicalTo($this->message); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/Serializer/NativeSerializerTest.php
test/unit/Serializer/NativeSerializerTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Serializer; use PHPUnit\Framework\MockObject\MockObject; use PMG\Queue\Envelope; use PMG\Queue\DefaultEnvelope; use PMG\Queue\SimpleMessage; use PMG\Queue\Exception\MissingSignature; use PMG\Queue\Exception\NotAnEnvelope; use PMG\Queue\Exception\SerializationError; use PMG\Queue\Exception\InvalidSignature; use PMG\Queue\Signer\Signer; class NativeSerializerTest extends \PMG\Queue\UnitTestCase { const SIG = 'someHmac'; /** * @var Signer&MockObject */ private Signer $signer; private NativeSerializer $serializer; private DefaultEnvelope $env; private string $envMessage; private string $sigMessage; public function testSerializeNativeSerializersAndSignsTheMessageBeforeReturningIt() { $this->willSignMessage($this->envMessage); $result = $this->serializer->serialize($this->env); $this->assertStringContainsString(self::SIG, $result); $this->assertStringContainsString($this->envMessage, $result); } public function testUnserializeErrorsWhenTheMessageSignatureIsNotPresent() { $this->expectException(MissingSignature::class); $this->expectExceptionMessage('does not have a signature'); $this->serializer->unserialize($this->envMessage); } public function testUnserializeErrorsWhenTheSignatureIsInvalid() { $this->expectException(InvalidSignature::class); $this->expectExceptionMessage('Invalid Message Signature'); $this->signer->expects($this->once()) ->method('verify') ->with('invalid', $this->envMessage) ->willReturn(false); $this->serializer->unserialize('invalid|'.$this->envMessage); } public function testUnserializeErrorsWhenTheSerializedStringIsInvalid() { $this->expectException(SerializationError::class); $this->expectExceptionMessage('Error unserializing message:'); $env = base64_encode('a:'); $this->willVerifyMessage($env); $this->serializer->unserialize(self::SIG.'|'.$env); } public function testUnserializeErrorsWhenTheClassUnserializeIsNotAnEnvelope() { $this->expectException(NotAnEnvelope::class); $this->expectExceptionMessage('an instance of'); $env = base64_encode(serialize(new \stdClass())); $this->willVerifyMessage($env); $this->serializer->unserialize(self::SIG.'|'.$env); } public function testUnserializeReturnsTheUnserializeEnvelopeWhenSuccessful() { $this->willVerifyMessage($this->envMessage); $result = $this->serializer->unserialize($this->sigMessage); $this->assertEquals($this->env, $result); } protected function setUp() : void { $this->signer = $this->createMock(Signer::class); $this->serializer = new NativeSerializer($this->signer); $this->env = new DefaultEnvelope(new SimpleMessage('t')); $this->envMessage = base64_encode(serialize($this->env)); $this->sigMessage = self::SIG.'|'.$this->envMessage; } private function willSignMessage(string $message) { $this->signer->expects($this->once()) ->method('sign') ->with($message) ->willReturn(self::SIG); } private function willVerifyMessage(string $message) { $this->signer->expects($this->once()) ->method('verify') ->with(self::SIG, $message) ->willReturn(true); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/Router/FallbackRouterTest.php
test/unit/Router/FallbackRouterTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Router; use PMG\Queue\Router; use PMG\Queue\SimpleMessage; class FallbackRouterTest extends \PMG\Queue\UnitTestCase { const FALLBACK = 'FallbackQueue'; private $wrapped, $router, $message; public function testQueueForReturnsValueFromWrappedRouterWhenFound() { $this->wrappedRouterReturns('FoundQueue'); $this->assertEquals('FoundQueue', $this->router->queueFor($this->message)); } public function testQueueForReturnsFallbackValueWhenWrappedWRouterFindsNothing() { $this->wrappedRouterReturns(null); $this->assertEquals(self::FALLBACK, $this->router->queueFor($this->message)); } protected function setUp() : void { $this->wrapped = $this->createMock(Router::class); $this->router = new FallbackRouter($this->wrapped, self::FALLBACK); $this->message = new SimpleMessage('test'); } private function wrappedRouterReturns(?string $value) { $this->wrapped->expects($this->once()) ->method('queueFor') ->with($this->identicalTo($this->message)) ->willReturn($value); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/Router/SimpleRouterTest.php
test/unit/Router/SimpleRouterTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Router; use PMG\Queue\SimpleMessage; class SimpleRouterTest extends \PMG\Queue\UnitTestCase { public function testQueueForReturnsTheQueueNamePassedToTheConstructor() { $r = new SimpleRouter('queue'); $this->assertEquals('queue', $r->queueFor(new SimpleMessage('test'))); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/Router/MappingRouterTest.php
test/unit/Router/MappingRouterTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Router; use PMG\Queue\SimpleMessage; use PMG\Queue\Exception\InvalidArgumentException; class MappingRouterTest extends \PMG\Queue\UnitTestCase { const NAME = 'TestMessage'; public function testRouterReturnsNullWhenNoQueueIsFound() { $this->assertNull((new MappingRouter([]))->queueFor(new SimpleMessage(self::NAME))); } public function validMappings() { return [ [[self::NAME => 'ExampleQueue']], [new \ArrayObject([self::NAME => 'ExampleQueue'])], ]; } /** * @dataProvider validMappings */ public function testRouterReturnsQueueNameFromMapWhenMessageIsFound($map) { $router = new MappingRouter($map); $this->assertEquals('ExampleQueue', $router->queueFor(new SimpleMessage(self::NAME))); } public function invalidMappings() { return [ [1], [1.1], [false], [null], [new \stdClass], ]; } /** * @dataProvider invalidMappings */ public function testRouterCannotBeCreatedWithInvalidMapping($map) { $this->expectException(InvalidArgumentException::class); new MappingRouter($map); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/Retry/LimitedSpecTest.php
test/unit/Retry/LimitedSpecTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Retry; use PMG\Queue\DefaultEnvelope; use PMG\Queue\SimpleMessage; use PMG\Queue\Exception\InvalidArgumentException; class LimitedSpecTest extends \PMG\Queue\UnitTestCase { public static function badAttempts() { return [ [0], [-1], ]; } /** * @dataProvider badAttempts */ public function testCreatingLimitSpecFailsWithInvalidAttempts($attempts) { $this->expectException(InvalidArgumentException::class); new LimitedSpec($attempts); } public function testCreatingLimitSpecFailsWithInvalidDelay() { $this->expectException(InvalidArgumentException::class); new LimitedSpec(5, -5); } public function testCanRetryReturnsTrueWhenAttemptsAreBelowLimit() { $spec = new LimitedSpec(); $env = new DefaultEnvelope(new SimpleMessage('test')); $this->assertTrue($spec->canRetry($env)); } public function testCanRetryReturnsFalseWhenAttemptsExceedTheLimit() { $spec = new LimitedSpec(1); $env = new DefaultEnvelope(new SimpleMessage('test'), 1); $this->assertFalse($spec->canRetry($env)); } public function testRetryDelayReturnsZeroWithoutSpecifiedDelay() { $spec = new LimitedSpec(); $env = new DefaultEnvelope(new SimpleMessage('test')); $this->assertSame(0, $spec->retryDelay($env)); } public function testRetryDelayReturnsAsConfigured() { $spec = new LimitedSpec(null, $expectedDelay = rand(1, 60)); $env = new DefaultEnvelope(new SimpleMessage('test')); $this->assertSame($expectedDelay, $spec->retryDelay($env)); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/Handler/PcntlForkingHandlerTest.php
test/unit/Handler/PcntlForkingHandlerTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Handler; use PMG\Queue\SimpleMessage; use PMG\Queue\Exception\CouldNotFork; use PMG\Queue\Exception\ForkedProcessCancelled; use PMG\Queue\Exception\ForkedProcessFailed; use PMG\Queue\Handler\Pcntl\Pcntl; /** * This uses `CallableHandler` simply because I'm not sure how phpunit mock objects * behave in forked processes. * * @requires extension pcntl */ class PcntlForkingHandlerTest extends \PMG\Queue\UnitTestCase { const NAME = 'TestMessage'; private $message; public function testChildProcessWithASuccessfulResultReturnsTrueFromParent() { $handler = $this->createHandler(function () { return true; }); $promise = $handler->handle($this->message); $this->assertTrue($promise->wait()); } public function testChildProcessWithFailedResultCausesErrorInParent() { $this->expectException(ForkedProcessFailed::class); $this->expectExceptionMessage('exit code 1'); $handler = $this->createHandler(function () { return false; }); $handler->handle($this->message)->wait(); } public function testChildProcessThatExitsEarlyWithErrorReturnsFalseFromParent() { $this->expectException(ForkedProcessFailed::class); $handler = $this->createHandler(function () { // we can't throw here because php unit complains. Instead just call // `exit` with 255 to simulate exiting early. exit(255); }); $handler->handle($this->message)->wait(); } public function testChildProcessThatThrowsAnExceptionExitsUnsuccessfully() { $this->expectException(ForkedProcessFailed::class); $handler = $this->createHandler(function () { throw new \Exception('oh noz'); }); $handler->handle($this->message)->wait(); } public function testChildProcessWithErrorExitsUnsuccessfully() { $this->expectException(ForkedProcessFailed::class); $handler = $this->createHandler(function () { throw new \Error('oh noz'); }); $handler->handle($this->message)->wait(); } public function testChildProcessIsPassedTheOptionsFromTheHandler() { $handler = $this->createHandler(function ($msg, $options) { // will cause an unsuccessful exit if it fails. $this->assertEquals($options, ['one' => true]); return true; }); $promise = $handler->handle($this->message, ['one' => true]); $this->assertTrue($promise->wait()); } public function testHandlerErrorsIfAChildProcessCannotFork() { $this->expectException(CouldNotFork::class); $pcntl = $this->createMock(Pcntl::class); $handler = $this->createHandler(function () { // ignored }, $pcntl); $pcntl->expects($this->once()) ->method('fork') ->willReturn(-1); $handler->handle($this->message); } /** * @group slow */ public function testHandlerPromisesCanBeCancelled() { $this->expectException(ForkedProcessCancelled::class); $handler = $this->createHandler(function () { sleep(10000); $this->assertTrue(false, 'causes a different exit exception'); }); $promise = $handler->handle($this->message); $promise->cancel(); $promise->wait(); } /** * @requires function pcntl_async_signals * @group slow */ public function testHandlersWaitingThatAreCancelledAsynchronouslyFail() { $this->expectException(ForkedProcessCancelled::class); $handler = $this->createHandler(function () { sleep(10000); $this->assertTrue(false, 'causes a different exit exception'); }); $promise = $handler->handle($this->message); $previous = pcntl_async_signals(true); pcntl_signal(SIGALRM, function () use ($promise) { $promise->cancel(); }); pcntl_alarm(3); try { $promise->wait(); } finally { pcntl_async_signals($previous); pcntl_signal(SIGALRM, SIG_DFL); } } protected function setUp() : void { $this->message = new SimpleMessage(self::NAME); } private function createHandler(callable $callback, ?Pcntl $pcntl=null) { return new PcntlForkingHandler(new CallableHandler($callback), $pcntl); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/Handler/CallableHandlerTest.php
test/unit/Handler/CallableHandlerTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Handler; use PMG\Queue\SimpleMessage; class CallableHandlerTest extends \PMG\Queue\UnitTestCase { const NAME = 'TestMessage'; private $message; public function testHandlerInvokesTheCallbackWithTheMessage() { $calledWith = null; $handler = new CallableHandler(function ($msg) use (&$calledWith) { $calledWith = $msg; return true; }); $promise = $handler->handle($this->message); $result = $promise->wait(); $this->assertTrue($result); $this->assertSame($this->message, $calledWith); } public function testHandlerInvokesTheCallbackWithTheRprovidedOptions() { $calledWith = null; $handler = new CallableHandler(function ($msg, $options) use (&$calledWith) { $calledWith = $options; return true; }); $promise = $handler->handle($this->message, ['one' => true]); $result = $promise->wait(); $this->assertTrue($result); $this->assertSame($calledWith, ['one' => true]); } protected function setUp() : void { $this->message = new SimpleMessage(self::NAME); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/test/unit/Handler/Pcntl/PcntlTest.php
test/unit/Handler/Pcntl/PcntlTest.php
<?php declare(strict_types=1); /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/Apache-2.0 Apache-2.0 */ namespace PMG\Queue\Handler\Pcntl; use PMG\Queue\Exception\AbnormalExit; /** * While most of pcntl "happy" path stuff is handled by `PcntlForkingHandlerTest` * this one covers some of the less happy path stuff like abnormal exits, etc. * * @requires extension pcntl * @requires extension posix */ class PcntlTest extends \PMG\Queue\UnitTestCase { private $pcntl; public function testStoppedProcessesThrowsAbnormalExit() { $this->expectException(AbnormalExit::class); $this->expectExceptionMessage('was stopped with'); $pid = $this->fork(); if ($pid) { posix_kill($pid, SIGSTOP); try { $this->pcntl->wait($pid); } finally { // continue, then kill the stopped process. $this->pcntl->signal($pid, SIGCONT); $this->pcntl->signal($pid, SIGTERM); pcntl_waitpid($pid, $status, WUNTRACED); $this->assertTrue(pcntl_wifsignaled($status)); } } else { self::waitAndExit(5, 0); } } public function testInterruptedProcessesThrowAbnormalExit() { $this->expectException(AbnormalExit::class); $this->expectExceptionMessage('was terminated with'); $pid = $this->fork(); if ($pid) { $this->pcntl->signal($pid, SIGINT); $this->pcntl->wait($pid); } else { self::waitAndExit(5, 0); } } protected function setUp() : void { $this->pcntl = new Pcntl(); } private function fork() { $pid = $this->pcntl->fork(); if (-1 === $pid) { $this->markTestSkipped('Could not fork!'); } return $pid; } private static function waitAndExit($time, $status) { sleep($time); exit($status); } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/examples/plain_object_message.php
examples/plain_object_message.php
<?php use PMG\Queue; require __DIR__.'/../vendor/autoload.php'; require __DIR__.'/StreamLogger.php'; class SomeMessage { public $hello = 'World'; } $driver = new Queue\Driver\MemoryDriver(); $router = new Queue\Router\SimpleRouter('q'); $producer = new Queue\DefaultProducer($driver, $router); // an example callback handler. If you're doing something like this in your // own application consider using `pmg/queue-mapping-handler` $handler = new Queue\Handler\CallableHandler(function (object $msg) { var_dump($msg); return true; }); $consumer = new Queue\DefaultConsumer( $driver, $handler, new Queue\Retry\NeverSpec(), // allow never retry messages new StreamLogger() ); $producer->send(new SomeMessage()); exit($consumer->once('q') ? 0 : 1);
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/examples/StreamLogger.php
examples/StreamLogger.php
<?php /** * This file is part of PMG\Queue * * Copyright (c) PMG <https://www.pmg.com> * * For full copyright information see the LICENSE file distributed * with this source code. * * @license http://opensource.org/licenses/MIT MIT */ use Psr\Log\AbstractLogger; /** * A logger implementation that ignores levels and just spits everything * out to a stream. * * @since 2.0 */ final class StreamLogger extends AbstractLogger { private $stream; public function __construct($stream=null) { $this->stream = $stream ?: fopen('php://stderr', 'w'); } public function __destruct() { fclose($this->stream); } /** * {@inheritdoc} */ public function log($level, $message, array $context=[]) : void { $replace = $this->makeReplacements($context); fwrite($this->stream, sprintf( '[%s] %s%s', $level, strtr($message, $replace), PHP_EOL )); } /** * @param array<string, string> $context * @return array<string, string> */ private function makeReplacements(array $context) : array { $rv = []; foreach ($context as $name => $replace) { $rv[sprintf('{%s}', $name)] = $replace; } return $rv; } }
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/examples/retrying.php
examples/retrying.php
<?php use PMG\Queue; require __DIR__.'/../vendor/autoload.php'; require __DIR__.'/StreamLogger.php'; $driver = new Queue\Driver\MemoryDriver(); $router = new Queue\Router\SimpleRouter('q'); $producer = new Queue\DefaultProducer($driver, $router); $handler = new Queue\Handler\CallableHandler(function () { static $calls = 0; if ($calls >= 5) { throw new Queue\Exception\SimpleMustStop('stopit'); } $calls++; throw new \Exception('broken'); }); $consumer = new Queue\DefaultConsumer( $driver, $handler, new Queue\Retry\LimitedSpec(5), // allow five retries new StreamLogger() ); $producer->send(new Queue\SimpleMessage('TestMessage')); exit($consumer->run('q'));
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
AgencyPMG/Queue
https://github.com/AgencyPMG/Queue/blob/7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f/examples/simple.php
examples/simple.php
<?php use PMG\Queue; require __DIR__.'/../vendor/autoload.php'; require __DIR__.'/StreamLogger.php'; $driver = new Queue\Driver\MemoryDriver(); $router = new Queue\Router\SimpleRouter('q'); $producer = new Queue\DefaultProducer($driver, $router); // an example callback handler. If you're doing something like this in your // own application consider using `pmg/queue-mapping-handler` $handler = new Queue\Handler\CallableHandler(function (Queue\Message $msg) { switch ($msg->getName()) { case 'TestMessage': // noop break; case 'TestMessage2': throw new \Exception('oops'); break; case 'MustStop': throw new Queue\Exception\SimpleMustStop('stopit'); break; } }); $consumer = new Queue\DefaultConsumer( $driver, $handler, new Queue\Retry\NeverSpec(), // allow never retry messages new StreamLogger() ); $producer->send(new Queue\SimpleMessage('TestMessage')); $producer->send(new Queue\SimpleMessage('TestMessage2')); $producer->send(new Queue\SimpleMessage('MustStop')); exit($consumer->run('q'));
php
Apache-2.0
7dd5f22268a8fbfb4ba50fca4f839f0ce4d1476f
2026-01-05T05:09:50.528684Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/.php_cs.dist.php
.php_cs.dist.php
<?php $finder = Symfony\Component\Finder\Finder::create() ->in([ __DIR__ . '/src', __DIR__ . '/tests', ]) ->name('*.php') ->notName('*.blade.php') ->ignoreDotFiles(true) ->ignoreVCS(true); return (new PhpCsFixer\Config()) ->setRules([ '@PSR2' => true, 'array_syntax' => ['syntax' => 'short'], 'ordered_imports' => ['sort_algorithm' => 'alpha'], 'no_unused_imports' => true, 'not_operator_with_successor_space' => true, 'trailing_comma_in_multiline' => true, 'phpdoc_scalar' => true, 'unary_operator_spaces' => true, 'binary_operator_spaces' => true, 'blank_line_before_statement' => [ 'statements' => ['break', 'continue', 'declare', 'return', 'throw', 'try'], ], 'phpdoc_single_line_var_spacing' => true, 'phpdoc_var_without_name' => true, 'class_attributes_separation' => [ 'elements' => [ 'method' => 'one', ], ], 'method_argument_space' => [ 'on_multiline' => 'ensure_fully_multiline', 'keep_multiple_spaces_after_comma' => true, ], 'single_trait_insert_per_statement' => true, ]) ->setFinder($finder);
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/src/MassUpdatable.php
src/MassUpdatable.php
<?php namespace Iksaku\Laravel\MassUpdate; use Iksaku\Laravel\MassUpdate\Exceptions\EmptyUniqueByException; use Iksaku\Laravel\MassUpdate\Exceptions\MassUpdatingAndFilteringModelUsingTheSameColumn; use Iksaku\Laravel\MassUpdate\Exceptions\MissingFilterableColumnsException; use Iksaku\Laravel\MassUpdate\Exceptions\OrphanValueException; use Iksaku\Laravel\MassUpdate\Exceptions\RecordWithoutFilterableColumnsException; use Iksaku\Laravel\MassUpdate\Exceptions\RecordWithoutUpdatableValuesException; use Iksaku\Laravel\MassUpdate\Exceptions\UnexpectedModelClassException; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Contracts\Support\Jsonable; use Illuminate\Database\Eloquent\Builder; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Arr; use Illuminate\Support\Facades\DB; /** * @mixin Model */ trait MassUpdatable { public function getMassUpdateKeyName(): string|array|null { return $this->getKeyName(); } public function scopeMassUpdate(Builder $query, array | Arrayable $values, array | string | null $uniqueBy = null): int { if (empty($values)) { return 0; } if ($uniqueBy !== null && empty($uniqueBy)) { throw new EmptyUniqueByException(); } $quoteValue = function (mixed $value) use ($query) { if (is_null($value)) { return 'NULL'; } if (is_bool($value)) { return (int) $value; } if (is_int($value)) { return $value; } if ($value instanceof Arrayable) { $value = $value->toArray(); } if (is_array($value)) { $value = json_encode($value); } if ($value instanceof Jsonable) { $value = $value->toJson(); } return $query->getConnection()->getPdo()->quote($value); }; $uniqueBy = Arr::wrap($uniqueBy ?? $this->getMassUpdateKeyName()); /* * Values per row to use as a query filter. * Example: * [ * 'id' => [1, 2, 3, 4, ...], * ... * ] */ $whereIn = []; /* * Column name-value association pending update. * Value is pre-compiled into a `WHEN <condition> THEN <value>` format. * Example: * [ * 'name' => [ * 'WHEN `id` = 1 THEN Jorge González', * 'WHEN `id` = 2 THEN Elena González', * ... * ] * ] */ $preCompiledUpdateStatements = []; // Cached column reference used to separate from each record's value. $intersectionColumns = array_flip($uniqueBy); foreach ($values as $record) { if (empty($record)) { continue; } if ($record instanceof Model) { if ($record::class !== static::class) { throw new UnexpectedModelClassException(static::class, $record::class); } if (! $record->isDirty()) { continue; } $uniqueColumns = array_intersect_key($record->getAttributes(), $intersectionColumns); $updatableColumns = $record->getDirty(); if (! empty($crossReferencedColumns = array_intersect_key($updatableColumns, $uniqueColumns))) { throw new MassUpdatingAndFilteringModelUsingTheSameColumn($crossReferencedColumns); } } else { $uniqueColumns = array_intersect_key($record, $intersectionColumns); $updatableColumns = array_diff_key($record, $intersectionColumns); } if (empty($uniqueColumns)) { throw new RecordWithoutFilterableColumnsException(); } if (empty($updatableColumns)) { throw new RecordWithoutUpdatableValuesException(); } if (count($missingColumns = array_diff_key($intersectionColumns, $uniqueColumns)) > 0) { throw new MissingFilterableColumnsException(array_flip($missingColumns)); } /* * List of conditions for our future `CASE` statement to be met * in order to update current record's value. */ $preCompiledConditions = []; /* * Loop through columns labelled as `unique`, which will allow * the DB to properly assign the correct value to the correct * record. */ foreach ($uniqueColumns as $column => $value) { $preCompiledConditions[] = "{$query->getGrammar()->wrap($column)} = {$quoteValue($value)}"; if (! isset($whereIn[$column])) { $whereIn[$column] = [$value]; continue; } if (! in_array($value, $whereIn[$column])) { $whereIn[$column][] = $value; } } $preCompiledConditions = implode(' AND ', $preCompiledConditions); /* * Loop through the columns that are actual values to update. * These do not include the `unique columns`, so we will not * be updating those. */ foreach ($updatableColumns as $column => $value) { if (! is_string($column)) { throw new OrphanValueException($value); } $preCompiledAssociation = "WHEN $preCompiledConditions THEN {$quoteValue($value)}"; if (! isset($preCompiledUpdateStatements[$column])) { $preCompiledUpdateStatements[$column] = [$preCompiledAssociation]; continue; } if (! in_array($preCompiledAssociation, $preCompiledUpdateStatements[$column])) { $preCompiledUpdateStatements[$column][] = $preCompiledAssociation; } } } if (empty($preCompiledUpdateStatements)) { return 0; } /* * Tell the DB to only operate in rows where the specified * `unique` columns equal the collected values. */ foreach ($whereIn as $column => $values) { $query->whereIn($column, $values); } /* * Final column name-value association pending update. * Value is compiled as an SQL `CASE WHEN ... THEN ...` statement, * which will tell the DB to assign a different value depending * on the column values of the row it's currently operating on. * Example: * [ * 'name' => <<<SQL * CASE WHEN `id` = 1 THEN Jorge González * WHEN `id` = 2 THEN Elena González * ELSE `name` * END * SQL, * ... * ] */ $compiledUpdateStatements = collect($preCompiledUpdateStatements) ->mapWithKeys(function (array $conditionalAssignments, string $column) use ($query) { $conditions = implode("\n", $conditionalAssignments); return [ $column => DB::raw(<<<SQL CASE $conditions ELSE {$query->getGrammar()->wrap($column)} END SQL), ]; }) ->toArray(); // If the model tracks an update timestamp, update it for all touched records. if ($this->usesTimestamps() && $this->getUpdatedAtColumn() !== null) { $compiledUpdateStatements[$this->getUpdatedAtColumn()] = $this->freshTimestampString(); } /* * Finally, execute the update query against the database and * return the number of touched records. */ return $query->update($compiledUpdateStatements); } public function scopeMassUpdateQuietly(Builder $query, array | Arrayable $values, array | string | null $uniqueBy = null): int { $this->timestamps = false; return tap($query->massUpdate($values, $uniqueBy), function () { $this->timestamps = true; }); } }
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/src/Exceptions/RecordWithoutUpdatableValuesException.php
src/Exceptions/RecordWithoutUpdatableValuesException.php
<?php namespace Iksaku\Laravel\MassUpdate\Exceptions; use Throwable; use UnexpectedValueException; class RecordWithoutUpdatableValuesException extends UnexpectedValueException { public function __construct(Throwable $previous = null) { parent::__construct( 'No updatable columns where found for the current record.', 3, $previous ); } }
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/src/Exceptions/UnexpectedModelClassException.php
src/Exceptions/UnexpectedModelClassException.php
<?php namespace Iksaku\Laravel\MassUpdate\Exceptions; use Throwable; use UnexpectedValueException; class UnexpectedModelClassException extends UnexpectedValueException { public function __construct(string $expectedClass, string $impostorClass, Throwable $previous = null) { parent::__construct( "Expected an array of [{$expectedClass}] model instances. Found an instance of [{$impostorClass}].", 6, $previous ); } }
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/src/Exceptions/RecordWithoutFilterableColumnsException.php
src/Exceptions/RecordWithoutFilterableColumnsException.php
<?php namespace Iksaku\Laravel\MassUpdate\Exceptions; use Throwable; use UnexpectedValueException; class RecordWithoutFilterableColumnsException extends UnexpectedValueException { public function __construct(Throwable $previous = null) { parent::__construct( "None of the specified 'uniqueBy' columns where found on current record.", 2, $previous ); } }
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/src/Exceptions/OrphanValueException.php
src/Exceptions/OrphanValueException.php
<?php namespace Iksaku\Laravel\MassUpdate\Exceptions; use Throwable; use UnexpectedValueException; class OrphanValueException extends UnexpectedValueException { public function __construct(mixed $orphanValue, Throwable $previous = null) { parent::__construct( "Expected column name on which value should be updated, but none was given.\n" . "Affected value: $orphanValue", 4, $previous ); } }
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/src/Exceptions/EmptyUniqueByException.php
src/Exceptions/EmptyUniqueByException.php
<?php namespace Iksaku\Laravel\MassUpdate\Exceptions; use Throwable; use UnexpectedValueException; class EmptyUniqueByException extends UnexpectedValueException { public function __construct(Throwable $previous = null) { parent::__construct( 'Second parameter expects an array of column names, used to properly filter your mass updatable values, but no names were given.', 1, $previous ); } }
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/src/Exceptions/MissingFilterableColumnsException.php
src/Exceptions/MissingFilterableColumnsException.php
<?php namespace Iksaku\Laravel\MassUpdate\Exceptions; use Throwable; use UnexpectedValueException; class MissingFilterableColumnsException extends UnexpectedValueException { public function __construct(array $missingColumns, Throwable $previous = null) { parent::__construct( "One of your records is missing some of the specified 'uniqueBy' columns. Make sure to include them all:\n" . '[' . implode(', ', $missingColumns) . ']', 7, $previous ); } }
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/src/Exceptions/MassUpdatingAndFilteringModelUsingTheSameColumn.php
src/Exceptions/MassUpdatingAndFilteringModelUsingTheSameColumn.php
<?php namespace Iksaku\Laravel\MassUpdate\Exceptions; use Throwable; use UnexpectedValueException; class MassUpdatingAndFilteringModelUsingTheSameColumn extends UnexpectedValueException { public function __construct(array $columns, Throwable $previous = null) { parent::__construct( "It appears that an Eloquent Model's column was updated " . 'and is being used at the same time for mass filtering. ' . 'This may cause filtering issues and may not even update the value properly. ' . "Affected columns:\n - " . implode("\n - ", $columns), 5, $previous ); } }
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/tests/Pest.php
tests/Pest.php
<?php /* |-------------------------------------------------------------------------- | Test Case |-------------------------------------------------------------------------- | | The closure you provide to your test functions is always bound to a specific PHPUnit test | case class. By default, that class is "PHPUnit\Framework\TestCase". Of course, you may | need to change it using the "uses()" function to bind a different classes or traits. | */ use Iksaku\Laravel\MassUpdate\Tests\TestCase; uses(TestCase::class)->in('Feature'); /* |-------------------------------------------------------------------------- | Expectations |-------------------------------------------------------------------------- | | When you're writing tests, you often need to check that values meet certain conditions. The | "expect()" function gives you access to a set of "expectations" methods that you can use | to assert different things. Of course, you may extend the Expectation API at any time. | */ //expect()->extend('toBeOne', function () { // return $this->toBe(1); //}); /* |-------------------------------------------------------------------------- | Functions |-------------------------------------------------------------------------- | | While Pest is very powerful out-of-the-box, you may have some testing code specific to your | project that you don't want to repeat in every file. Here you can also expose helpers as | global functions to help you to reduce the number of lines of code in your test files. | */ //function something() //{ // // .. //}
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/tests/TestCase.php
tests/TestCase.php
<?php namespace Iksaku\Laravel\MassUpdate\Tests; use Illuminate\Database\Eloquent\Factories\Factory; use Illuminate\Foundation\Testing\RefreshDatabase; use Orchestra\Testbench\TestCase as Orchestra; class TestCase extends Orchestra { use RefreshDatabase; protected function setUp(): void { parent::setUp(); Factory::guessFactoryNamesUsing( fn (string $modelName) => 'Iksaku\\Laravel\\MassUpdate\\Tests\\Database\\Factories\\'.class_basename($modelName).'Factory' ); } public function getEnvironmentSetUp($app) { config()->set('database.default', 'testing'); config()->set('database.connections.testing', [ 'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '', ]); } public function defineDatabaseMigrations() { $this->loadMigrationsFrom(__DIR__ . '/database/migrations'); } }
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/tests/app/Models/CustomUser.php
tests/app/Models/CustomUser.php
<?php namespace Iksaku\Laravel\MassUpdate\Tests\App\Models; class CustomUser extends User { public const UPDATED_AT = 'custom_updated_at'; }
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/tests/app/Models/User.php
tests/app/Models/User.php
<?php namespace Iksaku\Laravel\MassUpdate\Tests\App\Models; use Carbon\Carbon; use Iksaku\Laravel\MassUpdate\MassUpdatable; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; /** * @property string $username * @property string|null $name * @property int $rank * @property bool $can_code * @property Carbon $updated_at */ class User extends Model { use HasFactory; use MassUpdatable; protected $guarded = []; protected $casts = [ 'rank' => 'int', 'height' => 'float', 'can_code' => 'bool', ]; public function expenses(): HasMany { return $this->hasMany(Expense::class); } }
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/tests/app/Models/Expense.php
tests/app/Models/Expense.php
<?php namespace Iksaku\Laravel\MassUpdate\Tests\App\Models; use Iksaku\Laravel\MassUpdate\MassUpdatable; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; /** * @property int $year * @property string $quarter * @property float $total */ class Expense extends Model { use HasFactory; use MassUpdatable; public $timestamps = false; protected $guarded = []; protected $casts = [ 'year' => 'int', 'total' => 'float', ]; public function user(): BelongsTo { return $this->belongsTo(User::class); } }
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/tests/Feature/FailsProperlyTest.php
tests/Feature/FailsProperlyTest.php
<?php use Iksaku\Laravel\MassUpdate\Exceptions\EmptyUniqueByException; use Iksaku\Laravel\MassUpdate\Exceptions\MassUpdatingAndFilteringModelUsingTheSameColumn; use Iksaku\Laravel\MassUpdate\Exceptions\MissingFilterableColumnsException; use Iksaku\Laravel\MassUpdate\Exceptions\OrphanValueException; use Iksaku\Laravel\MassUpdate\Exceptions\RecordWithoutFilterableColumnsException; use Iksaku\Laravel\MassUpdate\Exceptions\RecordWithoutUpdatableValuesException; use Iksaku\Laravel\MassUpdate\Exceptions\UnexpectedModelClassException; use Iksaku\Laravel\MassUpdate\Tests\App\Models\CustomUser; use Iksaku\Laravel\MassUpdate\Tests\App\Models\Expense; use Iksaku\Laravel\MassUpdate\Tests\App\Models\User; it('returns 0 when no updatable records are given', function () { $result = User::query()->massUpdate([]); expect($result)->toBe(0); }); it('fails when no columns are given to filter record values', function () { $this->expectException(EmptyUniqueByException::class); User::query()->massUpdate([ ['id' => 1, 'name' => 'Jorge'], ], []); }); it('fails when no filterable columns are found in a record', function () { $this->expectException(RecordWithoutFilterableColumnsException::class); User::query()->massUpdate([ ['name' => 'Jorge'], ]); }); it('fails when filterable columns are missing in a record', function () { $this->expectException(MissingFilterableColumnsException::class); User::query()->massUpdate( values: [['id' => 1, 'name' => 'Jorge']], uniqueBy: ['id', 'username'] ); }); it('fails when no updatable values are found in a record', function () { $this->expectException(RecordWithoutUpdatableValuesException::class); User::query()->massUpdate([ ['id' => 1], ]); }); it('fails when an orphan value is found in a record', function () { $this->expectException(OrphanValueException::class); User::query()->massUpdate([ ['id' => 1, 'Jorge González'], ]); }); it('fails when model is trying to update and filter on the same column', function () { /** @var User $user */ $user = User::factory()->create(); $user->fill([ 'id' => 2, 'name' => 'Jorge', ]); $this->expectException(MassUpdatingAndFilteringModelUsingTheSameColumn::class); User::query()->massUpdate([$user]); }); it('fails when trying to trying to update an unexpected model class', function (string $impostor) { $this->expectException(UnexpectedModelClassException::class); User::query()->massUpdate([ $impostor::factory()->create(), ]); })->with([ 'Completely Different Model Class' => [Expense::class], 'Extended Model Class' => [CustomUser::class], ]);
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/tests/Feature/FiltersByKeysTest.php
tests/Feature/FiltersByKeysTest.php
<?php use Iksaku\Laravel\MassUpdate\Tests\App\Models\User; use Illuminate\Support\Arr; use Illuminate\Support\Facades\DB; it('uses model\'s default key column if no other filtering columns are provided', function () { User::factory()->createMany([ ['name' => 'Jorge Gonzales'], ['name' => 'Gladys Martines'], ]); DB::enableQueryLog(); User::query()->massUpdate([ ['id' => 1, 'name' => 'Jorge González'], ['id' => 2, 'name' => 'Gladys Martínez'], ]); expect(User::all())->sequence( fn ($user) => $user->name->toEqual('Jorge González'), fn ($user) => $user->name->toEqual('Gladys Martínez'), ); expect(Arr::first(DB::getQueryLog())['query'])->toContain('id'); }); it('can use a different filter column', function () { User::factory()->createMany([ ['username' => 'iksaku', 'name' => 'Jorge Gonzalez'], ['username' => 'gm_mtz', 'name' => 'Gladys Martines'], ]); DB::enableQueryLog(); User::query()->massUpdate( values: [ ['username' => 'iksaku', 'name' => 'Jorge González'], ['username' => 'gm_mtz', 'name' => 'Gladys Martínez'], ], uniqueBy: 'username' ); expect(User::all())->sequence( fn ($user) => $user->name->toEqual('Jorge González'), fn ($user) => $user->name->toEqual('Gladys Martínez'), ); expect(Arr::first(DB::getQueryLog())['query'])->toContain('name'); }); it('can use multiple filter columns', function () { User::factory()->createMany([ ['username' => 'iksaku', 'name' => 'Jorge Gonzalez'], ['username' => 'gm_mtz', 'name' => 'Gladys Martines'], ]); DB::enableQueryLog(); User::query()->massUpdate( values: [ ['id' => 1, 'username' => 'iksaku', 'name' => 'Jorge González'], ['id' => 2, 'username' => 'gm_mtz', 'name' => 'Gladys Martínez'], ], uniqueBy: ['id', 'username'] ); expect(User::all())->sequence( fn ($user) => $user->name->toEqual('Jorge González'), fn ($user) => $user->name->toEqual('Gladys Martínez'), ); expect(Arr::first(DB::getQueryLog())['query']) ->toContain('id') ->toContain('name'); }); it('can specify custom mass-update key', function () { $customKeyUser = new class extends User { protected $table = 'users'; public function getMassUpdateKeyName(): string|array|null { return 'username'; } }; User::factory()->createMany([ ['username' => 'iksaku', 'name' => 'Jorge Gonzalez'], ['username' => 'gm_mtz', 'name' => 'Gladys Martines'], ]); DB::enableQueryLog(); $customKeyUser::query()->massUpdate( values: [ ['username' => 'iksaku', 'name' => 'Jorge González'], ['username' => 'gm_mtz', 'name' => 'Gladys Martínez'], ] ); expect(User::all())->sequence( fn ($user) => $user->name->toEqual('Jorge González'), fn ($user) => $user->name->toEqual('Gladys Martínez'), ); expect(Arr::first(DB::getQueryLog())['query']) ->toContain('username') ->toContain('name') ->not->toContain('id'); }); it('can specify multiple custom mass-update keys', function () { $customKeyUser = new class extends User { protected $table = 'users'; public function getMassUpdateKeyName(): string|array|null { return ['id', 'username']; } }; User::factory()->createMany([ ['username' => 'iksaku', 'name' => 'Jorge Gonzalez'], ['username' => 'gm_mtz', 'name' => 'Gladys Martines'], ]); DB::enableQueryLog(); $customKeyUser::query()->massUpdate( values: [ ['id' => 1, 'username' => 'iksaku', 'name' => 'Jorge González'], ['id' => 2, 'username' => 'gm_mtz', 'name' => 'Gladys Martínez'], ] ); expect(User::all())->sequence( fn ($user) => $user->name->toEqual('Jorge González'), fn ($user) => $user->name->toEqual('Gladys Martínez'), ); expect(Arr::first(DB::getQueryLog())['query']) ->toContain('id') ->toContain('username') ->toContain('name'); });
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/tests/Feature/CompileMultipleTypesTest.php
tests/Feature/CompileMultipleTypesTest.php
<?php use Iksaku\Laravel\MassUpdate\Tests\App\Models\User; use Illuminate\Support\Facades\DB; it('can compile NULL values', function () { $user = User::factory()->create(); DB::enableQueryLog(); User::query()->massUpdate([ $user->fill(['name' => null]), ]); expect(DB::getQueryLog()[0]['query'])->toContain('THEN NULL'); expect($user->refresh()->name)->toBeNull(); }); it('can compile boolean values', function (bool $value) { $user = User::factory()->create([ 'can_code' => ! $value, ]); expect($user->can_code)->toBe(! $value); DB::enableQueryLog(); User::query()->massUpdate([ $user->fill(['can_code' => $value]), ]); expect(DB::getQueryLog()[0]['query'])->toContain("THEN $value"); expect($user->refresh()->can_code)->toBe($value); })->with([ true, false, ]); it('can compile numeric values', function (int $rank, float $height) { $user = User::factory()->create(); expect($user) ->rank->toBeNull() ->height->toBeNull(); DB::enableQueryLog(); User::query()->massUpdate([ $user->fill(compact('rank', 'height')), ]); expect(DB::getQueryLog()[0]['query'])->toContain('THEN 10', "THEN '1.7'"); expect($user->refresh()) ->rank->toBe($rank) ->height->toBe($height); })->with([ [ 'rank' => 10, 'height' => 1.7, ], ]); it('can compile strings', function (string $name) { $user = User::factory()->create(); expect($user->name)->not->toBe($name); DB::enableQueryLog(); User::query()->massUpdate([ $user->fill(compact('name')), ]); expect($user->refresh()->name)->toBe($name); })->with([ 'simple string' => 'Jorge González', 'single quoted string' => "Jorge 'iksaku' González", 'double quoted string' => 'Jorge "iksaku" González', 'complex string' => '"\'Jorge \"\\\'iksaku\\\'\" González\'"', ]);
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/tests/Feature/MassUpdateQuietlyTest.php
tests/Feature/MassUpdateQuietlyTest.php
<?php use Iksaku\Laravel\MassUpdate\Tests\App\Models\CustomUser; use Iksaku\Laravel\MassUpdate\Tests\App\Models\Expense; use Iksaku\Laravel\MassUpdate\Tests\App\Models\User; use Illuminate\Support\Arr; use Illuminate\Support\Facades\DB; it('does not update timestamp of touched records without events', function () { $this->travelTo(now()->subDay()); User::factory()->createMany([ ['name' => 'Jorge Gonzales'], ['name' => 'Gladys Martines'], ['name' => 'Elena González'], ]); $this->travelBack(); DB::enableQueryLog(); User::query()->massUpdateQuietly([ ['id' => 1, 'name' => 'Jorge González'], ['id' => 2, 'name' => 'Gladys Martínez'], ]); expect( User::query()->where('updated_at', '>=', now()->startOfDay())->count() )->toBe(0); expect( User::query()->where('updated_at', '<', now())->count() )->toBe(3); expect(Arr::first(DB::getQueryLog())['query'])->not()->toContain('updated_at'); }); it('does not update custom timestamp column of touched records without events', function () { $this->travelTo(now()->subDay()); CustomUser::factory()->createMany([ ['name' => 'Jorge Gonzales'], ['name' => 'Gladys Martines'], ['name' => 'Elena González'], ]); $this->travelBack(); DB::enableQueryLog(); CustomUser::query()->massUpdateQuietly([ ['id' => 1, 'name' => 'Jorge González'], ['id' => 2, 'name' => 'Gladys Martínez'], ]); expect( CustomUser::query()->where('custom_updated_at', '>=', now()->startOfDay())->count() )->toBe(0); expect( CustomUser::query()->where('custom_updated_at', '<', now())->count() )->toBe(3); expect(Arr::first(DB::getQueryLog())['query'])->not()->toContain('custom_updated_at'); }); it('does not touch update timestamp if model does not use it even without events', function () { Expense::factory()->createMany([ ['total' => 20], ['total' => 4], ]); DB::enableQueryLog(); Expense::query()->massUpdateQuietly([ ['id' => 1, 'total' => 4], ['id' => 2, 'total' => 20], ]); expect(Expense::all())->sequence( fn ($expense) => $expense->total->toBe(4.0), fn ($expense) => $expense->total->toBe(20.0), ); expect(Arr::first(DB::getQueryLog())['query'])->not->toContain('updated_at'); });
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/tests/Feature/InteractsWithModelsTest.php
tests/Feature/InteractsWithModelsTest.php
<?php use Iksaku\Laravel\MassUpdate\Tests\App\Models\User; use Illuminate\Support\Facades\DB; it('can process array of changed models', function () { /** @var User[] $users */ $users = User::factory()->count(2)->create(); $users[0]->name = 'Jorge'; $users[1]->name = 'Elena'; User::query()->massUpdate($users); expect(User::all())->sequence( fn ($user) => $user->name->toEqual('Jorge'), fn ($user) => $user->name->toEqual('Elena'), ); }); it('skips models that have not changed', function () { /** @var User[] $users */ $users = User::factory()->count(2)->create(); $users[0]->name = 'Jorge'; expect(User::query()->massUpdate($users))->toBe(1); expect(User::query()->first()->name)->toBe('Jorge'); }); it('skips query execution if there are no updates in given models', function () { $users = User::factory()->count(10)->create(); DB::enableQueryLog(); expect(User::query()->massUpdate($users))->toBe(0); expect(DB::getQueryLog())->toHaveCount(0); });
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/tests/Feature/TouchesTimestampTest.php
tests/Feature/TouchesTimestampTest.php
<?php use Iksaku\Laravel\MassUpdate\Tests\App\Models\CustomUser; use Iksaku\Laravel\MassUpdate\Tests\App\Models\Expense; use Iksaku\Laravel\MassUpdate\Tests\App\Models\User; use Illuminate\Support\Arr; use Illuminate\Support\Facades\DB; it('updates timestamps of touched records', function () { $this->travelTo(now()->subDay()); User::factory()->createMany([ ['name' => 'Jorge Gonzales'], ['name' => 'Gladys Martines'], ['name' => 'Elena González'], ]); $this->travelBack(); DB::enableQueryLog(); User::query()->massUpdate([ ['id' => 1, 'name' => 'Jorge González'], ['id' => 2, 'name' => 'Gladys Martínez'], ]); expect( User::query()->where('updated_at', '>=', now()->startOfDay())->count() )->toBe(2); expect( User::query()->where('updated_at', '<', now())->count() )->toBe(1); expect(Arr::first(DB::getQueryLog())['query'])->toContain('updated_at'); }); it('updates custom timestamp column of touched records', function () { $this->travelTo(now()->subDay()); CustomUser::factory()->createMany([ ['name' => 'Jorge Gonzales'], ['name' => 'Gladys Martines'], ['name' => 'Elena González'], ]); $this->travelBack(); DB::enableQueryLog(); CustomUser::query()->massUpdate([ ['id' => 1, 'name' => 'Jorge González'], ['id' => 2, 'name' => 'Gladys Martínez'], ]); expect( CustomUser::query()->where('custom_updated_at', '>=', now()->startOfDay())->count() )->toBe(2); expect( CustomUser::query()->where('custom_updated_at', '<', now())->count() )->toBe(1); expect(Arr::first(DB::getQueryLog())['query'])->toContain('custom_updated_at'); }); it('does not touch update timestamp if model does not use it', function () { Expense::factory()->createMany([ ['total' => 20], ['total' => 4], ]); DB::enableQueryLog(); Expense::query()->massUpdate([ ['id' => 1, 'total' => 4], ['id' => 2, 'total' => 20], ]); expect(Expense::all())->sequence( fn ($expense) => $expense->total->toBe(4.0), fn ($expense) => $expense->total->toBe(20.0), ); expect(Arr::first(DB::getQueryLog())['query'])->not->toContain('updated_at'); });
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/tests/Feature/QueryInActionTest.php
tests/Feature/QueryInActionTest.php
<?php use Iksaku\Laravel\MassUpdate\Tests\App\Models\User; it('updates multiple records in a single query', function () { User::factory()->createMany([ ['name' => 'Jorge Gonzales'], ['name' => 'Gladys Martines'], ]); User::query()->massUpdate([ ['id' => 1, 'name' => 'Jorge González'], ['id' => 2, 'name' => 'Gladys Martínez'], ]); expect(User::all())->sequence( fn ($user) => $user->name->toEqual('Jorge González'), fn ($user) => $user->name->toEqual('Gladys Martínez'), ); }); it('can chain other query statements', function () { $this->travelTo(now()->startOfDay()); User::factory()->count(10)->create(); $this->travelBack(); User::query() ->where('id', '<', 5) ->massUpdate([ ['id' => 1, 'name' => 'Updated User'], ['id' => 4, 'name' => 'Another Updated User'], ['id' => 5, 'name' => 'Ignored User'], ['id' => 10, 'name' => 'Another Ignored User'], ]); expect( User::query()->where('updated_at', '>', now()->startOfDay())->count() )->toBe(2); }); it('can update multiple value types', function (string $attribute, mixed $value) { User::factory()->create(); User::query()->massUpdate( values: [[ 'id' => 1, $attribute => $value, ]] ); expect(User::query()->first()->getAttribute($attribute))->toEqual($value); })->with([ 'int' => ['rank', 1], 'null' => ['name', null], 'string' => ['name', 'Jorge González'], 'bool (true)' => ['can_code', true], 'bool (false)' => ['can_code', false], ]);
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/tests/database/factories/CustomUserFactory.php
tests/database/factories/CustomUserFactory.php
<?php namespace Iksaku\Laravel\MassUpdate\Tests\Database\Factories; use Iksaku\Laravel\MassUpdate\Tests\App\Models\CustomUser; use Illuminate\Database\Eloquent\Factories\Factory; class CustomUserFactory extends Factory { protected $model = CustomUser::class; public function definition(): array { return [ 'name' => $this->faker->name, ]; } }
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/tests/database/factories/UserFactory.php
tests/database/factories/UserFactory.php
<?php namespace Iksaku\Laravel\MassUpdate\Tests\Database\Factories; use Iksaku\Laravel\MassUpdate\Tests\App\Models\User; use Illuminate\Database\Eloquent\Factories\Factory; class UserFactory extends Factory { protected $model = User::class; public function definition(): array { return [ 'username' => $this->faker->userName, 'name' => $this->faker->name, ]; } }
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/tests/database/factories/ExpenseFactory.php
tests/database/factories/ExpenseFactory.php
<?php namespace Iksaku\Laravel\MassUpdate\Tests\Database\Factories; use Iksaku\Laravel\MassUpdate\Tests\App\Models\Expense; use Iksaku\Laravel\MassUpdate\Tests\App\Models\User; use Illuminate\Database\Eloquent\Factories\Factory; class ExpenseFactory extends Factory { protected $model = Expense::class; public function definition(): array { return [ 'user_id' => User::factory(), 'year' => $this->faker->year(), 'quarter' => 'Q' . $this->faker->numberBetween(0, 4), 'total' => $this->faker->randomFloat(2, 10, 100), ]; } }
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/tests/database/migrations/2021_06_14_000002_create_custom_users_test_table.php
tests/database/migrations/2021_06_14_000002_create_custom_users_test_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateCustomUsersTestTable extends Migration { public function up(): void { Schema::create('custom_users', function (Blueprint $table) { $table->id(); $table->string('name'); $table->timestamp('created_at')->nullable(); $table->timestamp('custom_updated_at')->nullable(); }); } public function down(): void { Schema::drop('custom_users'); } }
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/tests/database/migrations/2021_06_14_000000_create_users_test_table.php
tests/database/migrations/2021_06_14_000000_create_users_test_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateUsersTestTable extends Migration { public function up(): void { Schema::create('users', function (Blueprint $table) { $table->id(); $table->string('username'); $table->string('name')->nullable(); $table->unsignedTinyInteger('rank')->nullable(); $table->decimal('height')->unsigned()->nullable(); $table->boolean('can_code')->default(false); $table->timestamps(); }); } public function down(): void { Schema::drop('users'); } }
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
iksaku/laravel-mass-update
https://github.com/iksaku/laravel-mass-update/blob/99f363af0a0b14ee83e50dd23f712e8033f4e2b1/tests/database/migrations/2021_06_14_000001_create_expenses_test_table.php
tests/database/migrations/2021_06_14_000001_create_expenses_test_table.php
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateExpensesTestTable extends Migration { public function up(): void { Schema::create('expenses', function (Blueprint $table) { $table->id(); $table->unsignedInteger('year'); $table->string('quarter', 2); $table->decimal('total')->unsigned(); $table->foreignId('user_id') ->constrained() ->cascadeOnDelete(); }); } public function down(): void { Schema::drop('expenses'); } }
php
MIT
99f363af0a0b14ee83e50dd23f712e8033f4e2b1
2026-01-05T05:10:14.152241Z
false
camya/filament-title-with-slug
https://github.com/camya/filament-title-with-slug/blob/352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8/src/helpers.php
src/helpers.php
<?php
php
MIT
352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8
2026-01-05T05:10:10.355011Z
false
camya/filament-title-with-slug
https://github.com/camya/filament-title-with-slug/blob/352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8/src/FilamentTitleWithSlugServiceProvider.php
src/FilamentTitleWithSlugServiceProvider.php
<?php namespace Camya\Filament; use Filament\PluginServiceProvider; use Spatie\LaravelPackageTools\Package; class FilamentTitleWithSlugServiceProvider extends PluginServiceProvider { public function configurePackage(Package $package): void { $package ->name('filament-title-with-slug') ->hasConfigFile() ->hasViews() ->hasTranslations(); } protected function getStyles(): array { return [ 'filament-title-with-slug-styles' => __DIR__.'/../resources/dist/filament-title-with-slug.css', ]; } }
php
MIT
352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8
2026-01-05T05:10:10.355011Z
false
camya/filament-title-with-slug
https://github.com/camya/filament-title-with-slug/blob/352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8/src/Forms/Components/TitleWithSlugInput.php
src/Forms/Components/TitleWithSlugInput.php
<?php namespace Camya\Filament\Forms\Components; use Camya\Filament\Forms\Fields\SlugInput; use Closure; use Filament\Forms\Components\Group; use Filament\Forms\Components\Hidden; use Filament\Forms\Components\TextInput; use Illuminate\Database\Eloquent\Model; use Illuminate\Support\Str; class TitleWithSlugInput { public static function make( // Model fields string|null $fieldTitle = null, string|null $fieldSlug = null, // Url string|Closure|null $urlPath = '/', string|Closure|null $urlHost = null, bool $urlHostVisible = true, bool|Closure $urlVisitLinkVisible = true, null|Closure|string $urlVisitLinkLabel = null, null|Closure $urlVisitLinkRoute = null, // Title string|Closure|null $titleLabel = null, string|null $titlePlaceholder = null, array|Closure|null $titleExtraInputAttributes = null, array $titleRules = [ 'required', ], array $titleRuleUniqueParameters = [], bool|Closure $titleIsReadonly = false, bool|Closure $titleAutofocus = true, null|Closure $titleAfterStateUpdated = null, // Slug string|null $slugLabel = null, array $slugRules = [ 'required', ], array $slugRuleUniqueParameters = [], bool|Closure $slugIsReadonly = false, null|Closure $slugAfterStateUpdated = null, null|Closure $slugSlugifier = null, string|Closure|null $slugRuleRegex = '/^[a-z0-9\-\_]*$/', string|Closure|null $slugLabelPostfix = null, ): Group { $fieldTitle = $fieldTitle ?? config('filament-title-with-slug.field_title'); $fieldSlug = $fieldSlug ?? config('filament-title-with-slug.field_slug'); $urlHost = $urlHost ?? config('filament-title-with-slug.url_host'); /** Input: "Title" */ $textInput = TextInput::make($fieldTitle) ->disabled($titleIsReadonly) ->autofocus($titleAutofocus) ->reactive() ->disableAutocomplete() ->rules($titleRules) ->extraInputAttributes($titleExtraInputAttributes ?? ['class' => 'text-xl font-semibold']) ->beforeStateDehydrated(fn (TextInput $component, $state) => $component->state(trim($state))) ->afterStateUpdated( function ( $state, Closure $set, Closure $get, string $context, ?Model $record, TextInput $component ) use ( $slugSlugifier, $fieldSlug, $titleAfterStateUpdated, ) { $slugAutoUpdateDisabled = $get('slug_auto_update_disabled'); if ($context === 'edit' && filled($record)) { $slugAutoUpdateDisabled = true; } if (! $slugAutoUpdateDisabled && filled($state)) { $set($fieldSlug, self::slugify($slugSlugifier, $state)); } if ($titleAfterStateUpdated) { $component->evaluate($titleAfterStateUpdated); } } ); if (in_array('required', $titleRules, true)) { $textInput->required(); } if ($titlePlaceholder !== '') { $textInput->placeholder($titlePlaceholder ?: fn () => Str::of($fieldTitle)->headline()); } if (! $titleLabel) { $textInput->disableLabel(); } if ($titleLabel) { $textInput->label($titleLabel); } if ($titleRuleUniqueParameters) { $textInput->unique(...$titleRuleUniqueParameters); } /** Input: "Slug" (+ view) */ $slugInput = SlugInput::make($fieldSlug) // Custom SlugInput methods ->slugInputVisitLinkRoute($urlVisitLinkRoute) ->slugInputVisitLinkLabel($urlVisitLinkLabel) ->slugInputUrlVisitLinkVisible($urlVisitLinkVisible) ->slugInputContext(fn ($context) => $context === 'create' ? 'create' : 'edit') ->slugInputRecordSlug(fn (?Model $record) => $record?->getAttributeValue($fieldSlug)) ->slugInputModelName( fn (?Model $record) => $record ? Str::of(class_basename($record))->headline() : '' ) ->slugInputLabelPrefix($slugLabel) ->slugInputBasePath($urlPath) ->slugInputBaseUrl($urlHost) ->slugInputShowUrl($urlHostVisible) ->slugInputSlugLabelPostfix($slugLabelPostfix) // Default TextInput methods ->readonly($slugIsReadonly) ->reactive() ->disableAutocomplete() ->disableLabel() ->regex($slugRuleRegex) ->rules($slugRules) ->afterStateUpdated( function ( $state, Closure $set, Closure $get, TextInput $component ) use ( $slugSlugifier, $fieldTitle, $fieldSlug, $slugAfterStateUpdated, ) { $text = trim($state) === '' ? $get($fieldTitle) : $get($fieldSlug); $set($fieldSlug, self::slugify($slugSlugifier, $text)); $set('slug_auto_update_disabled', true); if ($slugAfterStateUpdated) { $component->evaluate($slugAfterStateUpdated); } } ); if (in_array('required', $slugRules, true)) { $slugInput->required(); } $slugRuleUniqueParameters ? $slugInput->unique(...$slugRuleUniqueParameters) : $slugInput->unique(ignorable: fn (?Model $record) => $record); /** Input: "Slug Auto Update Disabled" (Hidden) */ $hiddenInputSlugAutoUpdateDisabled = Hidden::make('slug_auto_update_disabled') ->dehydrated(false); /** Group */ return Group::make() ->schema([ $textInput, $slugInput, $hiddenInputSlugAutoUpdateDisabled, ]); } /** Fallback slugifier, over-writable with slugSlugifier parameter. */ protected static function slugify(Closure|null $slugifier, string|null $text): string { if (is_null($text) || ! trim($text)) { return ''; } return is_callable($slugifier) ? $slugifier($text) : Str::slug($text); } }
php
MIT
352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8
2026-01-05T05:10:10.355011Z
false
camya/filament-title-with-slug
https://github.com/camya/filament-title-with-slug/blob/352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8/src/Forms/Fields/SlugInput.php
src/Forms/Fields/SlugInput.php
<?php namespace Camya\Filament\Forms\Fields; use Closure; use Filament\Forms\Components\TextInput; use Illuminate\Support\Str; class SlugInput extends TextInput { protected string $view = 'filament-title-with-slug::forms.fields.slug-input'; protected string|Closure|null $context = null; protected string|Closure $basePath = '/'; protected string|Closure|null $baseUrl = null; protected bool $showUrl = true; protected bool $cancelled = false; protected Closure $recordSlug; protected bool|Closure $readonly = false; protected string $labelPrefix; protected Closure|null $visitLinkRoute = null; protected string|Closure|null $visitLinkLabel = null; protected bool|Closure $slugInputUrlVisitLinkVisible = true; protected Closure|null $slugInputModelName = null; protected string|Closure|null $slugLabelPostfix = null; public function slugInputUrlVisitLinkVisible(bool|Closure $slugInputUrlVisitLinkVisible): static { $this->slugInputUrlVisitLinkVisible = $slugInputUrlVisitLinkVisible; return $this; } public function getSlugInputUrlVisitLinkVisible(): string|null { return $this->evaluate($this->slugInputUrlVisitLinkVisible); } public function slugInputModelName(Closure|null $slugInputModelName): static { $this->slugInputModelName = $slugInputModelName; return $this; } public function getSlugInputModelName(): string|null { return $this->evaluate($this->slugInputModelName); } public function slugInputVisitLinkRoute(Closure|null $visitLinkRoute): static { $this->visitLinkRoute = $visitLinkRoute; return $this; } public function getVisitLinkRoute(): string|null { return $this->evaluate($this->visitLinkRoute); } public function slugInputVisitLinkLabel(string|Closure|null $visitLinkLabel): static { $this->visitLinkLabel = $visitLinkLabel; return $this; } public function getVisitLinkLabel(): string { $label = $this->evaluate($this->visitLinkLabel); if ($label === '') { return ''; } return $label ?: trans('filament-title-with-slug::package.permalink_label_link_visit').' '.$this->getSlugInputModelName(); } public function slugInputLabelPrefix(string|null $labelPrefix): static { $this->labelPrefix = $labelPrefix ?? trans('filament-title-with-slug::package.permalink_label'); return $this; } public function getLabelPrefix(): string { return $this->evaluate($this->labelPrefix); } public function readonly(bool|Closure $readonly): static { $this->readonly = $readonly; return $this; } public function getReadonly(): string { return $this->evaluate($this->readonly); } public function slugInputContext(string|Closure|null $context): static { $this->context = $context; return $this; } public function getContext(): ?string { return $this->evaluate($this->context); } public function slugInputSlugLabelPostfix(string|Closure|null $slugLabelPostfix): static { $this->slugLabelPostfix = $slugLabelPostfix; return $this; } public function getSlugLabelPostfix(): string|null { return $this->evaluate($this->slugLabelPostfix); } public function slugInputRecordSlug(Closure $recordSlug): static { $this->recordSlug = $recordSlug; return $this; } public function getRecordSlug(): ?string { return $this->evaluate($this->recordSlug); } public function getRecordUrl(): ?string { if (! $this->getRecordSlug()) { return null; } $visitLinkRoute = $this->getVisitLinkRoute(); return $visitLinkRoute ? $this->getVisitLinkRoute() : $this->getBaseUrl().$this->getBasePath().$this->evaluate($this->recordSlug); } public function slugInputBasePath(string|Closure|null $path): static { $this->basePath = ! is_null($path) ? $path : $this->basePath; return $this; } public function slugInputBaseUrl(string|Closure|null $url): static { $this->baseUrl = $url ?: config('app.url'); return $this; } public function getBaseUrl(): string { return Str::of($this->evaluate($this->baseUrl))->rtrim('/'); } public function slugInputShowUrl(bool $showUrl): static { $this->showUrl = $showUrl; return $this; } public function getShowUrl(): ?bool { return $this->showUrl; } public function getFullBaseUrl(): ?string { return $this->showUrl ? $this->getBaseUrl().$this->getBasePath() : $this->getBasePath(); } public function getBasePath(): string { return $this->evaluate($this->basePath); } }
php
MIT
352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8
2026-01-05T05:10:10.355011Z
false
camya/filament-title-with-slug
https://github.com/camya/filament-title-with-slug/blob/352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8/tests/Pest.php
tests/Pest.php
<?php use Camya\Filament\Tests\TestCase; uses(TestCase::class)->in(__DIR__);
php
MIT
352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8
2026-01-05T05:10:10.355011Z
false
camya/filament-title-with-slug
https://github.com/camya/filament-title-with-slug/blob/352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8/tests/TestCase.php
tests/TestCase.php
<?php namespace Camya\Filament\Tests; use BladeUI\Heroicons\BladeHeroiconsServiceProvider; use BladeUI\Icons\BladeIconsServiceProvider; use Camya\Filament\FilamentTitleWithSlugServiceProvider; use Filament\FilamentServiceProvider; use Filament\Forms\FormsServiceProvider; use Filament\Support\SupportServiceProvider; use Livewire\LivewireServiceProvider; use Orchestra\Testbench\TestCase as Orchestra; class TestCase extends Orchestra { protected function setUp(): void { parent::setUp(); } protected function getPackageProviders($app) { return [ FilamentTitleWithSlugServiceProvider::class, FilamentServiceProvider::class, LivewireServiceProvider::class, FormsServiceProvider::class, SupportServiceProvider::class, BladeIconsServiceProvider::class, BladeHeroiconsServiceProvider::class, ]; } public function getEnvironmentSetUp($app) { config()->set('database.default', 'testing'); } }
php
MIT
352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8
2026-01-05T05:10:10.355011Z
false
camya/filament-title-with-slug
https://github.com/camya/filament-title-with-slug/blob/352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8/tests/Support/RecordFactory.php
tests/Support/RecordFactory.php
<?php namespace Camya\Filament\Tests\Support; use Illuminate\Database\Eloquent\Factories\Factory; class RecordFactory extends Factory { protected $model = Record::class; public function definition() { return []; } }
php
MIT
352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8
2026-01-05T05:10:10.355011Z
false
camya/filament-title-with-slug
https://github.com/camya/filament-title-with-slug/blob/352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8/tests/Support/TestableForm.php
tests/Support/TestableForm.php
<?php namespace Camya\Filament\Tests\Support; use Filament\Forms\Concerns\InteractsWithForms; use Filament\Forms\Contracts\HasForms; use Illuminate\Database\Eloquent\Model; use Livewire\Component; class TestableForm extends Component implements HasForms { use InteractsWithForms; public static array $formSchema = []; public array $data = []; public $record; protected $listeners = ['$refresh']; public function render() { return view('filament-title-with-slug::tests.support.testable-form'); } protected function getFormModel(): Model|string|null { return $this->record; } public function getFormSchema(): array { return static::$formSchema; } public function getFormStatePath(): ?string { return 'data'; } }
php
MIT
352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8
2026-01-05T05:10:10.355011Z
false
camya/filament-title-with-slug
https://github.com/camya/filament-title-with-slug/blob/352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8/tests/Support/Record.php
tests/Support/Record.php
<?php namespace Camya\Filament\Tests\Support; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; class Record extends Model { use HasFactory; protected $guarded = []; public static function newFactory(): RecordFactory { return RecordFactory::new(); } }
php
MIT
352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8
2026-01-05T05:10:10.355011Z
false
camya/filament-title-with-slug
https://github.com/camya/filament-title-with-slug/blob/352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8/tests/Forms/Components/TitleWithSlugInputTest.php
tests/Forms/Components/TitleWithSlugInputTest.php
<?php use Camya\Filament\Forms\Components\TitleWithSlugInput; use Camya\Filament\Tests\Support\Record; use Camya\Filament\Tests\Support\TestableForm; use Illuminate\Database\Eloquent\Model; use Livewire\Livewire; it('returns OK if component is used', function () { TestableForm::$formSchema = [ TitleWithSlugInput::make(), ]; $component = Livewire::test(TestableForm::class); $component->assertOk(); }); it('fills view correctly with default component parameters', function () { TestableForm::$formSchema = [ TitleWithSlugInput::make(), ]; $component = Livewire::test(TestableForm::class) ->set([ 'data.title' => 'Persisted Title', 'data.slug' => 'persisted-slug', ]); $component ->assertSeeHtml('wire:model="data.title"') ->assertSeeHtml('wire:model="data.slug"') ->assertSet('data.title', 'Persisted Title') ->assertSet('data.slug', 'persisted-slug') ->assertSeeHtml('<span class="mr-1">persisted-slug</span>'); }); it('fills view correctly with overwritten component parameters', function () { TestableForm::$formSchema = [ TitleWithSlugInput::make( fieldTitle: 'TitleFieldName', fieldSlug: 'SlugFieldName', urlVisitLinkLabel: '*Visit Link Label*', titleLabel: '*Title Label*', titlePlaceholder: '*Title Placeholder*', slugLabel: '*Slug Label*', ), ]; $component = Livewire::test(TestableForm::class) ->set([ 'data.TitleFieldName' => 'Persisted Title', 'data.SlugFieldName' => 'persisted-slug', ]); $component ->assertSeeHtml('wire:model="data.TitleFieldName"') ->assertSeeHtml('wire:model="data.SlugFieldName"') ->assertSee('*Title Label*') ->assertSee('*Slug Label*') ->assertSee('*Visit Link Label*') ->assertSeeHtml('placeholder="*Title Placeholder*"'); }); it('does not show the visit link if it is set invisible', function () { TestableForm::$formSchema = [ TitleWithSlugInput::make( urlVisitLinkVisible: false, urlVisitLinkLabel: '*Visit Link Label*', ), ]; $component = Livewire::test(TestableForm::class) ->set([ 'data.TitleFieldName' => 'Persisted Title', 'data.SlugFieldName' => 'persisted-slug', ]); $component->assertDontSee('*Visit Link Label*'); }); it('generates the default visit link from host + path + slug', function () { config()->set('filament-title-with-slug.url_host', 'https://www.camya.com'); TestableForm::$formSchema = [ TitleWithSlugInput::make( urlPath: '/blog/' ), ]; $component = Livewire::test(TestableForm::class, [ 'record' => new Record([ 'title' => 'Persisted Title', 'slug' => 'persisted-slug', ]), ]); $component->assertSeeHtml('https://www.camya.com/blog/persisted-slug'); }); it('generates a custom visit link for subdomain', function () { TestableForm::$formSchema = [ TitleWithSlugInput::make( urlPath: '', urlHostVisible: false, urlVisitLinkRoute: fn (?Model $record) => $record?->slug ? 'https://'.$record->slug.'.camya.com' : null, slugLabelPostfix: '.camya.com', ), ]; $component = Livewire::test(TestableForm::class, [ 'record' => new Record([ 'title' => 'My Subdomain', 'slug' => 'my-subdomain', ]), ]); $component ->assertSeeHtml('https://my-subdomain.camya.com') ->assertSeeHtml('>.camya.com<'); }); it('allows generating a URL with an empty slug, if slug has no required rule.', function () { config()->set('filament-title-with-slug.url_host', 'https://www.camya.com'); TestableForm::$formSchema = [ TitleWithSlugInput::make( slugRules: [], ), ]; $component = Livewire::test(TestableForm::class, [ 'record' => new Record([ 'title' => 'My Homepage', 'slug' => '/', ]), ]); $component ->assertSeeHtml("!editing ? 'https://www.camya.com/' : '/'"); });
php
MIT
352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8
2026-01-05T05:10:10.355011Z
false
camya/filament-title-with-slug
https://github.com/camya/filament-title-with-slug/blob/352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8/config/filament-title-with-slug.php
config/filament-title-with-slug.php
<?php return [ /* |-------------------------------------------------------------------------- | Model Fields |-------------------------------------------------------------------------- | | The names of the fields in your model where the title and slug are stored. | | Overridable like: TitleWithSlugInput::make(fieldTitle: 'title') | */ 'field_title' => 'title', // Overridable with parameter (fieldTitle: 'title') 'field_slug' => 'slug', // Overridable with parameter (fieldSlug: 'title') /* |-------------------------------------------------------------------------- | Url |-------------------------------------------------------------------------- | | URL related config values. | */ 'url_host' => env('APP_URL'), // Overridable with parameter (urlHost: 'https://www.camya.com/') ];
php
MIT
352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8
2026-01-05T05:10:10.355011Z
false
camya/filament-title-with-slug
https://github.com/camya/filament-title-with-slug/blob/352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8/resources/lang/de/package.php
resources/lang/de/package.php
<?php return [ 'permalink_label' => 'Permalink:', 'permalink_label_link_visit' => 'Besuche', 'permalink_action_edit' => 'Bearbeiten', 'permalink_action_ok' => 'OK', 'permalink_action_reset' => 'Zurücksetzen', 'permalink_action_cancel' => 'Abbrechen', 'permalink_status_changed' => 'geändert', ];
php
MIT
352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8
2026-01-05T05:10:10.355011Z
false
camya/filament-title-with-slug
https://github.com/camya/filament-title-with-slug/blob/352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8/resources/lang/pt_BR/package.php
resources/lang/pt_BR/package.php
<?php return [ 'permalink_label' => 'Link Permanente:', 'permalink_label_link_visit' => 'Visitar', 'permalink_action_edit' => 'Editar', 'permalink_action_ok' => 'OK', 'permalink_action_reset' => 'Resetar', 'permalink_action_cancel' => 'Cancelar', 'permalink_status_changed' => 'alterado', ];
php
MIT
352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8
2026-01-05T05:10:10.355011Z
false
camya/filament-title-with-slug
https://github.com/camya/filament-title-with-slug/blob/352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8/resources/lang/en/package.php
resources/lang/en/package.php
<?php return [ 'permalink_label' => 'Permalink:', 'permalink_label_link_visit' => 'Visit', 'permalink_action_edit' => 'Edit', 'permalink_action_ok' => 'OK', 'permalink_action_reset' => 'Reset', 'permalink_action_cancel' => 'Cancel', 'permalink_status_changed' => 'changed', ];
php
MIT
352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8
2026-01-05T05:10:10.355011Z
false
camya/filament-title-with-slug
https://github.com/camya/filament-title-with-slug/blob/352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8/resources/lang/ar/package.php
resources/lang/ar/package.php
<?php return [ 'permalink_label' => 'الرابط:', 'permalink_label_link_visit' => 'زيارة', 'permalink_action_edit' => 'تعديل', 'permalink_action_ok' => 'موافق', 'permalink_action_reset' => 'إعادة الضبط', 'permalink_action_cancel' => 'إلغاء', 'permalink_status_changed' => 'تم التغيير', ];
php
MIT
352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8
2026-01-05T05:10:10.355011Z
false
camya/filament-title-with-slug
https://github.com/camya/filament-title-with-slug/blob/352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8/resources/lang/nl/package.php
resources/lang/nl/package.php
<?php return [ 'permalink_label' => 'Permalink:', 'permalink_label_link_visit' => 'Bezoeken', 'permalink_action_edit' => 'Bewerken', 'permalink_action_ok' => 'OK', 'permalink_action_reset' => 'Resetten', 'permalink_action_cancel' => 'Annuleren', 'permalink_status_changed' => 'aangepast', ];
php
MIT
352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8
2026-01-05T05:10:10.355011Z
false
camya/filament-title-with-slug
https://github.com/camya/filament-title-with-slug/blob/352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8/resources/lang/fr/package.php
resources/lang/fr/package.php
<?php return [ 'permalink_label' => 'Permalien :', 'permalink_label_link_visit' => 'Voir', 'permalink_action_edit' => 'Éditer', 'permalink_action_ok' => 'OK', 'permalink_action_reset' => 'Réinitialiser', 'permalink_action_cancel' => 'Annuler', 'permalink_status_changed' => 'modifié', ];
php
MIT
352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8
2026-01-05T05:10:10.355011Z
false
camya/filament-title-with-slug
https://github.com/camya/filament-title-with-slug/blob/352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8/resources/lang/id/package.php
resources/lang/id/package.php
<?php return [ 'permalink_label' => 'Tautan:', 'permalink_label_link_visit' => 'Kunjungi', 'permalink_action_edit' => 'Ubah', 'permalink_action_ok' => 'Ok', 'permalink_action_reset' => 'Reset', 'permalink_action_cancel' => 'Batal', 'permalink_status_changed' => 'berhasil diubah', ];
php
MIT
352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8
2026-01-05T05:10:10.355011Z
false
camya/filament-title-with-slug
https://github.com/camya/filament-title-with-slug/blob/352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8/resources/views/tests/support/testable-form.blade.php
resources/views/tests/support/testable-form.blade.php
<div> {{ $this->form }} </div>
php
MIT
352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8
2026-01-05T05:10:10.355011Z
false
camya/filament-title-with-slug
https://github.com/camya/filament-title-with-slug/blob/352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8/resources/views/forms/fields/slug-input.blade.php
resources/views/forms/fields/slug-input.blade.php
<x-forms::field-wrapper :id="$getId()" :label="$getLabel()" :label-sr-only="$isLabelHidden()" :helper-text="$getHelperText()" :hint="$getHint()" :hint-icon="$getHintIcon()" :required="$isRequired()" :state-path="$getStatePath()" class="-mt-3 filament-seo-slug-input-wrapper" > <div x-data="{ context: '{{ $getContext() }}', // edit or create state: $wire.entangle('{{ $getStatePath() }}'), // current slug value statePersisted: '', // slug value received from db stateInitial: '', // slug value before modification editing: false, modified: false, initModification: function() { this.stateInitial = this.state; if(!this.statePersisted) { this.statePersisted = this.state; } this.editing = true; setTimeout(() => $refs.slugInput.focus(), 75); {{--$nextTick(() => $refs.slugInput.focus());--}} }, submitModification: function() { if(!this.stateInitial) { this.state = ''; } else { this.state = this.stateInitial; } this.detectModification(); this.editing = false; }, cancelModification: function() { this.stateInitial = this.state; this.detectModification(); this.editing = false; }, resetModification: function() { this.stateInitial = this.statePersisted; this.detectModification(); }, detectModification: function() { this.modified = this.stateInitial !== this.statePersisted; }, }" x-on:submit.document="modified = false" > <div {{ $attributes->merge($getExtraAttributes())->class(['flex mx-1 items-center justify-between group text-sm filament-forms-text-input-component']) }} > @if($getReadonly()) <span class="flex"> <span class="mr-1">{{ $getLabelPrefix() }}</span> <span class="text-gray-400">{{ $getFullBaseUrl() }}</span> <span class="text-gray-400 font-semibold">{{ $getState() }}</span> </span> @if($getSlugInputUrlVisitLinkVisible()) <a href="{{ $getRecordUrl() }}" target="_blank" class=" filament-link cursor-pointer text-sm text-primary-600 underline inline-flex items-center justify-center space-x-1 hover:text-primary-500 dark:text-primary-500 dark:hover:text-primary-400 " > <span>{{ $getVisitLinkLabel() }}</span> <x-heroicon-o-external-link stroke-width="2" class="h-4 w-4" /> </a> @endif @else <span class=" @if(!$getState()) flex items-center gap-1 @endif " > <span>{{ $getLabelPrefix() }}</span> <span x-text="!editing ? '{{ $getFullBaseUrl() }}' : '{{ $getBasePath() }}'" class="text-gray-400" ></span> <a href="#" role="button" title="{{ trans('filament-title-with-slug::package.permalink_action_edit') }}" x-on:click.prevent="initModification()" x-show="!editing" class=" cursor-pointer font-semibold text-gray-400 inline-flex items-center justify-center hover:underline hover:text-primary-500 dark:hover:text-primary-400 " :class="context !== 'create' && modified ? 'text-gray-600 bg-gray-100 dark:text-gray-400 dark:bg-gray-700 px-1 rounded-md' : ''" > <span class="mr-1">{{ $getState() }}</span> <x-heroicon-o-pencil-alt stroke-width="2" class=" h-4 w-4 text-primary-600 dark:text-primary-500 " /> <span class="sr-only">{{ trans('filament-title-with-slug::package.permalink_action_edit') }}</span> </a> @if($getSlugLabelPostfix()) <span x-show="!editing" class="ml-0.5 text-gray-400" >{{ $getSlugLabelPostfix() }}</span> @endif <span x-show="!editing && context !== 'create' && modified"> [{{ trans('filament-title-with-slug::package.permalink_status_changed') }}]</span> </span> <div class="flex-1 mx-2" x-show="editing" style="display: none;" > <input type="text" x-ref="slugInput" x-model="stateInitial" x-bind:disabled="!editing" x-on:keydown.enter="submitModification()" x-on:keydown.escape="cancelModification()" {!! ($autocomplete = $getAutocomplete()) ? "autocomplete=\"{$autocomplete}\"" : null !!} id="{{ $getId() }}" {!! ($placeholder = $getPlaceholder()) ? "placeholder=\"{$placeholder}\"" : null !!} {!! $isRequired() ? 'required' : null !!} {{ $getExtraInputAttributeBag()->class(['block w-full transition duration-75 rounded-lg shadow-sm focus:border-primary-600 focus:ring-1 focus:ring-inset focus:ring-primary-600 disabled:opacity-70', 'dark:bg-gray-700 dark:text-white' => config('forms.dark_mode'), 'border-gray-300' => !$errors->has($getStatePath()), 'dark:border-gray-600' => !$errors->has($getStatePath()) && config('forms.dark_mode'), 'border-danger-600 ring-danger-600' => $errors->has($getStatePath())]) }} /> <input type="hidden" {{ $applyStateBindingModifiers('wire:model') }}="{{ $getStatePath() }}" /> </div> <div x-show="editing" class="flex space-x-2" style="display: none;" > <a href="#" role="button" x-on:click.prevent="submitModification()" class=" filament-button filament-button-size-md inline-flex items-center justify-center py-2.5 font-medium rounded-lg border transition-colors focus:outline-none focus:ring-offset-2 focus:ring-2 focus:ring-inset dark:focus:ring-offset-0 min-h-[2.25rem] px-4 text-sm text-gray-800 bg-white border-gray-300 hover:bg-gray-50 focus:ring-primary-600 focus:text-primary-600 focus:bg-primary-50 focus:border-primary-600 dark:bg-gray-800 dark:hover:bg-gray-700 dark:border-gray-600 dark:hover:border-gray-500 dark:text-gray-200 dark:focus:text-primary-400 dark:focus:border-primary-400 dark:focus:bg-gray-800 filament-page-button-action " > {{ trans('filament-title-with-slug::package.permalink_action_ok') }} </a> <x-filament::link x-show="context === 'edit' && modified" x-on:click="resetModification()" class="cursor-pointer ml-4" icon="heroicon-o-refresh" color="gray" size="sm" title="{{ trans('filament-title-with-slug::package.permalink_action_reset') }}" > <span class="sr-only">{{ trans('filament-title-with-slug::package.permalink_action_reset') }}</span> </x-filament::link> <x-filament::link x-on:click="cancelModification()" class="cursor-pointer" icon="heroicon-o-x" color="gray" size="sm" title="{{ trans('filament-title-with-slug::package.permalink_action_cancel') }}" > <span class="sr-only">{{ trans('filament-title-with-slug::package.permalink_action_cancel') }}</span> </x-filament::link> </div> <span x-show="context === 'edit'" class="flex items-center space-x-2" > @if($getSlugInputUrlVisitLinkVisible()) <template x-if="!editing"> <a href="{{ $getRecordUrl() }}" target="_blank" class="filament-link inline-flex items-center justify-center space-x-1 hover:underline focus:outline-none focus:underline text-sm text-primary-600 hover:text-primary-500 dark:text-primary-500 dark:hover:text-primary-400 cursor-pointer" > <span>{{ $getVisitLinkLabel() }}</span> <x-heroicon-o-external-link stroke-width="2" class="h-4 w-4" /> </a> </template> @endif </span> @endif </div> </div> </x-forms::field-wrapper>
php
MIT
352b70fd7b45ff2d7f1bfdfb45fcd90573902fc8
2026-01-05T05:10:10.355011Z
false