ValidatesPostTypeTrait::assertPostType()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
cc 2
eloc 4
nc 2
nop 2
dl 0
loc 9
ccs 0
cts 5
cp 0
crap 6
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Leonidas\Library\System\Model\Abstracts\Post;
4
5
use InvalidArgumentException;
6
use Stringable;
7
use WP_Post;
8
use WP_Query;
0 ignored issues
show
Bug introduced by
The type WP_Query was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
9
10
trait ValidatesPostTypeTrait
11
{
12
    /**
13
     * @throws InvalidArgumentException
14
     */
15
    protected function assertPostType(WP_Post $post, string $postType): self
16
    {
17
        if ($postType !== $actual = $post->post_type) {
18
            throw new InvalidArgumentException(
19
                "The post type of the post must be \"{$postType}\", but it is \"{$actual}.\"",
20
            );
21
        }
22
23
        return $this;
24
    }
25
26
    /**
27
     * @throws InvalidArgumentException
28
     */
29
    protected function assertPostTypeOnQuery(WP_Query $query, string $postType): self
30
    {
31
        $actual = $query->get('post_type')
32
            ?: $query->get_queried_object()->post_type
33
            ?? $postType;
34
35
        if (is_array($actual) && count($actual) === 1) {
36
            $actual = $actual[0];
37
        } elseif (!is_string($actual)) {
38
            $actual = null;
39
        }
40
41
        if ($postType !== $actual) {
42
            if (is_string($actual) || $actual instanceof Stringable) {
43
                $message = "Query post_type value must be \"{$postType}\", but it is \"{$actual}\".";
44
            } elseif (is_array($actual) && in_array($postType, $actual, true)) {
45
                $message = "post_type value for query must be exclusively for \"{$postType}\".";
46
            } else {
47
                $message = "Query post_type value must be \"{$postType}\".";
48
            }
49
50
            throw new InvalidArgumentException($message);
51
        }
52
53
        return $this;
54
    }
55
}
56