Completed
Push — master ( d2d28e...1c2760 )
by mw
35:37
created

MandatoryTypePropertyAnnotator.php (4 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace SMW\PropertyAnnotator;
4
5
use SMW\DataTypeRegistry;
6
use SMW\DataValueFactory;
7
use SMW\DIProperty;
8
use SMW\PropertyAnnotator;
9
use SMW\Store;
10
11
/**
12
 * @license GNU GPL v2+
13
 * @since 2.2
14
 *
15
 * @author mwjames
16
 */
17
class MandatoryTypePropertyAnnotator extends PropertyAnnotatorDecorator {
18
19 187
	protected function addPropertyValues() {
20
21 187
		$subject = $this->getSemanticData()->getSubject();
22
23 187
		if ( $subject->getNamespace() !== SMW_NS_PROPERTY ) {
24 177
			return;
25
		}
26
27 146
		$property = DIProperty::newFromUserLabel(
28 146
			str_replace( '_', ' ', $subject->getDBKey() )
29
		);
30
31 146
		if ( !$property->isUserDefined() ) {
32 1
			return;
33
		}
34
35 145
		$this->findMandatoryTypeForImportVocabulary();
36 145
	}
37
38 145
	private function findMandatoryTypeForImportVocabulary() {
39
40 145
		$property = new DIProperty( '_IMPO' );
41
42 145
		$dataItems = $this->getSemanticData()->getPropertyValues(
43
			$property
44
		);
45
46 145
		if ( $dataItems === null || $dataItems === array() ) {
47 138
			return;
48
		}
49
50 10
		$this->addTypeFromImportVocabulary( $property, current( $dataItems ) );
51 10
	}
52
53 10
	private function addTypeFromImportVocabulary( $property, $dataItem ) {
54
55 10
		$importValue = DataValueFactory::getInstance()->newDataValueByItem(
56
			$dataItem,
57
			$property
58
		);
59
60 10
		if ( strpos( $importValue->getTermType(), ':' ) === false ) {
61 1
			return;
62
		}
63
64 9
		$property = new DIProperty( '_TYPE' );
65
66 9
		list( $ns, $type ) = explode( ':', $importValue->getTermType(), 2 );
0 ignored issues
show
It seems like you code against a specific sub-type and not the parent class SMWDataValue as the method getTermType() does only exist in the following sub-classes of SMWDataValue: SMW\DataValues\ImportValue. 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...
The assignment to $ns is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
67
68 9
		$typeId = DataTypeRegistry::getInstance()->findTypeId( $type );
69
70 9
		if ( $typeId === '' ) {
71 1
			return;
72
		}
73
74 8
		$dataValue = DataValueFactory::getInstance()->newDataValueByProperty(
75
			$property,
76
			$typeId
0 ignored issues
show
$typeId is of type string, but the function expects a boolean.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
77
		);
78
79 8
		$this->replaceAnyTypeByImportType( $property, $dataValue );
80 8
	}
81
82 8
	private function replaceAnyTypeByImportType( DIProperty $property, $dataValue ) {
83
84 8
		foreach ( $this->getSemanticData()->getPropertyValues( $property ) as $dataItem ) {
0 ignored issues
show
The expression $this->getSemanticData()...opertyValues($property) of type array|object<SMWDataItem> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
85 2
			$this->getSemanticData()->removePropertyObjectValue(
86
				$property,
87
				$dataItem
88
			);
89
		}
90
91 8
		$this->getSemanticData()->addDataValue( $dataValue );
92 8
	}
93
94
}
95