Completed
Push — master ( 759646...873ac1 )
by mw
05:00
created

isKnownNotificationsGroup()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 1

Importance

Changes 0
Metric Value
dl 0
loc 18
rs 9.4285
c 0
b 0
f 0
ccs 10
cts 10
cp 1
cc 1
eloc 10
nc 1
nop 1
crap 1
1
<?php
2
3
namespace SMW\Notifications\DataValues;
4
5
use SMW\DataValueFactory;
6
use SMW\ApplicationFactory;
7
use SMW\DIProperty;
8
use SMW\Message;
9
use SMW\RequestOptions;
10
use SMW\Notifications\PropertyRegistry;
11
use SMWStringValue as StringValue;
12
use SMWDIBlob as DIBlob;
13
use SMWDataValue as DataValue;
14
use Html;
15
use SpecialPage;
16
17
/**
18
 * @license GNU GPL v2+
19
 * @since 1.0
20
 *
21
 * @author mwjames
22
 */
23
class NotificationGroupValue extends StringValue {
24
25
	/**
26
	 * DV identifier
27
	 */
28
	const TYPE_ID = '_notification_group';
29
30
	/**
31
	 * Special group name
32
	 */
33
	const SPECIAL_GROUP = 'smw-notifications-entity-specification-change-group';
34
35
	/**
36
	 * Get name in a possible localized representation
37
	 *
38
	 * @since 1.0
39
	 *
40
	 * @param string $language
41
	 *
42
	 * @return string
43
	 */
44 7
	public static function getSpecialGroupName( $language = Message::CONTENT_LANGUAGE ) {
45 7
		return Message::get( self::SPECIAL_GROUP, Message::TEXT, $language );
46
	}
47
48
	/**
49
	 * @see StringValue::parseUserValue
50
	 */
51 6
	protected function parseUserValue( $value ) {
52
53 6
		$inputValue = trim( $value );
54
55
		// Special group to watch property changes
56 6
		if ( mb_strtolower( $inputValue ) === self::getSpecialGroupName() ) {
57 1
			return parent::parseUserValue( $value );;
58
		}
59
60 5
		if ( !$this->isKnownNotificationsGroup( $inputValue ) ) {
61 1
			$this->addErrorMsg( array( 'smw-notifications-datavalue-invalid-group', $inputValue ), Message::PARSE );
62 1
			$this->m_dataitem = new DIBlob( 'ERROR' );
63 1
			return;
64
		}
65
66
		// If it has no contextPage it is most likely linked from a Special page
67
		// such as Special:SearchByProperty or Special:Ask
68 4
		if ( $this->getContextPage() !== null && !$this->hasUserContext() ) {
69 1
			$this->addErrorMsg( array( 'smw-notifications-datavalue-restricted-to-user', $inputValue ), Message::PARSE );
70 1
			$this->m_dataitem = new DIBlob( 'ERROR' );
71 1
			return;
72
		}
73
74 3
		parent::parseUserValue( $value );
75 3
	}
76
77
	/**
78
	 * @see StringValue::getShortWikiText
79
	 */
80 3
	public function getShortWikiText( $linker = null ) {
81
82 3
		if ( !$this->isValid() ) {
83 1
			return '';
84
		}
85
86 2
		if ( !$this->m_caption ) {
87 2
			$this->m_caption = $this->m_dataitem->getString();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class SMWDataItem as the method getString() does only exist in the following sub-classes of SMWDataItem: SMWDIBlob, SMWDIError, SMWDIString. 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...
88 2
		}
89
90 2
		if ( $linker === null ) {
91
			return $this->m_caption;
92
		}
93
94
	//	return Html::rawElement(
0 ignored issues
show
Unused Code Comprehensibility introduced by
43% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
95
	//		'span',
96
	//		array(),
97
	//		'[' . $this->getTargetLink( urlencode( $this->m_caption ) ) . ' ' . $this->m_caption .']'
0 ignored issues
show
Unused Code Comprehensibility introduced by
40% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
98
	//	);
99
100 2
		$text = SpecialPage::getTitleFor( 'SearchByProperty' )->getPrefixedText();
101
102
		// This is a bit heavy handed ...
103 2
		return '[[' . $text . '/' . SMW_NOTIFICATIONS_TO_GROUP . '/' . rawurlencode( $this->m_caption ) . '|' . $this->m_caption . ']]';
104
	}
105
106
	/**
107
	 * @see StringValue::getShortHTMLText
108
	 */
109 3
	public function getShortHTMLText( $linker = null ) {
110
111 3
		if ( !$this->isValid() ) {
112 1
			return '';
113
		}
114
115 2
		if ( !$this->m_caption ) {
116
			$this->m_caption = $this->m_dataitem->getString();
0 ignored issues
show
Bug introduced by
It seems like you code against a specific sub-type and not the parent class SMWDataItem as the method getString() does only exist in the following sub-classes of SMWDataItem: SMWDIBlob, SMWDIError, SMWDIString. 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...
117
		}
118
119 2
		if ( $linker === null ) {
120
			return $this->m_caption;
121
		}
122
123 2
		$url = SpecialPage::getTitleFor( 'SearchByProperty' )->getLocalUrl(
124
			array(
125 2
				'property' => SMW_NOTIFICATIONS_TO_GROUP,
126 2
				'value' => $this->m_caption
127 2
			)
128 2
		);
129
130 2
		return Html::rawElement(
131 2
			'a',
132
			array(
133 2
				'href'   => $url,
134
			//	'target' => '_blank'
0 ignored issues
show
Unused Code Comprehensibility introduced by
50% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
135 2
			),
136 2
			$this->m_caption
137 2
		);
138
	}
139
140
	/**
141
	 * @see StringValue::getLongWikiText
142
	 */
143 2
	public function getLongWikiText( $linked = null ) {
144 2
		return $this->getShortWikiText( $linked );
145
	}
146
147
	/**
148
	 * @see StringValue::getLongHTMLText
149
	 */
150 2
	public function getLongHTMLText( $linker = null ) {
151 2
		return $this->getShortHTMLText( $linker );
152
	}
153
154 5
	private function isKnownNotificationsGroup( $value ) {
155
156 5
		$property = new DIProperty(
157
			PropertyRegistry::NOTIFICATIONS_TO_GROUP
158 5
		);
159
160 5
		$requestOptions = new RequestOptions();
161 5
		$requestOptions->limit = 1;
162
163
		// Is a known group?
164 5
		$propertyValues = ApplicationFactory::getInstance()->getStore()->getPropertySubjects(
165 5
			$property,
166 5
			new DIBlob( $value ),
167
			$requestOptions
168 5
		);
169
170 5
		return $propertyValues !== array();
171
	}
172
173 3
	private function hasUserContext() {
174 3
		return $this->getContextPage() !== null && $this->getContextPage()->getNamespace() === NS_USER;
175
	}
176
177
}
178