Query_Helper::get_current_query()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 1 Features 1
Metric Value
cc 1
eloc 5
nc 1
nop 0
dl 0
loc 7
rs 9.4285
c 4
b 1
f 1
1
<?php
2
/**
3
 * Helper for work with WP_Query.
4
 *
5
 * @package Classy
6
 */
7
8
namespace Classy;
9
10
/**
11
 * Class Query_Helper.
12
 */
13
class Query_Helper {
14
15
	/**
16
	 * Finds or creates new query based on provided params.
17
	 *
18
	 * @param array|boolean $args Args for WP_Query.
19
	 *
20
	 * @return \WP_Query
21
	 */
22
	public static function find_query( $args = false ) {
23
		$default_args = array();
24
25
		if ( ! $args ) {
26
			return self::get_current_query();
27
		}
28
29
		if ( is_array( $args ) ) {
30
			return new \WP_Query( array_merge( $default_args, $args ) );
31
		}
32
33
		return new \WP_Query( $default_args );
34
	}
35
36
	/**
37
	 * Returns current WP_Query.
38
	 *
39
	 * @return \WP_Query
40
	 */
41
	public static function get_current_query() {
42
		global $wp_query;
0 ignored issues
show
Compatibility Best Practice introduced by
Use of global functionality is not recommended; it makes your code harder to test, and less reusable.

Instead of relying on global state, we recommend one of these alternatives:

1. Pass all data via parameters

function myFunction($a, $b) {
    // Do something
}

2. Create a class that maintains your state

class MyClass {
    private $a;
    private $b;

    public function __construct($a, $b) {
        $this->a = $a;
        $this->b = $b;
    }

    public function myFunction() {
        // Do something
    }
}
Loading history...
43
		$query =& $wp_query;
44
		$query = self::handle_maybe_custom_posts_page( $query );
45
46
		return $query;
47
	}
48
49
	/**
50
	 * Checks and returns WP_Query for home posts page.
51
	 *
52
	 * @param \WP_Query $query WP_Query object.
53
	 *
54
	 * @return \WP_Query
55
	 */
56
	private static function handle_maybe_custom_posts_page( $query ) {
57
		if ( $custom_posts_page = get_option( 'page_for_posts' ) ) {
58
			if (
59
				isset( $query->query['p'] ) &&
60
				absint( $query->query['p'] ) === absint( $custom_posts_page )
61
			) {
62
				return new \WP_Query( array( 'post_type' => 'post' ) );
63
			}
64
		}
65
66
		return $query;
67
	}
68
}
69