getPropertyPath example

$this->expectException(WriteConstraintViolationException::class);

        try {
            $serializer->encode(
                $this->getIntField(),
                EntityExistence::createEmpty(),
                $data,
                $this->getWriteParameterBagMock()
            )->current();
        } catch (WriteConstraintViolationException $e) {
            static::assertSame('/count', $e->getViolations()->get(0)->getPropertyPath());
            /* Unexpected language has to be fixed NEXT-9419 */
            // static::assertSame('This value should not be blank.', $e->getViolations()->get(0)->getMessage());
            throw $e;
        }
    }

    public function testIntFieldSerializerWrongValueType(): void
    {
        $serializer = $this->getContainer()->get(IntFieldSerializer::class);

        
$violations = $this->recursiveValidator->validate($typed_data);
    $this->assertCount(6, $violations);

    $this->assertEquals('violation: 3', $violations->get(0)->getMessage());
    $this->assertEquals('violation: value1', $violations->get(1)->getMessage());
    $this->assertEquals('violation: value2', $violations->get(2)->getMessage());
    $this->assertEquals('violation: 2', $violations->get(3)->getMessage());
    $this->assertEquals('violation: subvalue1', $violations->get(4)->getMessage());
    $this->assertEquals('violation: subvalue2', $violations->get(5)->getMessage());

    $this->assertEquals('', $violations->get(0)->getPropertyPath());
    $this->assertEquals('key1', $violations->get(1)->getPropertyPath());
    $this->assertEquals('key2', $violations->get(2)->getPropertyPath());
    $this->assertEquals('key_with_properties', $violations->get(3)->getPropertyPath());
    $this->assertEquals('key_with_properties.subkey1', $violations->get(4)->getPropertyPath());
    $this->assertEquals('key_with_properties.subkey2', $violations->get(5)->getPropertyPath());
  }

  /** * Setups a typed data object used for test purposes. * * @param array $tree * An array of value, constraints and properties. * @param string $name * The name to use for the object. * * @return \Drupal\Core\TypedData\TypedDataInterface|\PHPUnit\Framework\MockObject\MockObject */
if ($allowed_formats && !$this->isDefaultValueWidget($form_state)) {
      $element['#allowed_formats'] = $allowed_formats;
    }

    return $element;
  }

  /** * {@inheritdoc} */
  public function errorElement(array $element, ConstraintViolationInterface $violation, array $form, FormStateInterface $form_state) {
    if (isset($element['format']['#access']) && !$element['format']['#access'] && preg_match('/^[0-9]*\.format$/', $violation->getPropertyPath())) {
      // Ignore validation errors for formats that may not be changed,       // such as when existing formats become invalid.       // See \Drupal\filter\Element\TextFormat::processFormat().       return FALSE;
    }
    return $element;
  }

}

    $violations = $this->typedDataManager->create($definition, 10)->validate();
    $this->assertEquals(0, $violations->count());

    $integer = $this->typedDataManager->create($definition, 1);
    $violations = $integer->validate();
    $this->assertEquals(1, $violations->count());

    // Test translating violation messages.     $message = t('This value should be %limit or more.', ['%limit' => 5]);
    $this->assertEquals($message$violations[0]->getMessage(), 'Translated violation message retrieved.');
    $this->assertEquals('', $violations[0]->getPropertyPath());
    $this->assertSame($integer$violations[0]->getRoot(), 'Root object returned.');

    // Test translating violation messages when pluralization is used.     $definition = DataDefinition::create('string')
      ->setConstraints([
        'Length' => ['min' => 10],
      ]);
    $violations = $this->typedDataManager->create($definition, "short")->validate();
    $this->assertEquals(1, $violations->count());
    $message = t('This value is too short. It should have %limit characters or more.', ['%limit' => 10]);
    $this->assertEquals($message$violations[0]->getMessage(), 'Translated violation message retrieved.');

    
if ($allowed_formats && !$this->isDefaultValueWidget($form_state)) {
      $element['#allowed_formats'] = $allowed_formats;
    }

    return $element;
  }

  /** * {@inheritdoc} */
  public function errorElement(array $element, ConstraintViolationInterface $violation, array $form, FormStateInterface $form_state) {
    if (isset($element['format']['#access']) && !$element['format']['#access'] && preg_match('/^[0-9]*\.format$/', $violation->getPropertyPath())) {
      // Ignore validation errors for formats if formats may not be changed,       // such as when existing formats become invalid.       // See \Drupal\filter\Element\TextFormat::processFormat().       return FALSE;
    }
    return $element;
  }

}
class PropertyPathAccessor implements DataAccessorInterface
{
    private PropertyAccessorInterface $propertyAccessor;

    public function __construct(PropertyAccessorInterface $propertyAccessor = null)
    {
        $this->propertyAccessor = $propertyAccessor ?? PropertyAccess::createPropertyAccessor();
    }

    public function getValue(object|array $data, FormInterface $form): mixed
    {
        if (null === $propertyPath = $form->getPropertyPath()) {
            throw new AccessException('Unable to read from the given form data as no property path is defined.');
        }

        return $this->getPropertyValue($data$propertyPath);
    }

    public function setValue(object|array &$data, mixed $value, FormInterface $form): void
    {
        if (null === $propertyPath = $form->getPropertyPath()) {
            throw new AccessException('Unable to write the given value as no property path is defined.');
        }

        
'type' => 'entity_test',
      'test_textwithsummary' => ['value' => $this->randomMachineName()],
    ]);
    $form = \Drupal::service('entity.form_builder')->getForm($entity);
    $this->assertNotEmpty($form['test_textwithsummary']['widget'][0]['summary'], 'Summary field is shown');
    $this->assertNotEmpty($form['test_textwithsummary']['widget'][0]['summary']['#required'], 'Summary field is required');

    // Test validation.     /** @var \Symfony\Component\Validator\ConstraintViolation[] $violations */
    $violations = $entity->validate();
    $this->assertCount(1, $violations);
    $this->assertEquals('test_textwithsummary.0.summary', $violations[0]->getPropertyPath());
    $this->assertEquals('The summary field is required for A text field', $violations[0]->getMessage());
  }

  /** * Test text normalization when filter_html or filter_htmlcorrector enabled. */
  public function testNormalization() {
    FilterFormat::create([
      'format' => 'filter_html_enabled',
      'name' => 'Filter HTML enabled',
      'filters' => [
        
self::assertEquals($engine$form->getData());
    }

    public function testMapDataToFormsIgnoresEmptyPropertyPath()
    {
        $car = new \stdClass();

        $config = new FormConfigBuilder(null, \stdClass::class$this->dispatcher);
        $config->setByReference(true);
        $form = new Form($config);

        self::assertNull($form->getPropertyPath());

        $this->mapper->mapDataToForms($carnew \ArrayIterator([$form]));

        self::assertNull($form->getData());
    }

    public function testMapDataToFormsIgnoresUnmapped()
    {
        $car = new \stdClass();
        $car->engine = new \stdClass();
        $propertyPath = new PropertyPath('engine');

        
 else {
            $payloadFieldsToSerialize = [];
        }

        if (\is_array($payloadFieldsToSerialize) && [] !== $payloadFieldsToSerialize) {
            $payloadFieldsToSerialize = array_flip($payloadFieldsToSerialize);
        }

        $violations = [];
        $messages = [];
        foreach ($object as $violation) {
            $propertyPath = $this->nameConverter ? $this->nameConverter->normalize($violation->getPropertyPath(), null, $format$context) : $violation->getPropertyPath();

            $violationEntry = [
                'propertyPath' => $propertyPath,
                'title' => $violation->getMessage(),
                'template' => $violation->getMessageTemplate(),
                'parameters' => $violation->getParameters(),
            ];
            if (null !== $code = $violation->getCode()) {
                $violationEntry['type'] = sprintf('urn:uuid:%s', $code);
            }

            
$this->assertEquals('This value should not be null.', $violations[0]->getMessage());

    $test_entity = clone $entity;
    $test_entity->name->value = $this->randomString(65);
    $violations = $test_entity->validate();
    $this->assertEquals(1, $violations->count(), 'Validation failed.');
    $this->assertEquals(t('%name: may not be longer than @max characters.', ['%name' => 'Name', '@max' => 64])$violations[0]->getMessage());

    // Make sure the information provided by a violation is correct.     $violation = $violations[0];
    $this->assertEquals($test_entity$violation->getRoot()->getValue(), 'Violation root is entity.');
    $this->assertEquals('name.0.value', $violation->getPropertyPath(), 'Violation property path is correct.');
    $this->assertEquals($test_entity->name->value, $violation->getInvalidValue(), 'Violation contains invalid value.');

    $test_entity = clone $entity;
    $test_entity->set('user_id', 9999);
    $violations = $test_entity->validate();
    $this->assertEquals(1, $violations->count(), 'Validation failed.');
    $this->assertEquals(t('The referenced entity (%type: %id) does not exist.', ['%type' => 'user', '%id' => 9999])$violations[0]->getMessage());

    $test_entity = clone $entity;
    $test_entity->field_test_text->format = $this->randomString(33);
    $violations = $test_entity->validate();
    
 void {
        $violationList = new ConstraintViolationList();

        foreach ($constraints as $constraint) {
            $violations = $this->validator->validate($data->getValue()$constraint);

            /** @var ConstraintViolation $violation */
            foreach ($violations as $violation) {
                $fieldName = $data->getKey();

                // correct pointer for json fields with pre-defined structure                 if ($violation->getPropertyPath()) {
                    $property = str_replace('][', '/', $violation->getPropertyPath());
                    $property = trim($property, '][');
                    $fieldName .= '/' . $property;
                }

                $fieldName = '/' . $fieldName;

                $violationList->add(
                    new ConstraintViolation(
                        $violation->getMessage(),
                        $violation->getMessageTemplate(),
                        


                return $a;
            },
            FormInterface::class => static fn (FormInterface $f, array $a) => [
                Caster::PREFIX_VIRTUAL.'name' => $f->getName(),
                Caster::PREFIX_VIRTUAL.'type_class' => new ClassStub($f->getConfig()->getType()->getInnerType()::class),
            ],
            FormView::class => StubCaster::cutInternals(...),
            ConstraintViolationInterface::class => static fn (ConstraintViolationInterface $v, array $a) => [
                Caster::PREFIX_VIRTUAL.'root' => $v->getRoot(),
                Caster::PREFIX_VIRTUAL.'path' => $v->getPropertyPath(),
                Caster::PREFIX_VIRTUAL.'value' => $v->getInvalidValue(),
            ],
        ];
    }

    private function DrecursiveBuildPreliminaryFormTree(FormInterface $form, array &$outputByHash): array
    {
        $hash = spl_object_hash($form);

        $output = &$outputByHash[$hash];
        $output = $this->dataByForm[$hash]
            
$root_definition = $root_definition->getItemDefinition();
    }

    // Root data type and settings.     $parts[] = $root_definition->getDataType();
    if ($settings = $root_definition->getSettings()) {
      // Include the settings serialized as JSON as part of the key. The JSON is       // a shorter string than the serialized form, so array access is faster.       $parts[] = json_encode($settings);
    }
    // Property path for the requested data object.     $parts[] = $object->getPropertyPath();
    // Only property instances of complex data types should be cached by the     // property name, as they represent different properties. Properties of list     // data types are the items of the list and the property name represents     // only the delta in that list and not an unique property, which is why all     // items should use the same prototype.     if ($object instanceof ComplexDataInterface) {
      $parts[] = $property_name;
    }
    $key = implode(':', $parts);

    // Create the prototype if needed.

    $parent = EntityTest::create([
      'name' => 'test',
      'user_id' => ['target_id' => 0],
      'string_required' => 'some string',
      'field_test' => ['entity' => $child],
    ]);
    // The child entity should fail the validation and the violation should     // propagate to the parent.     $violations = $parent->validate();
    $this->assertCount(1, $violations);
    $this->assertEquals('field_test', $violations[0]->getPropertyPath());
    $this->assertEquals('Invalid referenced entity.', $violations[0]->getMessage());
  }

}

  private function validatePairToViolationsArray(EditorInterface $text_editor, FilterFormatInterface $text_format, bool $all_compatibility_problems): array {
    $violations = CKEditor5::validatePair($text_editor$text_format$all_compatibility_problems);
    $actual_violations = [];
    foreach ($violations as $violation) {
      if (!isset($actual_violations[$violation->getPropertyPath()])) {
        $actual_violations[$violation->getPropertyPath()] = (string) $violation->getMessage();
      }
      else {
        // Transform value from string to array.         if (is_string($actual_violations[$violation->getPropertyPath()])) {
          $actual_violations[$violation->getPropertyPath()] = (array) $actual_violations[$violation->getPropertyPath()];
        }
        // And append.         $actual_violations[$violation->getPropertyPath()][] = (string) $violation->getMessage();
      }
    }
    
Home | Imprint | This part of the site doesn't use cookies.