• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

phpolar / model / 6342020820

28 Sep 2023 05:04PM UTC coverage: 91.815%. First build
6342020820

Pull #43

github

web-flow
Merge b2a566f61 into 1d352f618
Pull Request #43: build(deps-dev): bump phpmd/phpmd from 2.14.0 to 2.14.1

258 of 281 relevant lines covered (91.81%)

7.74 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/ValidationTrait.php
1
<?php
2

3
declare(strict_types=1);
4

5
namespace Phpolar\Model;
6

7
use PhpContrib\Validator\ValidatorInterface;
8
use ReflectionAttribute;
9
use ReflectionObject;
10
use ReflectionProperty;
11

12
/**
13
 * Use to add support for validating the properties of an object.
14
 */
15
trait ValidationTrait
16
{
17
    /**
18
     * Determines if the configured properties of an object
19
     * are valid.
20
     *
21
     * The configuration is used to determine validity.
22
     *
23
     * @api
24
     */
25
    public function isValid(): bool
26
    {
27
        return array_reduce(
×
28
            (new ReflectionObject($this))->getProperties(ReflectionProperty::IS_PUBLIC),
×
29
            $this->validateProperty(...),
×
30
            true
×
31
        );
×
32
    }
33

34
    /**
35
     * Uses validation attributes to determine if the
36
     * property is valid.
37
     */
38
    private function validateProperty(bool $prev, ReflectionProperty $prop): bool
39
    {
40
        return $prev && array_reduce(
×
41
            $this->getValidators($prop),
×
42
            static fn (bool $previousResult, ValidatorInterface $currentAttribute) =>
×
43
                $previousResult && $currentAttribute->isValid(),
×
44
            true
×
45
        );
×
46
    }
47

48
    /**
49
     * Provides a way of retrieving only the validator attributes of a property.
50
     *
51
     * Returns only validation attributes.
52
     *
53
     * @return ValidatorInterface[]
54
     */
55
    private function getValidators(ReflectionProperty $prop): array
56
    {
57
        return array_map(
×
58
            function (ValidatorInterface $instance) use ($prop): ValidatorInterface {
×
59
                if (property_exists($instance, "propVal") === true) {
×
60
                    $instance->propVal = $prop->isInitialized($this) === true ? $prop->getValue($this) : $prop->getDefaultValue();
×
61
                }
62
                return $instance;
×
63
            },
×
64
            array_map(
×
65
                static fn (ReflectionAttribute $attr) => $attr->newInstance(),
×
66
                $prop->getAttributes(ValidatorInterface::class, ReflectionAttribute::IS_INSTANCEOF),
×
67
            ),
×
68
        );
×
69
    }
70
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc