CustomValidationException example

return $manufacturer;
    }

    /** * @throws ApiException\CustomValidationException * * @return array */
    private function prepareManufacturerData(array $params)
    {
        if (!isset($params['name'])) {
            throw new ApiException\CustomValidationException('A name is required');
        }

        if (!empty($params['attribute'])) {
            foreach ($params['attribute'] as $key => $value) {
                if (is_numeric($key)) {
                    $params['attribute']['attribute' . $key] = $value;
                    unset($params[$key]);
                }
            }
        }

        
$customerId = !empty($params['customer']) ? (int) $params['customer'] : 0;
        unset($params['customer']);

        $customer = $this->getContainer()->get(ModelManager::class)->find(CustomerModel::class$customerId);
        if (!$customer) {
            throw new NotFoundException(sprintf('Customer by id %s not found', $customerId));
        }

        $this->setupContext($customer->getShop()->getId());

        if (!$params['country']) {
            throw new CustomValidationException('A country is required.');
        }

        $params = $this->prepareAddressData($params);

        $address = new AddressModel();
        $address->fromArray($params);

        $this->addressService->create($address$customer);

        if (!empty($params['__options_set_default_billing_address'])) {
            $this->addressService->setDefaultBillingAddress($address);
        }
return $fields;
    }

    private function validateFields(array $data): void
    {
        foreach ($this->type->getFields() as $field) {
            if (!$field->isRequired() || $field->getType() instanceof CheckboxField) {
                continue;
            }

            if (empty($data[$field->getName()])) {
                throw new CustomValidationException(sprintf('Field %s is required', $field->getName()));
            }
        }
    }

    private function quoteFields(array $data): array
    {
        foreach ($data as $key => $value) {
            unset($data[$key]);
            $data['`' . $key . '`'] = $value;
        }

        


        if (!empty($params['file'])) {
            $path = $this->load($params['file']$media->getFileName());
            $file = new UploadedFile($path$params['file']);

            try {
                $this->getContainer()->get(MediaReplaceServiceInterface::class)->replace($id$file);
                @unlink($path);
            } catch (Exception $exception) {
                @unlink($path);
                throw new CustomValidationException($exception->getMessage());
            }
        }

        if (isset($params['attribute']) && \is_array($params['attribute'])) {
            $attribute = $media->getAttribute();
            $attribute->fromArray($params['attribute']);

            $media->setAttribute($attribute);
            $this->getManager()->persist($attribute);
            $this->getManager()->flush();
        }

        

    public function postAction(): void
    {
        if (!$this->Request()->getParam('password')) {
            $passwordPlain = Random::generatePassword();
            $this->Request()->setPost('password', $passwordPlain);
        }

        if ($this->Request()->getParam('apiKey') && \strlen($this->Request()->getParam('apiKey')) < 40) {
            throw new CustomValidationException('apiKey is too short. The minimal length is 40.');
        }

        $user = $this->resource->create($this->Request()->getPost());

        $location = $this->apiBaseUrl . 'users/' . $user->getId();
        $data = [
            'id' => $user->getId(),
            'location' => $location,
        ];
        if (isset($passwordPlain)) {
            $data['password'] = $passwordPlain;
        }

        if (isset($data['esd'])) {
            $data = $this->prepareEsdAssociation($data$variant);
        }

        if (!empty($data['number']) && $data['number'] !== $variant->getNumber()) {
            // Number changed, hence make sure it does not already exist in another variant             $exists = $this->getContainer()
                ->get(Connection::class)
                ->fetchColumn('SELECT id FROM s_articles_details WHERE ordernumber = ?', [$data['number']]);
            if ($exists) {
                throw new CustomValidationException(sprintf('A variant with the given order number "%s" already exists.', $data['number']));
            }
        }

        return $data;
    }

    /** * Resolves the passed images array for the current variant. * An image can be assigned to a variant over a media id of an existing product image * or over the link property which can contain a image link. * This image will be added automatically to the product. * * @param array $data * * @throws CustomValidationException * * @return array */
case self::TYPE_FILTER_SET:
                return $this->getFilterSetIdByNumber($number);
            case self::TYPE_FILTER_GROUP:
                return $this->getFilterGroupIdByNumber($number);
            case self::TYPE_FILTER_OPTION:
                return $this->getFilterOptionIdByNumber($number);
            case self::TYPE_CONFIGURATOR_GROUP:
                return $this->getConfiguratorGroupIdByNumber($number);
            case self::TYPE_CONFIGURATOR_OPTION:
                return $this->getConfiguratorOptionIdByNumber($number);
            default:
                throw new CustomValidationException(sprintf('Unknown translation type %s', $type));
        }
    }

    /** * Returns the identifier of the product (s_articles.id). * The function expects a variant order number as alphanumeric identifier (s_articles_details.ordernumber) * * @param string $number - Alphanumeric order number of the variant * * @throws Exception * * @return int - Identifier of the product */
return $data;
    }

    /** * @throws CustomValidationException */
    private function validateStream(CustomerStreamEntity $stream): void
    {
        if (!$stream->isStatic()) {
            if (!$stream->getConditions()) {
                throw new CustomValidationException('A dynamic stream has to have at least one condition');
            }

            if ($stream->getFreezeUp()) {
                throw new CustomValidationException('A dynamic stream can not have a freezeUp time');
            }
        }
    }
}

    private function preparePropertyData(array $params$propertyGroup = null)
    {
        // If property group is created, we need to set some default values         if (!$propertyGroup) {
            if (!isset($params['name']) || empty($params['name'])) {
                throw new ApiException\CustomValidationException('A name is required');
            }

            if (!isset($params['position']) || empty($params['position'])) {
                $params['position'] = 0;
            }

            if (!isset($params['comparable']) || empty($params['comparable'])) {
                // Set comparable                 $params['comparable'] = 0;
            }

            
$params = $this->applyAddressData($params$customer);

        $customer->fromArray($params);

        $customerValidator = $this->getContainer()->get(CustomerValidatorInterface::class);
        $addressValidator = $this->getContainer()->get(AddressValidatorInterface::class);
        $addressService = $this->getContainer()->get(AddressServiceInterface::class);

        $customerValidator->validate($customer);
        $defaultBillingAddress = $customer->getDefaultBillingAddress();
        if ($defaultBillingAddress === null) {
            throw new CustomValidationException('Default billing address not set');
        }
        $defaultShippingAddress = $customer->getDefaultShippingAddress();
        if ($defaultShippingAddress === null) {
            throw new CustomValidationException('Default shipping address not set');
        }
        $addressValidator->validate($defaultBillingAddress);
        $addressValidator->validate($defaultShippingAddress);

        $addressService->update($defaultBillingAddress);
        $addressService->update($defaultShippingAddress);

        
'name',
            'description',
            'descriptionLong',
            'shippingTime',
            'keywords',
            'packUnit'
        );

        foreach ($translations as $translation) {
            $shop = $this->getManager()->find(Shop::class$translation['shopId']);
            if (!$shop instanceof Shop) {
                throw new CustomValidationException(sprintf('Shop by id "%s" not found', $translation['shopId']));
            }

            // Backward compatibility for attribute translations             foreach ($translation as $key => $value) {
                $attrKey = '__attribute_' . $key;
                if (\in_array($attrKey$whitelist) && !isset($translation[$attrKey])) {
                    $translation[$attrKey] = $value;
                }
            }

            $data = array_intersect_key($translationarray_flip($whitelist));
            

    protected function prepareAssociatedData(array $data, UserModel $user)
    {
        // Check if a role id or role name is passed and load the role model or set the role parameter to null.         if (!empty($data['roleId'])) {
            $data['role'] = $this->getManager()->find(Role::class$data['roleId']);

            if (empty($data['role'])) {
                throw new ApiException\CustomValidationException(sprintf('Role by id %s not found', $data['roleId']));
            }
        } elseif (isset($data['role']) && ($data['role'] >= 0)) {
            $role = $this->getManager()->getRepository(Role::class)->findOneBy(['name' => $data['role']]);

            if (!$role) {
                throw new ApiException\CustomValidationException(sprintf('Role by name %s not found', $data['role']));
            }
            $data['role'] = $role;
        } else {
            unset($data['role']);
        }

        


            if (!isset($params['tax'])) {
                $params['tax'] = $defaults['tax'];
            }

            if (!isset($params['mode'])) {
                $params['mode'] = $defaults['mode'];
            }

            if (empty($params['name'])) {
                throw new CustomValidationException(sprintf("Parameter '%s' is missing", 'name'));
            }

            if (empty($params['key'])) {
                throw new CustomValidationException(sprintf("Parameter '%s' is missing", 'key'));
            }
        }

        if (isset($params['name']) && empty($params['name'])) {
            throw new CustomValidationException(sprintf("Parameter '%s' is missing", 'name'));
        }

        
if ($preset->getId()) {
            $qb->andWhere('preset.id != :id')
                ->setParameter('id', $preset->getId());
        }

        $result = $qb->setParameter('name', $preset->getName())
            ->getQuery()
            ->getSingleScalarResult();

        if ($result > 0) {
            throw new CustomValidationException(sprintf('Preset with name %s already exists', $preset->getName()));
        }
    }

    /** * @param bool $fetchAll * * @return array[] */
    private function fetch($fetchAll = true)
    {
        $builder = $this->models->createQueryBuilder();

        
$request = $this->Request();
        $id = $request->getParam('id');

        if (empty($id)) {
            throw new ApiException\ParameterMissingException('id');
        }

        $useNumberAsId = (bool) $request->getParam('useNumberAsId', 0);
        $id = $useNumberAsId ? $this->resource->getIdFromNumber($id) : (int) $id;

        if (!$useNumberAsId && $id <= 0) {
            throw new ApiException\CustomValidationException('Invalid product id');
        }

        /** @var Article|null $product */
        $product = $this->resource->getRepository()->find($id);

        if (!$product) {
            throw new ApiException\NotFoundException(sprintf('Product by id %d not found', $id));
        }

        $this->resource->generateImages($product(bool) $request->getParam('force', 0));

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