Completed
Push — develop ( df3f0b...88eeb8 )
by David
07:56 queued 02:04
created

Wordlift_Timeline_Service::date()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 5
nc 1
nop 1
dl 0
loc 9
rs 9.6666
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * Provides functions and AJAX endpoints to support the Timeline widget.
5
 *
6
 * @since 3.1.0
7
 */
8
class Wordlift_Timeline_Service {
9
10
	/**
11
	 * The Log service.
12
	 *
13
	 * @since 3.1.0
14
	 * @access private
15
	 * @var \Wordlift_Log_Service $log_service The Log service.
16
	 */
17
	private $log_service;
18
19
	/**
20
	 * The Entity service.
21
	 *
22
	 * @since 3.1.0
23
	 * @access private
24
	 * @var \Wordlift_Entity_Service $entity_service The Entity service.
25
	 */
26
	private $entity_service;
27
28
	/**
29
	 * The number of words to use for the excerpt, set in the `to_json` function
30
	 * and used by a filter.
31
	 *
32
	 * @since 3.7.0
33
	 * @access private
34
	 * @var int $excerpt_length The number of words to use for the excerpt.
35
	 */
36
	private $excerpt_length;
37
38
	/**
39
	 * A singleton instance of the Timeline service (useful for unit tests).
40
	 *
41
	 * @since 3.1.0
42
	 * @access private
43
	 * @var \Wordlift_Timeline_Service $instance The singleton instance.
44
	 */
45
	private static $instance;
46
47
	/**
48
	 * Create a Wordlift_Timeline_Service instance.
49
	 *
50
	 * @since 3.1.0
51
	 *
52
	 * @param \Wordlift_Entity_Service $entity_service The Entity service.
53
	 */
54
	public function __construct( $entity_service ) {
55
56
		$this->log_service = Wordlift_Log_Service::get_logger( 'Wordlift_Timeline_Service' );
57
58
		$this->entity_service = $entity_service;
59
60
		self::$instance = $this;
61
62
	}
63
64
	/**
65
	 * Get the singleton instance of the Wordlift_Timeline_Service
66
	 *
67
	 * @since 3.1.0
68
	 *
69
	 * @return \Wordlift_Timeline_Service The singleton instance of the Wordlift_Timeline_Service.
70
	 */
71
	public static function get_instance() {
72
73
		return self::$instance;
74
	}
75
76
	/**
77
	 * Retrieve timeline events and output them in JSON.
78
	 *
79
	 * @since 3.1.0
80
	 */
81
	public function ajax_timeline() {
82
83
		// Get the ID of the post who requested the timeline.
84
		$post_id = ( isset( $_REQUEST['post_id'] ) ? $_REQUEST['post_id'] : NULL );
85
86
		// Get the events and transform them for the JSON response, then send them to the client.
87
		wp_send_json( $this->to_json( $this->get_events( $post_id ) ) );
88
89
	}
90
91
	/**
92
	 * Retrieve timeline events.
93
	 *
94
	 * @since 3.1.0
95
	 *
96
	 * @uses wl_core_get_related_entity_ids() to retrieve the entities referenced by the specified post.
97
	 *
98
	 * @param int $post_id The post ID.
99
	 *
100
	 * @return array An array of event posts.
101
	 */
102
	public function get_events( $post_id = NULL ) {
103
104
		// Get the entity IDs either from the entities related to the specified post or from the last 50 published
105
		// posts if no post has been specified.
106
		$ids = ( is_numeric( $post_id )
107
			? wl_core_get_related_entity_ids( $post_id )
108
			: $this->entity_service->get_all_related_to_last_50_published_posts() );
109
110
		// Add the post itself if it's an entity.
111
		if ( is_numeric( $post_id ) && $this->entity_service->is_entity( $post_id ) ) {
112
			$ids[] = $post_id;
113
		}
114
115
		// If there's no entities, return an empty array right away.
116
		if ( 0 === sizeof( $ids ) ) {
117
			$this->log_service->trace( "No events found [ post id :: $post_id ]" );
118
119
			return array();
120
		}
121
122
		$this->log_service->trace( "Getting events [ entity ids :: " . join( ', ', $ids ) . " ]" );
123
124
		return get_posts( array(
125
			'post__in'       => $ids,
126
			'post_type'      => Wordlift_Entity_Service::TYPE_NAME,
127
			'post_status'    => 'publish',
128
			'posts_per_page' => - 1,
129
			'meta_query'     => array(
130
				'relation' => 'AND',
131
				array(
132
					'key'     => Wordlift_Schema_Service::FIELD_DATE_START,
133
					'value'   => NULL,
134
					'compare' => '!='
135
				),
136
				array(
137
					'key'     => Wordlift_Schema_Service::FIELD_DATE_END,
138
					'value'   => NULL,
139
					'compare' => '!='
140
				)
141
			),
142
			'tax_query'      => array(
143
				'taxonomy' => Wordlift_Entity_Types_Taxonomy_Service::TAXONOMY_NAME,
144
				'field'    => 'slug',
145
				'terms'    => 'event'
146
			)
147
		) );
148
	}
149
150
	/**
151
	 * Convert timeline events to JSON. This function sets the global post in order
152
	 * to get an automatic excerpt. Since we're being called inside an AJAX request,
153
	 * we're not taking care of restoring any previous post: there isn't any.
154
	 *
155
	 * @since 3.1.0
156
	 *
157
	 * @param array $posts An array of posts.
158
	 *
159
	 * @return array|string An array of timeline events or an empty string if no posts are provided.
160
	 */
161
	public function to_json( $posts ) {
0 ignored issues
show
Coding Style introduced by
to_json uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
Coding Style introduced by
to_json uses the super-global variable $GLOBALS which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
162
163
		// If there are no events, return empty JSON
164
		if ( empty( $posts ) || is_null( $posts ) ) {
165
			return '';
166
		}
167
168
		// {media|thumbnail}: if set to 'media' the image is attached to the slide, if set to 'background' the image is set as background.
169
		$display_images_as = isset( $_REQUEST['display_images_as'] ) ? $_REQUEST['display_images_as'] : 'media';
170
171
		// The number of words for the excerpt (by default 55, as WordPress).
172
		$this->excerpt_length = isset( $_REQUEST['excerpt_words'] ) && is_numeric( $_REQUEST['excerpt_words'] ) ? $_REQUEST['excerpt_words'] : 55;
173
		add_filter( 'excerpt_length', array( $this, 'excerpt_length' ) );
174
175
		// Add a filter to remove the [...] after excerpts, since we're adding
176
		// a link to the post itself.
177
		add_filter( 'excerpt_more', array( $this, 'excerpt_more' ) );
178
179
		// Prepare for the starting slide data. The starting slide will be the one where *now* is between *start/end* dates.
180
		$start_at_slide = 0;
181
		$event_index    = - 1;
182
		$now            = time();
183
184
		// Prepare the timeline variable.
185
		$timeline = array();
186
187
		// Populate the arrays.
188
		$timeline['events'] = array_map( function ( $item ) use ( &$timeline, &$event_index, &$start_at_slide, &$now, $display_images_as ) {
189
190
			// Get the start and end dates.
191
			$start_date = strtotime( get_post_meta( $item->ID, Wordlift_Schema_Service::FIELD_DATE_START, TRUE ) );
192
			$end_date   = strtotime( get_post_meta( $item->ID, Wordlift_Schema_Service::FIELD_DATE_END, TRUE ) );
193
194
			// Set the starting slide.
195
			$event_index ++;
196
			if ( 0 === $start_at_slide && $now >= $start_date && $now <= $end_date ) {
197
				$start_at_slide = $event_index;
198
			}
199
200
			// Load thumbnail
201
			if ( '' !== ( $thumbnail_id = get_post_thumbnail_id( $item->ID ) )
202
			     && FALSE !== ( $attachment = wp_get_attachment_image_src( $thumbnail_id ) )
203
			) {
204
205
				// Set the thumbnail URL.
206
				if ( 'background' === $display_images_as ) {
207
					$date['background'] = array( 'url' => $attachment[0], );
0 ignored issues
show
Coding Style Comprehensibility introduced by
$date was never initialized. Although not strictly required by PHP, it is generally a good practice to add $date = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
208
					$date['media']      = array( 'thumbnail' => $attachment[0], );
209
				} else {
210
					$date['media'] = array(
0 ignored issues
show
Coding Style Comprehensibility introduced by
$date was never initialized. Although not strictly required by PHP, it is generally a good practice to add $date = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
211
						'url'       => $attachment[0],
212
						'thumbnail' => $attachment[0],
213
					);
214
				}
215
216
			}
217
218
			// Set the start/end dates by converting them to TimelineJS required format.
219
			$date['start_date'] = Wordlift_Timeline_Service::date( $start_date );
0 ignored issues
show
Bug introduced by
The variable $date does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
220
			$date['end_date']   = Wordlift_Timeline_Service::date( $end_date );
221
222
			setup_postdata( $GLOBALS['post'] = &$item );
223
224
			$more_link_text = sprintf(
225
				'<span aria-label="%1$s">%2$s</span>',
226
				sprintf(
227
				/* translators: %s: Name of current post */
228
					__( 'Continue reading %s' ),
229
					the_title_attribute( array( 'echo' => FALSE ) )
230
				),
231
				__( '(more&hellip;)' )
232
			);
233
234
			// Set the event text only with the headline (see https://github.com/insideout10/wordlift-plugin/issues/352).
235
			$date['text'] = array(
236
				'headline' => '<a href="' . get_permalink( $item->ID ) . '">' . $item->post_title . '</a>',
237
			);
238
239
			// If we have an excerpt, set it.
240
			if ( 0 < $this->excerpt_length ) {
241
				$date['text']['text'] = sprintf( '%s <a href="%s">%s</a>', get_the_excerpt( $item ), get_permalink(), $more_link_text );
242
			}
243
244
			return $date;
245
246
		}, $posts );
247
248
		// Finally remove the excerpt filter.
249
		remove_filter( 'excerpt_length', array( $this, 'excerpt_length' ) );
250
251
		// The JSON format is defined here: https://timeline.knightlab.com/docs/json-format.html
252
		return array(
253
			'timeline'       => $timeline,
254
			'start_at_slide' => $start_at_slide,
255
		);
256
	}
257
258
	/**
259
	 * This function filters {@link excerpt_more} by removing it, since we're
260
	 * adding the 'read more' link. This filter is set by {@see to_json}.
261
	 *
262
	 * @since 3.7.0
263
	 *
264
	 * @param string $excerpt_more The excerpt more preset.
265
	 *
266
	 * @return string An empty string.
267
	 */
268
	public function excerpt_more( $excerpt_more ) {
0 ignored issues
show
Unused Code introduced by
The parameter $excerpt_more is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
269
270
		return '';
271
	}
272
273
	/**
274
	 * A filter for the excerpt length, set by the `to_json` function, to tailor
275
	 * how many words to return according to the client setting.
276
	 *
277
	 * @since 3.7.0
278
	 *
279
	 * @param int $length The preset number of words.
280
	 *
281
	 * @return int The number of words for the preset.
282
	 */
283
	public function excerpt_length( $length ) {
0 ignored issues
show
Unused Code introduced by
The parameter $length is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
284
285
		return $this->excerpt_length;
286
	}
287
288
289
	/**
290
	 * Convert the date to a date array.
291
	 *
292
	 * @since 3.7.0
293
	 *
294
	 * @param $value int A date value.
295
	 *
296
	 * @return array An array containing year, month and day values.
297
	 */
298
	public static function date( $value ) {
299
300
		return array(
301
			'year'  => (int) date( 'Y', $value ),
302
			'month' => (int) date( 'm', $value ),
303
			'day'   => (int) date( 'd', $value ),
304
305
		);
306
	}
307
308
}
309