Completed
Push — master ( b12b0a...941074 )
by mw
127:49 queued 93:00
created

StringValidator::isMatch()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 13
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 2
dl 0
loc 13
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
namespace SMW\Tests\Utils\Validators;
4
5
/**
6
 * @license GNU GPL v2+
7
 * @since   2.1
8
 *
9
 * @author mwjames
10
 */
11
class StringValidator extends \PHPUnit_Framework_Assert {
12
13
	/**
14
	 * @since 2.1
15
	 *
16
	 * @param mixed $expected
17
	 * @param string $actual
18
	 */
19
	public function assertThatStringContains( $expected, $actual, $message = '' ) {
20
21
		$callback = function( &$expected, $actual, &$actualCounted ) {
22
			foreach ( $expected as $key => $pattern ) {
23
				if ( $this->isMatch( $pattern, $actual ) ) {
24
					$actualCounted++;
25
					unset( $expected[$key] );
26
				}
27
			}
28
		};
29
30
		$this->doAssertWith( $expected, $actual, $message, 'StringContains', $callback );
31
	}
32
33
	/**
34
	 * @since 2.3
35
	 *
36
	 * @param mixed $expected
37
	 * @param string $actual
38
	 */
39
	public function assertThatStringNotContains( $expected, $actual, $message = '' ) {
40
41
		$callback = function( &$expected, $actual, &$actualCounted ) {
42
			foreach ( $expected as $key => $string ) {
43
				if ( strpos( $actual, $string ) === false ) {
44
					$actualCounted++;
45
					unset( $expected[$key] );
46
				}
47
			}
48
		};
49
50
		$this->doAssertWith( $expected, $actual, $message, 'StringNotContains', $callback );
51
	}
52
53
	private function doAssertWith( $expected, $actual, $message = '', $method = '', $callback ) {
54
55
		if ( !is_array( $expected ) ) {
56
			$expected = array( $expected );
57
		}
58
59
		$expected = array_filter( $expected, 'strlen' );
60
61
		if ( $expected === array() ) {
62
			return self::assertTrue( true, $message );
63
		}
64
65
		self::assertInternalType(
66
			'string',
67
			$actual
68
		);
69
70
		$expectedToCount = count( $expected );
71
		$actualCounted = 0;
72
73
		call_user_func_array(
74
			$callback,
75
			array( &$expected, $actual, &$actualCounted )
76
		);
77
78
		self::assertEquals(
79
			$expectedToCount,
80
			$actualCounted,
81
			"Failed on `{$message}` for $actual with ($method) " . $this->toString( $expected )
82
		);
83
	}
84
85
	private function isMatch( $pattern, $source ) {
86
87
		// .* indicator to use the preg_match/wildcard search match otherwise
88
		// use a simple strpos (as it is faster)
89
		if ( strpos( $pattern, '.*' ) === false ) {
90
			return strpos( $source, $pattern ) !== false;
91
		}
92
93
		$pattern = preg_quote( $pattern, '/' );
94
		$pattern = str_replace( '\.\*' , '.*?', $pattern );
95
96
		return (bool)preg_match( '/' . $pattern . '/' , $source );
97
	}
98
99
	private function toString( $expected ) {
100
		return "[ " . ( is_array( $expected ) ? implode( ', ', $expected ) : $expected ) . " ]";
101
	}
102
103
}
104