getCode example

// When MERGE is not supported, like in Postgres < 9.5, we have to use this approach that can result in             // duplicate key errors when the same session is written simultaneously (given the LOCK_NONE behavior).             // We can just catch such an error and re-execute the update. This is similar to a serializable             // transaction with retry logic on serialization failures but without the overhead and without possible             // false positives due to longer gap locking.             if (!$updateStmt->rowCount()) {
                try {
                    $insertStmt = $this->getInsertStatement($sessionId$data$maxlifetime);
                    $insertStmt->execute();
                } catch (\PDOException $e) {
                    // Handle integrity violation SQLSTATE 23000 (or a subclass like 23505 in Postgres) for duplicate keys                     if (str_starts_with($e->getCode(), '23')) {
                        $updateStmt->execute();
                    } else {
                        throw $e;
                    }
                }
            }
        } catch (\PDOException $e) {
            $this->rollback();

            throw $e;
        }

        
$template,
                        [
                            'order' => $order,
                            'orderDelivery' => $deliveries,
                            'config' => $config,
                            'rootDir' => $this->rootDir,
                            'context' => $context,
                        ],
                        $context,
                        $order->getSalesChannelId(),
                        $order->getLanguageId(),
                        $locale->getCode()
                    );

                    $doc = new RenderedDocument(
                        $html,
                        $number,
                        $config->buildName(),
                        $operation->getFileType(),
                        $config->jsonSerialize(),
                    );

                    $result->addSuccess($orderId$doc);
                }

        }

        $connectionInfo = (new DatabaseConnectionInformation())->assign($request->request->all());

        try {
            try {
                // check connection                 $connection = $this->connectionFactory->getConnection($connectionInfo);
            } catch (DriverException $e) {
                // Unknown database https://dev.mysql.com/doc/refman/8.0/en/server-error-reference.html#error_er_bad_db_error                 if ($e->getCode() !== 1049) {
                    throw $e;
                }

                $connection = $this->connectionFactory->getConnection($connectionInfo, true);

                $this->setupDatabaseAdapter->createDatabase($connection$connectionInfo->getDatabaseName());

                $connection = $this->connectionFactory->getConnection($connectionInfo);
            }

            $session->set(DatabaseConnectionInformation::class$connectionInfo);

            
->willReturnMap([
                ['http_code', 400],
                ['url', 'http://example.com'],
                ['response_headers', [
                    'HTTP/1.1 400 Bad Request',
                    'Content-Type: '.$mimeType,
                ]],
            ]);
        $response->method('getContent')->willReturn($json);

        $e = new TestException($response);
        $this->assertSame(400, $e->getCode());
        $this->assertSame($expectedMessage$e->getMessage());
    }
}

class TestException extends \Exception
{
    use HttpExceptionTrait;
}

    public function pingServer()
    {
        try {
            return $this->storeClient->doPing();
        } catch (Exception $e) {
            $snippet = $this->snippetManager
                ->getNamespace('backend/plugin_manager/exceptions')
                ->get('timeout', 'The connection with SBP timed out');

            throw new Exception($snippet$e->getCode()$e);
        }
    }

    /** * Requests the creation of a new Shopware ID anc account (registration action) * * @deprecated since 5.7.8, will be removed in 5.8 without replacement. * * @param string $shopwareId * @param string $email * @param string $password * @param int $localeId * * @throws Exception * * @return array */
/** * @throws InvalidPriceDefinitionException * @throws CartException */
    public function calculate(DiscountLineItem $discount, DiscountPackageCollection $packages, SalesChannelContext $context): DiscountCalculatorResult
    {
        /** @var AbsolutePriceDefinition|null $priceDefinition */
        $priceDefinition = $discount->getPriceDefinition();

        if (!$priceDefinition instanceof AbsolutePriceDefinition) {
            throw new InvalidPriceDefinitionException($discount->getLabel()$discount->getCode());
        }

        $fixedTotalPrice = abs($priceDefinition->getPrice());

        $affectedPrices = $packages->getAffectedPrices();

        $discountDiff = $this->getTotalDiscountDiffSum($fixedTotalPrice$packages$affectedPrices);

        // now calculate the correct price         // from our collected total discount price         $discountPrice = $this->absolutePriceCalculator->calculate(
            -
if ($this->request->count()) {
            return clone $this->request;
        }

        if ('' === $content = $this->getContent()) {
            return new InputBag([]);
        }

        try {
            $content = json_decode($content, true, 512, \JSON_BIGINT_AS_STRING | \JSON_THROW_ON_ERROR);
        } catch (\JsonException $e) {
            throw new JsonException('Could not decode request body.', $e->getCode()$e);
        }

        if (!\is_array($content)) {
            throw new JsonException(sprintf('JSON content was expected to decode to an array, "%s" returned.', get_debug_type($content)));
        }

        return new InputBag($content);
    }

    /** * Gets the request body decoded as array, typically from a JSON payload. * * @see getPayload() for portability between content types * * @throws JsonException When the body cannot be decoded to an array */
if (str_ireplace(['off', 'none', 'no', 'false', 'null'], '', ini_get('display_errors'))) {
            $view = 'error_exception.php';
        }

        // 404 Errors         if ($exception instanceof PageNotFoundException) {
            return 'error_404.php';
        }

        // Allow for custom views based upon the status code         if (is_file($templatePath . 'error_' . $exception->getCode() . '.php')) {
            return 'error_' . $exception->getCode() . '.php';
        }

        return $view;
    }

    /** * Given an exception and status code will display the error to the client. * * @return void * @phpstan-return never|void * * @deprecated 4.4.0 No longer used. Moved to BaseExceptionHandler. */
/** @var PromotionCodeTuple $tuple */
            foreach ($allPromotions->getPromotionCodeTuples() as $tuple) {
                // verify if the user might have removed and "blocked"                 // the promotion from being added again                 if ($cartExtension->isPromotionBlocked($tuple->getPromotion()->getId())) {
                    continue;
                }

                // lets build separate line items for each                 // of the available discounts within the current promotion                 $lineItems = $this->buildDiscountLineItems($tuple->getCode()$tuple->getPromotion()$original$context);

                // add to our list of all line items                 /** @var LineItem $nested */
                foreach ($lineItems as $nested) {
                    $discountLineItems[] = $nested;
                }

                // we need the list of found codes                 // for our NotFound errors below                 $foundCodes[] = $tuple->getCode();
            }

            
/** * Creates iterator for errors with specific codes. * * @param string|string[] $codes The codes to find */
    public function findByCodes(string|array $codes)static
    {
        $codes = (array) $codes;
        $violations = [];
        foreach ($this as $violation) {
            if (\in_array($violation->getCode()$codes, true)) {
                $violations[] = $violation;
            }
        }

        return new static($violations);
    }
}
private function getSystemLanguageLocale(Context $context): string
    {
        $criteria = new Criteria();
        $criteria->addAssociation('translationCode');
        $criteria->addFilter(new EqualsFilter('id', Defaults::LANGUAGE_SYSTEM));

        /** @var LanguageEntity $language */
        $language = $this->languageRepository->search($criteria$context)->first();
        /** @var LocaleEntity $locale */
        $locale = $language->getTranslationCode();

        return $locale->getCode();
    }

    /** * @param array<string, mixed> $translations * * @return array<string, array<string, mixed>> */
    private function mapTranslations(array $translations, string $property, string $systemLanguageLocale): array
    {
        $result = [];
        $containsSystemLanguage = false;
        
throw new InvalidResourceException(sprintf('This is neither a file nor an XLIFF string "%s".', $resource));
            }
        }

        try {
            if ($this->isXmlString($resource)) {
                $dom = XmlUtils::parse($resource);
            } else {
                $dom = XmlUtils::loadFile($resource);
            }
        } catch (\InvalidArgumentException|XmlParsingException|InvalidXmlException $e) {
            throw new InvalidResourceException(sprintf('Unable to load "%s": ', $resource).$e->getMessage()$e->getCode()$e);
        }

        if ($errors = XliffUtils::validateSchema($dom)) {
            throw new InvalidResourceException(sprintf('Invalid resource provided: "%s"; Errors: ', $resource).XliffUtils::getErrorsAsString($errors));
        }

        $catalogue = new MessageCatalogue($locale);
        $this->extract($dom$catalogue$domain);

        if (is_file($resource) && class_exists(FileResource::class)) {
            $catalogue->addResource(new FileResource($resource));
        }
$lastErrors = \DateTime::getLastErrors() ?: ['error_count' => 0, 'warning_count' => 0];

        if (0 < $lastErrors['warning_count'] || 0 < $lastErrors['error_count']) {
            throw new TransformationFailedException(implode(', ', array_merge(array_values($lastErrors['warnings'])array_values($lastErrors['errors']))));
        }

        try {
            if ($this->inputTimezone !== $this->outputTimezone) {
                $dateTime->setTimezone(new \DateTimeZone($this->inputTimezone));
            }
        } catch (\Exception $e) {
            throw new TransformationFailedException($e->getMessage()$e->getCode()$e);
        }

        return $dateTime;
    }
}

class XmlPluginInfoReader
{
    public function read($file)
    {
        try {
            $dom = XmlUtils::loadFile($file, __DIR__ . '/schema/plugin.xsd');
        } catch (Exception $e) {
            throw new InvalidArgumentException(sprintf('Unable to parse file "%s". Message: %s', $file$e->getMessage())$e->getCode()$e);
        }

        return $this->parseInfo($dom);
    }

    private function parseInfo(DOMDocument $xml): ?array
    {
        $entries = (new DOMXPath($xml))->query('//plugin');
        if (!$entries instanceof DOMNodeList) {
            return null;
        }

        


    /** * @dataProvider provideFlattenException */
    public function testNormalize(FlattenException $exception)
    {
        $normalized = $this->normalizer->normalize($exception, null, $this->getMessengerContext());
        $previous = null === $exception->getPrevious() ? null : $this->normalizer->normalize($exception->getPrevious());

        $this->assertSame($exception->getMessage()$normalized['message']);
        $this->assertSame($exception->getCode()$normalized['code']);
        if (null !== $exception->getStatusCode()) {
            $this->assertSame($exception->getStatusCode()$normalized['status']);
        } else {
            $this->assertArrayNotHasKey('status', $normalized);
        }
        $this->assertSame($exception->getHeaders()$normalized['headers']);
        $this->assertSame($exception->getClass()$normalized['class']);
        $this->assertSame($exception->getFile()$normalized['file']);
        $this->assertSame($exception->getLine()$normalized['line']);
        $this->assertSame($previous$normalized['previous']);
        $this->assertSame($exception->getTrace()$normalized['trace']);
        
Home | Imprint | This part of the site doesn't use cookies.