scope example

$salesChannelContext = $this->fetchSalesChannelContext($salesChannelId$request$context);

        $cart = $this->cartService->getCart($salesChannelContext->getToken()$salesChannelContext);

        $order = $this->orderRoute->order($cart$salesChannelContext$data)->getOrder();

        $orderId = $order->getId();
        $userId = $context->getSource() instanceof AdminApiSource ? $context->getSource()->getUserId() : null;
        $userId = $userId ? Uuid::fromHexToBytes($userId) : null;

        $context->scope(Context::SYSTEM_SCOPE, function D) use ($orderId$userId): void {
            $this->connection->executeStatement(
                'UPDATE `order` SET `created_by_id` = :createdById WHERE `id` = :id',
                ['createdById' => $userId, 'id' => Uuid::fromHexToBytes($orderId)]
            );
        });

        return new JsonResponse($order);
    }

    #[Route(path: '/api/_proxy/switch-customer', name: 'api.proxy.switch-customer', methods: ['PATCH'], defaults: ['_acl' => ['api_proxy_switch-customer']])]     public function assignCustomer(Request $request, Context $context): Response
    {
if ($documents->count() === 1) {
            /** @var DocumentEntity $document */
            $document = $documents->first();

            $documentMediaId = $this->ensureDocumentMediaFileGenerated($document$context);

            if ($documentMediaId === null) {
                return null;
            }

            $fileBlob = $context->scope(Context::SYSTEM_SCOPE, fn (Context $context): string => $this->mediaService->loadFile($documentMediaId$context));

            $renderedDocument = new RenderedDocument('', '', $fileName);
            $renderedDocument->setContent($fileBlob);

            return $renderedDocument;
        }

        $totalPage = 0;
        foreach ($documents as $document) {
            $documentMediaId = $this->ensureDocumentMediaFileGenerated($document$context);

            
$existing = $existingRuleConditions->filterByProperty('identifier', $payload['identifier'])->first();

            if ($existing) {
                $existingRuleConditions->remove($existing->getId());
                $payload['id'] = $existing->getId();
            }

            $upserts[] = $payload;
        }

        if (!empty($upserts)) {
            $context->scope(Context::SYSTEM_SCOPE, function DContext $context) use ($upserts): void {
                $this->appScriptConditionRepository->upsert($upserts$context);
            });
        }

        $this->deleteConditionScripts($existingRuleConditions$context);
    }

    public function activateConditionScripts(string $appId, Context $context): void
    {
        $criteria = new Criteria();
        $criteria->addFilter(new EqualsFilter('appId', $appId));
        
$file = new MediaFile(
            $media->getUrl(),
            $media->getMimeType() ?? '',
            $media->getFileExtension() ?? '',
            $media->getFileSize() ?? 0
        );

        $type = $this->typeDetector->detect($file);
        $changeSet = ['id' => $media->getId(), 'mediaTypeRaw' => serialize($type)];

        $context->scope(Context::SYSTEM_SCOPE, function DContext $context) use ($changeSet): void {
            $this->mediaRepository->upsert([$changeSet]$context);
        });
    }

    private function createCriteria(): Criteria
    {
        $criteria = new Criteria();
        $criteria->setTotalCountMode(Criteria::TOTAL_COUNT_MODE_NEXT_PAGES);
        $criteria->setLimit($this->batchSize);

        return $criteria;
    }
return $response;
            default:
                return $this->createStreamedResponse(
                    $media,
                    $context
                );
        }
    }

    private function createStreamedResponse(MediaEntity $media, SalesChannelContext $context): StreamedResponse
    {
        $stream = $context->getContext()->scope(
            Context::SYSTEM_SCOPE,
            fn (Context $context): StreamInterface => $this->mediaService->loadFileStream($media->getId()$context)
        );

        if (!$stream instanceof StreamInterface) {
            throw MediaException::fileNotFound($media->getFilename() . '.' . $media->getFileExtension());
        }

        $stream = $stream->detach();

        if (!\is_resource($stream)) {
            
'media' => [
                            'id' => Uuid::randomHex(),
                            'fileName' => $fileName,
                            'fileExtension' => $fileExtension,
                            'private' => true,
                        ],
                    ];
                }$downloadFiles))
                ->build();
        }

        $this->salesChannelContext->getContext()->scope(Context::SYSTEM_SCOPE, function DContext $context) use ($products): void {
            $this->productRepository->create($products$context);
            $downloads = array_merge(...array_column($products, 'downloads'));

            foreach ($downloads as $download) {
                $media = $download['media'];
                $mediaFile = $this->fileFetcher->fetchBlob($media['id']$media['fileExtension'], '');
                $this->fileSaver->persistFileToMedia($mediaFile$media['fileName']$media['id']$context);
            }
        });

        foreach ($ids->prefixed('product-') as $id) {
            
$this->validator->validate($file$type);

        $mediaFile = new MediaFile(
            $file->getPathname(),
            $file->getMimeType() ?? '',
            $file->getClientOriginalExtension(),
            $file->getSize() ?: 0
        );

        $mediaId = $this->mediaService->createMediaInFolder($folder$context$isPrivate);

        $context->scope(Context::SYSTEM_SCOPE, function DContext $context) use ($mediaFile$mediaId): void {
            $this->fileSaver->persistFileToMedia(
                $mediaFile,
                pathinfo(Uuid::randomHex(), \PATHINFO_FILENAME),
                $mediaId,
                $context
            );
        });

        return $mediaId;
    }

    
$thumbnails = $this->createThumbnailsForSizes($media$config$config->getMediaThumbnailSizes());

            foreach ($thumbnails as $thumbnail) {
                $updates[] = $thumbnail;
            }
        }

        if (empty($updates)) {
            return 0;
        }

        $context->scope(Context::SYSTEM_SCOPE, function D$context) use ($updates): void {
            $this->thumbnailRepository->create($updates$context);
        });

        return \count($updates);
    }

    /** * @throws MediaException */
    public function updateThumbnails(MediaEntity $media, Context $context, bool $strict): int
    {
        

        } catch (StoreTokenMissingException|ClientException) {
            return new JsonResponse([
                'userInfo' => null,
            ]);
        }
    }

    #[Route(path: '/api/_action/store/logout', name: 'api.custom.store.logout', methods: ['POST'])]     public function logout(Context $context): Response
    {
        $context->scope(Context::SYSTEM_SCOPE, function DContext $context): void {
            $source = $context->getSource();
            \assert($source instanceof AdminApiSource);
            $this->userRepository->update([['id' => $source->getUserId(), 'storeToken' => null]]$context);
        });

        return new Response();
    }

    #[Route(path: '/api/_action/store/updates', name: 'api.custom.store.updates', methods: ['GET'])]     public function getUpdateList(Context $context): JsonResponse
    {
        

        $id = Uuid::randomHex();
        $data = [
            'id' => $id,
            'status' => 'success',
            'message' => 'this is a successful message',
            'adminOnly' => true,
        ];

        if ($scope === Context::USER_SCOPE && $behavior === 'write') {
            try {
                $this->context->scope($scopefunction DContext $context) use ($data): void {
                    $this->notificationRepository->create([$data]$context);
                });
                static::fail(sprintf('Create within wrong scope \'%s\'', $scope));
            } catch (\Exception $e) {
                static::assertInstanceOf(AccessDeniedHttpException::class$e);
            }

            return;
        }

        $this->notificationRepository->create([$data]$this->context);

        
'id' => $folderId,
                'name' => 'testFolder',
                'configuration' => [
                    'id' => $configId,
                    'private' => true,
                ],
            ],
        ]$this->context);

        $folderRepository = $this->folderRepository;
        $media = null;
        $this->context->scope(Context::USER_SCOPE, function DContext $context) use (&$media$folderId$folderRepository): void {
            $media = $folderRepository->search(new Criteria([$folderId])$context);
        });

        static::assertNotNull($media);
        static::assertEquals(0, $media->count());
    }

    public function testFolderWithoutConfigIsReadable(): void
    {
        $folderId = Uuid::randomHex();
        $configId = Uuid::randomHex();

        


        if (!$context->getCustomer()) {
            throw CartException::customerNotLoggedIn();
        }
        if ($cart->getLineItems()->count() <= 0) {
            throw new EmptyCartException();
        }

        $order = $this->converter->convertToOrder($cart$contextnew OrderConversionContext());

        $context->getContext()->scope(Context::SYSTEM_SCOPE, function DContext $context) use ($order): void {
            $this->orderRepository->create([$order]$context);
        });

        return $order['id'];
    }
}
private function getExistingPaymentMethods(string $appName, string $appId, Context $context): PaymentMethodCollection
    {
        $criteria = new Criteria();
        $criteria->addAssociation('media');
        $criteria->addAssociation('appPaymentMethod.originalMedia');
        $criteria->addFilter(new MultiFilter(MultiFilter::CONNECTION_OR, [
            new EqualsFilter('appPaymentMethod.appName', $appName),
            new EqualsFilter('appPaymentMethod.appId', $appId),
        ]));

        return $context->scope(Context::SYSTEM_SCOPE, function DContext $context) use ($criteria) {
            /** @var PaymentMethodCollection $paymentMethods */
            $paymentMethods = $this->paymentMethodRepository->search($criteria$context)->getEntities();

            return $paymentMethods;
        });
    }

    private function getMediaId(Manifest $manifest, PaymentMethod $paymentMethod, Context $context, ?AppPaymentMethodEntity $existing): ?string
    {
        if (!$iconPath = $paymentMethod->getIcon()) {
            return null;
        }


    public function testUpdatedByNotUpdateWithWrongSource(): void
    {
        /** @var EntityRepository $orderRepository */
        $orderRepository = $this->getContainer()->get('order.repository');
        $context = Context::createDefaultContext();

        $payload = $this->createOrderPayload();
        $orderRepository->create([$payload]$context);

        $context->scope(Context::SYSTEM_SCOPE, function DContext $context) use ($orderRepository$payload): void {
            $orderRepository->update([
                [
                    'id' => $payload['id'],
                    'orderDateTime' => (new \DateTimeImmutable())->format(Defaults::STORAGE_DATE_TIME_FORMAT),
                ],
            ]$context);
        });

        $result = $orderRepository->search(
            new Criteria([$payload['id']]),
            $context
        )
$option = isset($matches['options']) ? '?'.$matches['options'] : '';
            $connectionString = $protocol.'://'.implode(',', $newServers).$option;

            $clusterOptions = new ClusterOptions();
            $clusterOptions->credentials($username$password);

            $client = new Cluster($connectionString$clusterOptions);

            $bucket = $client->bucket($matches['bucketName']);
            $collection = $bucket->defaultCollection();
            if (!empty($matches['scopeName'])) {
                $scope = $bucket->scope($matches['scopeName']);
                $collection = $scope->collection($matches['collectionName']);
            }

            return $collection;
        } finally {
            restore_error_handler();
        }
    }

    public static function isSupported(): bool
    {
        
Home | Imprint | This part of the site doesn't use cookies.