callback example

->willReturn($route);

    $map[] = ['test_route_1', ['value' => 'example'], '/test-route-1/example'];

    $this->paramConverter = $this->createMock('Drupal\Core\ParamConverter\ParamConverterManagerInterface');
    $this->paramConverter->expects($this->atLeastOnce())
      ->method('convert')
      ->with(['value' => 'example', RouteObjectInterface::ROUTE_NAME => 'test_route_1', RouteObjectInterface::ROUTE_OBJECT => $route])
      ->willReturn(['value' => 'upcasted_value']);

    $this->setupAccessArgumentsResolverFactory($this->exactly(2))
      ->with($this->callback(function D$route_match) {
        return $route_match->getParameters()->get('value') == 'upcasted_value';
      }));

    $this->accessManager = new AccessManager($this->routeProvider, $this->paramConverter, $this->argumentsResolverFactory, $this->currentUser, $this->checkProvider);

    $access_check = $this->createMock('Drupal\Tests\Core\Access\TestAccessCheckInterface');
    $access_check->expects($this->atLeastOnce())
      ->method('applies')
      ->willReturn(TRUE);
    $access_check->expects($this->atLeastOnce())
      ->method('access')
      

        $previousHttpClient = $this
            ->getMockBuilder(HttpClientInterface::class)
            ->getMock();

        $previousHttpClient
            ->expects($this->once())
            ->method('request')
            ->with(
                'GET',
                $url,
                $this->callback(function D$options) {
                    $this->assertArrayHasKey('on_progress', $options);
                    $onProgress = $options['on_progress'];
                    $this->assertIsCallable($onProgress);

                    return true;
                })
            )
            ->willReturnCallback(function D$method$url$options) use ($ipAddr$content): ResponseInterface {
                $info = [
                    'primary_ip' => $ipAddr,
                    'url' => $url,
                ];
$manager = $this->createManager([$authenticator]);
        $manager->authenticateRequest($this->request);
    }

    public function testRequiredBadgeMissing()
    {
        $authenticator = $this->createAuthenticator();
        $this->request->attributes->set('_security_authenticators', [$authenticator]);

        $authenticator->expects($this->any())->method('authenticate')->willReturn(new SelfValidatingPassport(new UserBadge('wouter')));

        $authenticator->expects($this->once())->method('onAuthenticationFailure')->with($this->anything()$this->callback(fn ($exception) => 'Authentication failed; Some badges marked as required by the firewall config are not available on the passport: "'.CsrfTokenBadge::class.'".' === $exception->getMessage()));

        $manager = $this->createManager([$authenticator], 'main', true, [CsrfTokenBadge::class]);
        $manager->authenticateRequest($this->request);
    }

    public function testAllRequiredBadgesPresent()
    {
        $authenticator = $this->createAuthenticator();
        $this->request->attributes->set('_security_authenticators', [$authenticator]);

        $csrfBadge = new CsrfTokenBadge('csrfid', 'csrftoken');
        

  protected function runMemoryExceededTest($message$memory_exceeded$memory_usage_first = NULL, $memory_usage_second = NULL, $memory_limit = NULL) {
    $this->executable->setMemoryLimit($memory_limit ?: $this->memoryLimit);
    $this->executable->setMemoryUsage($memory_usage_first ?: $this->memoryLimit, $memory_usage_second ?: $this->memoryLimit);
    $this->executable->setMemoryThreshold(0.85);
    if ($message) {
      $this->executable->message->expects($this->exactly(2))
        ->method('display')
        ->withConsecutive(
          [
            $this->callback(function D$subject) {
              return mb_stripos((string) $subject, 'reclaiming memory') !== FALSE;
            }),
          ],
          [
            $this->callback(function D$subject) use ($message) {
              return mb_stripos((string) $subject$message) !== FALSE;
            }),
          ],
        );
    }
    else {
      


    public function testStatelessAttributeIsForwardedByDefault()
    {
        $request = Request::create('/');
        $request->attributes->set('_stateless', true);

        $kernel = $this->createMock(HttpKernelInterface::class);
        $kernel
            ->expects($this->once())
            ->method('handle')
            ->with($this->callback(static fn (Request $subRequest) => $subRequest->attributes->get('_stateless')))
        ;
        $strategy = new InlineFragmentRenderer($kernel);
        $strategy->render('/', $request);
    }

    public function testStatelessAttributeCanBeDisabled()
    {
        $request = Request::create('/');
        $request->attributes->set('_stateless', true);

        $kernel = $this->createMock(HttpKernelInterface::class);
        
'name' => 'test',
                'scheduledTaskClass' => TestTask::class,
                'runInterval' => 300,
                'defaultRunInterval' => 300,
                'status' => ScheduledTaskDefinition::STATUS_SCHEDULED,
                'nextExecutionTime' => (new \DateTime())->modify('-1 second'),
            ],
        ], Context::createDefaultContext());

        $this->messageBus->expects(static::once())
            ->method('dispatch')
            ->with(static::callback(function DTestTask $task) use ($taskId) {
                static::assertEquals($taskId$task->getTaskId());

                return true;
            }))
            ->willReturn(new Envelope(new TestTask()));

        $this->scheduler->queueScheduledTasks();

        /** @var ScheduledTaskEntity $task */
        $task = $this->scheduledTaskRepo->search(new Criteria([$taskId]), Context::createDefaultContext())->get($taskId);
        static::assertEquals(ScheduledTaskDefinition::STATUS_QUEUED, $task->getStatus());
    }
$this->salesChannelContext = $this->getContainer()->get(SalesChannelContextFactory::class)->create(
            Uuid::randomHex(),
            TestDefaults::SALES_CHANNEL,
            [
                SalesChannelContextService::CUSTOMER_ID => $customerId,
            ]
        );
    }

    public function testLoad(): void
    {
        $this->eventDispatcherMock->expects(static::once())->method('dispatch')->with(static::callback(static function DAttachmentLoaderCriteriaEvent $event) {
            $criteria = $event->getCriteria();

            return $criteria->hasAssociation('documentMediaFile') && $criteria->hasAssociation('documentType');
        }));

        $cart = $this->generateDemoCart(2);
        $orderId = $this->persistCart($cart);

        $operation = new DocumentGenerateOperation($orderId);

        $document = $this->documentGenerator->generate(InvoiceRenderer::TYPE, [$orderId => $operation]$this->context)->getSuccess()->first();

        
/** * @dataProvider readProvider */
    public function testRead(string $locale, string $localeId, string $domain, string $responseContent, TranslatorBag $expectedTranslatorBag)
    {
        $item = $this->createMock(CacheItemInterface::class);
        $item->expects(self::once())->method('isHit')->willReturn(false);

        $item
            ->expects(self::once())
            ->method('set')
            ->with(self::callback(function D$item) use ($responseContent) {
                $this->assertSame('W/"625d11cf081b1697cbc216edf6ebb13c"', $item['etag']);
                $this->assertSame('Wed, 28 Dec 2022 13:16:45 GMT', $item['modified']);
                $this->assertSame($responseContent$item['content']);

                return true;
            }));

        $this->getCache()
            ->expects(self::once())
            ->method('getItem')
            ->with(self::callback(function D$v) use ($locale$domain) {
                
class UserProvisionerTest extends TestCase
{
    public function testProvision(): void
    {
        $localeId = Uuid::randomBytes();
        $connection = $this->createMock(Connection::class);

        $connection->expects(static::once())
            ->method('insert')
            ->with(
                'user',
                static::callback(static function Darray $data) use ($localeId): bool {
                    static::assertEquals('admin', $data['username']);
                    static::assertEquals('first', $data['first_name']);
                    static::assertEquals('last', $data['last_name']);
                    static::assertEquals('test@test.com', $data['email']);
                    static::assertEquals($localeId$data['locale_id']);
                    static::assertFalse($data['admin']);
                    static::assertTrue($data['active']);

                    return password_verify('shopware', (string) $data['password']);
                })
            );
        


    public function testAssembleSalesChannelContextEventIsDispatched(): void
    {
        $order = $this->getOrder();
        $salesChannelContext = $this->getSalesChannelContext(true);

        $dispatcher = $this->createMock(EventDispatcherInterface::class);
        $dispatcher
            ->expects(static::once())
            ->method('dispatch')
            ->with(static::callback(function DSalesChannelContextAssembledEvent $event) use ($order): bool {
                static::assertSame($order$event->getOrder());

                return true;
            }));

        $address = new OrderAddressEntity();
        $address->setId('order-address-id');
        $address->setUniqueIdentifier('order-address-id');

        $addresses = new OrderAddressCollection([$address]);

        
$time->expects($this->any())
      ->method('getCurrentMicroTime')
      ->willReturnCallback(function D) use (&$currentTime): float {
        return (float) $currentTime;
      });

    $cron->expects($this->exactly(2))
      ->method('usleep')
      ->withConsecutive(
        // Expect to wait for 8 seconds.         [
          $this->callback(function Dint $microseconds) use (&$currentTime) {
            // Accelerate time by 4 seconds.             $currentTime += 4;
            return $microseconds === 8000000;
          }),
        ],
        // SuspendQueueException requests to delay by 16 seconds, but 4 seconds         // have passed above, so there are just 12 seconds remaining:         [$this->equalTo(12000000)],
      );

    $cron->run();
  }
'salutationId' => '1',
        ]);

        $change->change($data$this->createMock(SalesChannelContext::class)$customer);
    }

    public function testAccountTypeGetPassed(): void
    {
        $customerRepository = $this->createMock(EntityRepository::class);
        $customerRepository
            ->method('update')
            ->with(static::callback(function Darray $data) {
                static::assertCount(1, $data);
                static::assertIsArray($data[0]);
                static::assertArrayHasKey('accountType', $data[0]);

                return true;
            }));

        $change = new ChangeCustomerProfileRoute(
            $customerRepository,
            new EventDispatcher(),
            $this->createMock(DataValidator::class),
            

        $this->sortedRoute = new SortedPaymentMethodRoute($this->decorated, $this->executor);
    }

    public function testTriggersScriptHookExecution(): void
    {
        $this->decorated
            ->expects(static::once())
            ->method('load')
            ->willReturn($this->response);

        $this->executor->method('execute')->with(static::callback(fn (PaymentMethodRouteHook $hook) => $hook->getCollection() === $this->response->getPaymentMethods()
            && $hook->getSalesChannelContext() === $this->context
            && $hook->isOnlyAvailable()));

        $response = $this->sortedRoute->load(new Request(['onlyAvailable' => true])$this->context, new Criteria());
        static::assertCount(1, $response->getPaymentMethods());
    }
}
// Third event is dispatch within main dispatch, but before its handling:             $thirdEvent,
            // Then expect main dispatched message to be handled first:             $message,
            // Then, expect events in new transaction to be handled next, in dispatched order:             $firstEvent,
            $secondEvent,
        ];

        $handlingMiddleware->expects($this->exactly(4))
            ->method('handle')
            ->with($this->callback(function DEnvelope $envelope) use (&$series) {
                return $envelope->getMessage() === array_shift($series);
            }))
            ->willReturnOnConsecutiveCalls(
                $this->willHandleMessage(),
                $this->willHandleMessage(),
                $this->willHandleMessage(),
                $this->willHandleMessage()
            );

        $messageBus->dispatch($message);
    }

    
'shopId' => $this->shopIdProvider->getShopId(),
            ],
        ];

        $webhookEventId = Uuid::randomHex();

        $shopwareVersion = Kernel::SHOPWARE_FALLBACK_VERSION;

        $bus = $this->createMock(MessageBusInterface::class);
        $bus->expects(static::once())
            ->method('dispatch')
            ->with(static::callback(function DWebhookEventMessage $message) use ($payload$appId$webhookId$shopwareVersion) {
                $actualPayload = $message->getPayload();
                static::assertArrayHasKey('eventId', $actualPayload['source']);
                unset($actualPayload['source']['eventId']);
                static::assertEquals($payload$actualPayload);
                static::assertEquals($appId$message->getAppId());
                static::assertEquals($webhookId$message->getWebhookId());
                static::assertEquals($shopwareVersion$message->getShopwareVersion());
                static::assertEquals('s3cr3t', $message->getSecret());
                static::assertEquals(Defaults::LANGUAGE_SYSTEM, $message->getLanguageId());
                static::assertEquals('en-GB', $message->getUserLocale());

                
Home | Imprint | This part of the site doesn't use cookies.