Completed
Push — master ( fef851...52af6f )
by Stephan
04:43
created

CacheInvalidator::matchSubobjectsToSubject()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 3.7898

Importance

Changes 0
Metric Value
dl 0
loc 14
ccs 5
cts 9
cp 0.5556
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 8
nc 3
nop 2
crap 3.7898
1
<?php
2
3
namespace SG\Cache;
4
5
use SG\SemanticDataComparator;
6
use SG\PropertyRegistry;
7
8
use SMW\Store;
9
use SMW\SemanticData;
10
use SMW\DIWikiPage;
11
use SMW\DIProperty;
12
13
use Lingo\LingoParser;
14
15
use Title;
16
17
/**
18
 * @ingroup SG
19
 * @ingroup SemanticGlossary
20
 *
21
 * @license GNU GPL v2+
22
 * @since 1.0
23
 *
24
 * @author Stephan Gambke
25
 * @author mwjames
26
 */
27
class CacheInvalidator {
28
29
	/**
30
	 * @var CacheInvalidator
31
	 */
32
	private static $instance = null;
33
34
	/**
35
	 * @var GlossaryCache
36
	 */
37
	private $cache = null;
0 ignored issues
show
Unused Code introduced by
The property $cache is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
38
39
	/**
40
	 * @since 1.0
41
	 *
42
	 * @return CacheInvalidator
43
	 */
44 4
	public static function getInstance() {
45
46 4
		if ( self::$instance === null ) {
47
48 1
			$instance = new self();
49 1
			$instance->setCache( new GlossaryCache() );
50
51 1
			self::$instance = $instance;
52
		}
53
54 4
		return self::$instance;
55
	}
56
57
	/**
58
	 * @since 1.0
59
	 */
60 1
	public static function clear() {
61 1
		self::$instance = null;
62 1
	}
63
64
	/**
65
	 * @since 1.0
66
	 *
67
	 * @param GlossaryCache $glossaryCache
68
	 */
69 6
	public function setCache( GlossaryCache $glossaryCache ) {
70 6
		$this->glossaryCache = $glossaryCache;
0 ignored issues
show
Bug introduced by
The property glossaryCache does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
71 6
	}
72
73
	/**
74
	 * @since 1.0
75
	 *
76
	 * @param Store $store
77
	 * @param SemanticData $semanticData
78
	 *
79
	 * @return boolean
80
	 */
81 5
	public function invalidateCacheOnStoreUpdate( Store $store, SemanticData $semanticData ) {
82
83 5
		$this->matchAllSubobjects( $store, $semanticData );
84
85 5
		if ( $this->hasSemanticDataDeviation( $store, $semanticData ) ) {
86 3
			$this->purgeCache( $semanticData->getSubject() );
87 3
			LingoParser::purgeCache();
0 ignored issues
show
Deprecated Code introduced by
The method Lingo\LingoParser::purgeCache() has been deprecated with message: 2.0.2

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
88
		}
89
90 5
		return true;
91
	}
92
93
	/**
94
	 * @since 1.0
95
	 *
96
	 * @param Store $store
97
	 * @param DIWikiPage $subject
98
	 * @param boolean|true $purgeLingo
99
	 *
100
	 * @return boolean
101
	 */
102 3
	public function invalidateCacheOnPageDelete( Store $store, DIWikiPage $subject, $purgeLingo = true ) {
103
104 3
		$this->matchSubobjectsToSubject( $store, $subject );
105 3
		$this->purgeCache( $subject );
106
107 3
		if ( $purgeLingo ) {
108 3
			LingoParser::purgeCache();
0 ignored issues
show
Deprecated Code introduced by
The method Lingo\LingoParser::purgeCache() has been deprecated with message: 2.0.2

This method has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the method will be removed from the class and what other method or class to use instead.

Loading history...
109
		}
110
111 3
		return true;
112
	}
113
114
	/**
115
	 * @since 1.0
116
	 *
117
	 * @param Title $title
118
	 *
119
	 * @return boolean
120
	 */
121 1
	public function invalidateCacheOnPageMove( Title $title ) {
122 1
		$this->purgeCache( DIWikiPage::newFromTitle( $title ) );
123 1
		return true;
124
	}
125
126 5
	private function matchAllSubobjects( Store $store, SemanticData $semanticData ) {
127
128 5
		$properties = $semanticData->getProperties();
129
130 5
		if ( array_key_exists( DIProperty::TYPE_SUBOBJECT, $properties ) ) {
131 1
			foreach ( $semanticData->getPropertyValues( $properties[ DIProperty::TYPE_SUBOBJECT ] ) as $subobject ) {
132 1
				$this->invalidateCacheOnStoreUpdate(
133 1
					$store,
134 1
					$semanticData->findSubSemanticData( $subobject->getSubobjectName() ),
0 ignored issues
show
Bug introduced by
It seems like $semanticData->findSubSe...ct->getSubobjectName()) can be null; however, invalidateCacheOnStoreUpdate() does not accept null, maybe add an additional type check?

Unless you are absolutely sure that the expression can never be null because of other conditions, we strongly recommend to add an additional type check to your code:

/** @return stdClass|null */
function mayReturnNull() { }

function doesNotAcceptNull(stdClass $x) { }

// With potential error.
function withoutCheck() {
    $x = mayReturnNull();
    doesNotAcceptNull($x); // Potential error here.
}

// Safe - Alternative 1
function withCheck1() {
    $x = mayReturnNull();
    if ( ! $x instanceof stdClass) {
        throw new \LogicException('$x must be defined.');
    }
    doesNotAcceptNull($x);
}

// Safe - Alternative 2
function withCheck2() {
    $x = mayReturnNull();
    if ($x instanceof stdClass) {
        doesNotAcceptNull($x);
    }
}
Loading history...
Bug introduced by
It seems like you code against a specific sub-type and not the parent class SMWDataItem as the method getSubobjectName() does only exist in the following sub-classes of SMWDataItem: SMWDIWikiPage, SMW\DIWikiPage. Maybe you want to instanceof check for one of these explicitly?

Let’s take a look at an example:

abstract class User
{
    /** @return string */
    abstract public function getPassword();
}

class MyUser extends User
{
    public function getPassword()
    {
        // return something
    }

    public function getDisplayName()
    {
        // return some name.
    }
}

class AuthSystem
{
    public function authenticate(User $user)
    {
        $this->logger->info(sprintf('Authenticating %s.', $user->getDisplayName()));
        // do something.
    }
}

In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different sub-classes of User which does not have a getDisplayName() method, the code will break.

Available Fixes

  1. Change the type-hint for the parameter:

    class AuthSystem
    {
        public function authenticate(MyUser $user) { /* ... */ }
    }
    
  2. Add an additional type-check:

    class AuthSystem
    {
        public function authenticate(User $user)
        {
            if ($user instanceof MyUser) {
                $this->logger->info(/** ... */);
            }
    
            // or alternatively
            if ( ! $user instanceof MyUser) {
                throw new \LogicException(
                    '$user must be an instance of MyUser, '
                   .'other instances are not supported.'
                );
            }
    
        }
    }
    
Note: PHP Analyzer uses reverse abstract interpretation to narrow down the types inside the if block in such a case.
  1. Add the method to the parent class:

    abstract class User
    {
        /** @return string */
        abstract public function getPassword();
    
        /** @return string */
        abstract public function getDisplayName();
    }
    
Loading history...
135 1
					false
0 ignored issues
show
Unused Code introduced by
The call to CacheInvalidator::invalidateCacheOnStoreUpdate() has too many arguments starting with false.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
136
				);
137
			}
138
		}
139 5
	}
140
141 3
	private function matchSubobjectsToSubject( Store $store, DIWikiPage $subject ) {
142
143 3
		$properties = $store->getProperties( $subject );
144
145 3
		if ( array_key_exists( DIProperty::TYPE_SUBOBJECT, $properties ) ) {
146 1
			foreach ( $store->getPropertyValues( $subject, $properties[ DIProperty::TYPE_SUBOBJECT ] ) as $subobject ) {
147
				$this->invalidateCacheOnPageDelete(
148
					$store,
149
					$subobject->getSubject(),
150
					false
151
				);
152
			}
153
		}
154 3
	}
155
156 5
	private function hasSemanticDataDeviation( Store $store, SemanticData $semanticData ) {
157
158 5
		$dataComparator = new SemanticDataComparator( $store, $semanticData );
159
160 5
		return $dataComparator->compareForProperty( PropertyRegistry::SG_TERM ) ||
161 5
			$dataComparator->compareForProperty( PropertyRegistry::SG_DEFINITION ) ||
162 5
			$dataComparator->compareForProperty( PropertyRegistry::SG_LINK ) ||
163 5
			$dataComparator->compareForProperty( PropertyRegistry::SG_STYLE );
164
	}
165
166 6
	private function purgeCache( DIWikiPage $subject ) {
167
168 6
		$this->glossaryCache->getCache()->delete(
169 6
			$this->glossaryCache->getKeyForSubject( $subject )
170
		);
171
172 6
		return true;
173
	}
174
175
}
176