Test Failed
Push — master ( 50dd93...f69d16 )
by Chris
12:03
created

ValidatesPostTypeTrait   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 42
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
wmc 11
eloc 19
c 0
b 0
f 0
dl 0
loc 42
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B assertPostTypeOnQuery() 0 23 9
A assertPostType() 0 9 2
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', null);
32
33
        if (is_array($actual) && count($actual) === 1) {
34
            $actual = $actual[0];
35
        } elseif (!is_string($actual)) {
36
            $actual = null;
37
        }
38
39
        if ($postType !== $actual) {
40
            if (is_string($actual) || $actual instanceof Stringable) {
41
                $message = "Query post_type value must be \"{$postType}\", but it is \"{$actual}\".";
42
            } elseif (is_array($actual) && in_array($postType, $actual, true)) {
43
                $message = "post_type value for query must be exclusively for \"{$postType}\".";
44
            } else {
45
                $message = "Query post_type value must be \"{$postType}\".";
46
            }
47
48
            throw new InvalidArgumentException($message);
49
        }
50
51
        return $this;
52
    }
53
}
54