Completed
Pull Request — master (#22)
by mw
03:56
created

getSubjectIdListFromOrderedTableDiff()   B

Complexity

Conditions 6
Paths 17

Size

Total Lines 25
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 17
CRAP Score 6

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 25
ccs 17
cts 17
cp 1
rs 8.439
cc 6
eloc 12
nc 17
nop 1
crap 6
1
<?php
2
3
namespace SCI;
4
5
use SMW\Store;
6
use SMW\DIProperty;
7
use SMW\DIWikiPage;
8
use SMW\ApplicationFactory;
9
use SMW\HashBuilder;
10
use SMW\SQLStore\CompositePropertyTableDiffIterator;
11
12
/**
13
 * If a citation text was altered then lookup related references on pages used
14
 * and schedule a dispatch update job.
15
 *
16
 * @license GNU GPL v2+
17
 * @since 1.0
18
 *
19
 * @author mwjames
20
 */
21
class CitationTextChangeUpdateJobDispatcher {
22
23
	/**
24
	 * @var Store
25
	 */
26
	private $store;
27
28
	/**
29
	 * @var ReferenceBacklinksLookup
30
	 */
31
	private $referenceBacklinksLookup;
32
33
	/**
34
	 * @var boolean
35
	 */
36
	private $enabledUpdateJobState = true;
37
38
	/**
39
	 * @since  1.0
40
	 *
41
	 * @param Store $store
42
	 * @param ReferenceBacklinksLookup $referenceBacklinksLookup
43
	 */
44 19
	public function __construct( Store $store, ReferenceBacklinksLookup $referenceBacklinksLookup ) {
45 19
		$this->store = $store;
46 19
		$this->referenceBacklinksLookup = $referenceBacklinksLookup;
47 19
	}
48
49
	/**
50
	 * @since  1.0
51
	 *
52
	 * @param boolean $enabledUpdateJobState
53
	 */
54 15
	public function setEnabledUpdateJobState( $enabledUpdateJobState ) {
55 15
		$this->enabledUpdateJobState = $enabledUpdateJobState;
56 15
	}
57
58
	/**
59
	 * @since  1.0
60
	 *
61
	 * @param DIWikiPage $subject
62
	 * @param CompositePropertyTableDiffIterator $compositePropertyTableDiffIterator
63
	 *
64
	 * @return boolean
65
	 */
66 18
	public function dispatchUpdateJobFor( DIWikiPage $subject, CompositePropertyTableDiffIterator $compositePropertyTableDiffIterator ) {
67
68 18
		if ( !$this->enabledUpdateJobState ) {
69 15
			return false;
70
		}
71
72 3
		$tableName = $this->store->getPropertyTableInfoFetcher()->findTableIdForProperty(
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class SMW\Store as the method getPropertyTableInfoFetcher() does only exist in the following sub-classes of SMW\Store: SMWSQLStore3, SMW\Tests\Utils\Mock\FakeQueryStore. 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...
73 3
			new DIProperty( PropertyRegistry::SCI_CITE_TEXT )
74 3
		);
75
76 3
		$subjectIdList = $this->getSubjectIdListFromOrderedTableDiff(
77 3
			$compositePropertyTableDiffIterator->getOrderedDiffByTable( $tableName )
78 3
		);
79
80 3
		if ( $subjectIdList === array() ) {
81 1
			return false;
82
		}
83
84 2
		$updateDispatcherJob = ApplicationFactory::getInstance()->newJobFactory()->newUpdateDispatcherJob(
85 2
			$subject->getTitle(),
0 ignored issues
show
Bug introduced by
It seems like $subject->getTitle() can be null; however, newUpdateDispatcherJob() 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...
86
			array(
87 2
				'job-list' => $this->getDispatchableTargetList( $subjectIdList )
88 2
			)
89 2
		);
90
91 2
		$updateDispatcherJob->insert();
92
93 2
		return true;
94
	}
95
96 3
	private function getSubjectIdListFromOrderedTableDiff( array $orderedTableDiff ) {
97
98 3
		$subjectIdList = array();
99
100 3
		foreach ( $orderedTableDiff as $key => $value ) {
101
102 2
			if ( !isset( $value['delete'] ) ) {
103 1
				$value['delete'] = array();
104 1
			}
105
106 2
			foreach ( $value['delete'] as $delete ) {
107 1
				$subjectIdList[] = $delete['s_id'];
108 2
			}
109
110 2
			if ( !isset( $value['insert'] ) ) {
111 1
				$value['insert'] = array();
112 1
			}
113
114 2
			foreach ( $value['insert'] as $insert ) {
115 1
				$subjectIdList[] = $insert['s_id'];
116 2
			}
117 3
		}
118
119 3
		return $subjectIdList;
120
	}
121
122 2
	private function getDispatchableTargetList( array $subjectIdList ) {
123
124 2
		$hashList = $this->store->getObjectIds()->getDataItemPoolHashListFor( $subjectIdList );
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class SMW\Store as the method getObjectIds() does only exist in the following sub-classes of SMW\Store: SMWSQLStore3, SMWSparqlStore, SMW\SPARQLStore\SPARQLStore, SMW\Tests\Utils\Mock\FakeQueryStore. 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...
125 2
		$referenceBacklinks = array();
126
127 2
		foreach ( $hashList as $hash ) {
128 2
			$referenceBacklinks += $this->referenceBacklinksLookup->findReferenceBacklinksFor(
129 2
				$this->referenceBacklinksLookup->tryToFindCitationKeyFor( DIWikiPage::doUnserialize( $hash ) )
130 2
			);
131 2
		}
132
133 2
		$targetBatch = array();
134
135 2
		foreach ( $referenceBacklinks as $referenceBacklink ) {
136 2
			$targetBatch[HashBuilder::getHashIdForDiWikiPage( $referenceBacklink )] = true;
137 2
		}
138
139 2
		return $targetBatch;
140
	}
141
142
}
143