Completed
Push — develop ( d494ed...7721c5 )
by Paul
02:24
created

Media::get()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 6
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 3
nc 2
nop 2
1
<?php
2
3
namespace GeminiLabs\Castor\Helpers;
4
5
use GeminiLabs\Castor\Gallery;
6
use GeminiLabs\Castor\Image;
7
use GeminiLabs\Castor\Video;
8
use BadMethodCallException;
9
10
class Media
11
{
12
	protected $gallery;
13
	protected $image;
14
	protected $video;
15
16
	public function __construct( Gallery $gallery, Image $image, Video $video )
17
	{
18
		$this->gallery = $gallery;
19
		$this->image   = $image;
20
		$this->video   = $video;
21
	}
22
23
	/**
24
	 * @param string $name
25
	 *
26
	 * @return string|void
27
	 * @throws BadMethodCallException
28
	 */
29
	public function __call( $name, array $args )
30
	{
31
		$mediaType = $this->validateMethod( $name );
32
		if( !$mediaType ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $mediaType of type string|false is loosely compared to false; this is ambiguous if the string can be empty. You might want to explicitly use === false instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For string values, the empty string '' is a special case, in particular the following results might be unexpected:

''   == false // true
''   == null  // true
'ab' == false // false
'ab' == null  // false

// It is often better to use strict comparison
'' === false // false
'' === null  // false
Loading history...
33
			throw new BadMethodCallException( sprintf( 'Not a valid method: %s', $name ));
34
		}
35
		if( !count( $args )) {
36
			throw new BadMethodCallException( sprintf( 'Missing arguments for: %s', $name ));
37
		}
38
		return !empty( $args[1] )
39
			? $this->$mediaType->get( $args[0] )->render( $args[1] )
40
			: $this->$mediaType->get( $args[0] )->render();
41
	}
42
43
	/**
44
	 * @param string $name
45
	 * @param mixed  $args
46
	 *
47
	 * @return mixed
48
	 */
49
	public function get( $name, $args = [] )
50
	{
51
		if( $mediaType = $this->validateMethod( $name )) {
52
			return $this->$mediaType->get( $args )->$mediaType;
53
		}
54
	}
55
56
	/**
57
	 * @param string $name
58
	 *
59
	 * @return string|false
60
	 */
61
	protected function validateMethod( $name )
62
	{
63
		foreach( [$name, strtolower( substr( $name, 3 ))] as $method ) {
64
			if( in_array( $method, ['gallery', 'image', 'video'] )
65
				&& property_exists( $this, $method )
66
				&& is_object( $this->$method )) {
67
				return $method;
68
			}
69
		}
70
		return false;
71
	}
72
}
73