SpecialNewProperty::dataTypeExists()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 5
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Wikibase\Repo\Specials;
4
5
use OutputPage;
6
use Status;
7
use Wikibase\DataModel\Entity\EntityDocument;
8
use Wikibase\DataModel\Entity\Property;
9
use Wikibase\DataModel\Term\Term;
10
use Wikibase\Lib\Store\EntityNamespaceLookup;
11
use Wikibase\Lib\Store\EntityTitleLookup;
12
use Wikibase\Lib\Summary;
13
use Wikibase\Repo\CopyrightMessageBuilder;
14
use Wikibase\Repo\DataTypeSelector;
15
use Wikibase\Repo\EditEntity\MediawikiEditEntityFactory;
16
use Wikibase\Repo\Specials\HTMLForm\HTMLAliasesField;
17
use Wikibase\Repo\Specials\HTMLForm\HTMLContentLanguageField;
18
use Wikibase\Repo\Specials\HTMLForm\HTMLTrimmedTextField;
19
use Wikibase\Repo\Store\TermsCollisionDetector;
20
use Wikibase\Repo\SummaryFormatter;
21
use Wikibase\Repo\WikibaseRepo;
22
23
/**
24
 * Page for creating new Wikibase properties.
25
 *
26
 * @license GPL-2.0-or-later
27
 * @author John Erling Blad < [email protected] >
28
 */
29
class SpecialNewProperty extends SpecialNewEntity {
30
	const FIELD_LANG = 'lang';
31
	const FIELD_DATATYPE = 'datatype';
32
	const FIELD_LABEL = 'label';
33
	const FIELD_DESCRIPTION = 'description';
34
	const FIELD_ALIASES = 'aliases';
35
36
	/**
37
	 * @var TermsCollisionDetector
38
	 */
39
	private $termsCollisionDetector;
40
41
	public function __construct(
42
		SpecialPageCopyrightView $specialPageCopyrightView,
43
		EntityNamespaceLookup $entityNamespaceLookup,
44
		SummaryFormatter $summaryFormatter,
45
		EntityTitleLookup $entityTitleLookup,
46
		MediawikiEditEntityFactory $editEntityFactory,
47
		TermsCollisionDetector $termsCollisionDetector
48
	) {
49
		parent::__construct(
50
			'NewProperty',
51
			'property-create',
52
			$specialPageCopyrightView,
53
			$entityNamespaceLookup,
54
			$summaryFormatter,
55
			$entityTitleLookup,
56
			$editEntityFactory
57
		);
58
59
		$this->termsCollisionDetector = $termsCollisionDetector;
60
	}
61
62
	public static function factory(): self {
63
		$wikibaseRepo = WikibaseRepo::getDefaultInstance();
64
65
		$settings = $wikibaseRepo->getSettings();
66
		$copyrightView = new SpecialPageCopyrightView(
67
			new CopyrightMessageBuilder(),
68
			$settings->getSetting( 'dataRightsUrl' ),
69
			$settings->getSetting( 'dataRightsText' )
70
		);
71
72
		return new self(
73
			$copyrightView,
74
			$wikibaseRepo->getEntityNamespaceLookup(),
75
			$wikibaseRepo->getSummaryFormatter(),
76
			$wikibaseRepo->getEntityTitleLookup(),
77
			$wikibaseRepo->newEditEntityFactory(),
78
			$wikibaseRepo->getPropertyTermsCollisionDetector()
79
		);
80
	}
81
82
	/**
83
	 * @see SpecialNewEntity::doesWrites
84
	 *
85
	 * @return bool
86
	 */
87
	public function doesWrites() {
88
		return true;
89
	}
90
91
	/**
92
	 * @see SpecialNewEntity::createEntityFromFormData
93
	 *
94
	 * @param array $formData
95
	 *
96
	 * @return Property
97
	 */
98
	protected function createEntityFromFormData( array $formData ) {
99
		$languageCode = $formData[ self::FIELD_LANG ];
100
101
		$property = Property::newFromType( $formData[ self::FIELD_DATATYPE ] );
102
103
		$property->setLabel( $languageCode, $formData[ self::FIELD_LABEL ] );
104
		$property->setDescription( $languageCode, $formData[ self::FIELD_DESCRIPTION ] );
105
106
		$property->setAliases( $languageCode, $formData[ self::FIELD_ALIASES ] );
107
108
		return $property;
109
	}
110
111
	/**
112
	 * @param string $dataType
113
	 *
114
	 * @return bool
115
	 */
116
	private function dataTypeExists( $dataType ) {
117
		$dataTypeFactory = WikibaseRepo::getDefaultInstance()->getDataTypeFactory();
118
119
		return in_array( $dataType, $dataTypeFactory->getTypeIds() );
120
	}
121
122
	/**
123
	 * @see SpecialNewEntity::getFormFields()
124
	 *
125
	 * @return array[]
126
	 */
127
	protected function getFormFields() {
128
		$formFields = [
129
			self::FIELD_LANG => [
130
				'name' => self::FIELD_LANG,
131
				'class' => HTMLContentLanguageField::class,
132
				'id' => 'wb-newentity-language',
133
			],
134
			self::FIELD_LABEL => [
135
				'name' => self::FIELD_LABEL,
136
				'default' => $this->parts[0] ?? '',
137
				'class' => HTMLTrimmedTextField::class,
138
				'id' => 'wb-newentity-label',
139
				'placeholder-message' => 'wikibase-label-edit-placeholder',
140
				'label-message' => 'wikibase-newentity-label'
141
			],
142
			self::FIELD_DESCRIPTION => [
143
				'name' => self::FIELD_DESCRIPTION,
144
				'default' => $this->parts[1] ?? '',
145
				'class' => HTMLTrimmedTextField::class,
146
				'id' => 'wb-newentity-description',
147
				'placeholder-message' => 'wikibase-description-edit-placeholder',
148
				'label-message' => 'wikibase-newentity-description'
149
			],
150
			self::FIELD_ALIASES => [
151
				'name' => self::FIELD_ALIASES,
152
				'class' => HTMLAliasesField::class,
153
				'id' => 'wb-newentity-aliases',
154
			]
155
		];
156
157
		$dataTypeFactory = WikibaseRepo::getDefaultInstance()->getDataTypeFactory();
158
		$selector = new DataTypeSelector(
159
			$dataTypeFactory->getTypes(),
160
			$this->getLanguage()->getCode()
161
		);
162
163
		$options = [
164
			$this->msg( 'wikibase-newproperty-pick-data-type' )->text() => ''
165
		];
166
		$formFields[ self::FIELD_DATATYPE ] = [
167
			'name' => self::FIELD_DATATYPE,
168
			'type' => 'select',
169
			'default' => $this->parts[2] ?? '',
170
			'options' => array_merge( $options, $selector->getOptionsArray() ),
171
			'id' => 'wb-newproperty-datatype',
172
			'validation-callback' => function ( $dataType, $formData, $form ) {
0 ignored issues
show
Unused Code introduced by
The parameter $formData is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
Unused Code introduced by
The parameter $form is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
173
				if ( !$this->dataTypeExists( $dataType ) ) {
174
					return [ $this->msg( 'wikibase-newproperty-invalid-datatype' )->text() ];
175
				}
176
177
				return true;
178
			},
179
			'label-message' => 'wikibase-newproperty-datatype'
180
		];
181
182
		return $formFields;
0 ignored issues
show
Bug Best Practice introduced by
The return type of return $formFields; (array<string,array>) is incompatible with the return type declared by the abstract method Wikibase\Repo\Specials\S...ewEntity::getFormFields of type array[].

If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.

Let’s take a look at an example:

class Author {
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getName() {
        return $this->name;
    }
}

abstract class Post {
    public function getAuthor() {
        return 'Johannes';
    }
}

class BlogPost extends Post {
    public function getAuthor() {
        return new Author('Johannes');
    }
}

class ForumPost extends Post { /* ... */ }

function my_function(Post $post) {
    echo strtoupper($post->getAuthor());
}

Our function my_function expects a Post object, and outputs the author of the post. The base class Post returns a simple string and outputting a simple string will work just fine. However, the child class BlogPost which is a sub-type of Post instead decided to return an object, and is therefore violating the SOLID principles. If a BlogPost were passed to my_function, PHP would not complain, but ultimately fail when executing the strtoupper call in its body.

Loading history...
183
	}
184
185
	/**
186
	 * @inheritDoc
187
	 */
188
	protected function getLegend() {
189
		return $this->msg( 'wikibase-newproperty-fieldset' );
190
	}
191
192
	/**
193
	 * @see SpecialNewEntity::getWarnings
194
	 *
195
	 * @return string[]
196
	 */
197
	protected function getWarnings() {
198
		if ( $this->getUser()->isAnon() ) {
199
			return [
200
				$this->msg(
201
					'wikibase-anonymouseditwarning',
202
					$this->msg( 'wikibase-entity-property' )
203
				)->parse(),
204
			];
205
		}
206
207
		return [];
208
	}
209
210
	/**
211
	 * @param array $formData
212
	 *
213
	 * @return Status
214
	 */
215
	protected function validateFormData( array $formData ) {
216
		if ( $formData[ self::FIELD_LABEL ] == ''
217
			 && $formData[ self::FIELD_DESCRIPTION ] == ''
218
			 && $formData[ self::FIELD_ALIASES ] === []
219
		) {
220
			return Status::newFatal( 'wikibase-newproperty-insufficient-data' );
221
		}
222
223
		if ( $formData[ self::FIELD_LABEL ] !== '' &&
224
			$formData[ self::FIELD_LABEL ] === $formData[ self::FIELD_DESCRIPTION ]
225
		) {
226
			return Status::newFatal( 'wikibase-newproperty-same-label-and-description' );
227
		}
228
229
		$collidingPropertyId = $this->termsCollisionDetector->detectLabelCollision(
230
			$formData[ self::FIELD_LANG ],
231
			$formData[ self::FIELD_LABEL ]
232
		);
233
		if ( $collidingPropertyId !== null ) {
234
			return Status::newFatal(
235
				'wikibase-validator-label-conflict',
236
				$formData[ self::FIELD_LABEL ],
237
				$formData[ self::FIELD_LANG ],
238
				$collidingPropertyId
239
			);
240
		}
241
242
		return Status::newGood();
243
	}
244
245
	/**
246
	 * @param Property $property
247
	 *
248
	 * @return Summary
249
	 * @suppress PhanParamSignatureMismatch Uses intersection types
250
	 */
251
	protected function createSummary( EntityDocument $property ) {
252
		$uiLanguageCode = $this->getLanguage()->getCode();
253
254
		$summary = new Summary( 'wbeditentity', 'create' );
255
		$summary->setLanguage( $uiLanguageCode );
256
		/** @var Term|null $labelTerm */
257
		$labelTerm = $property->getLabels()->getIterator()->current();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Wikibase\DataModel\Entity\EntityDocument as the method getLabels() does only exist in the following implementations of said interface: Wikibase\DataModel\Entity\Item, Wikibase\DataModel\Entity\Property.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
258
		/** @var Term|null $descriptionTerm */
259
		$descriptionTerm = $property->getDescriptions()->getIterator()->current();
0 ignored issues
show
Bug introduced by
It seems like you code against a concrete implementation and not the interface Wikibase\DataModel\Entity\EntityDocument as the method getDescriptions() does only exist in the following implementations of said interface: Wikibase\DataModel\Entity\Item, Wikibase\DataModel\Entity\Property.

Let’s take a look at an example:

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

class MyUser implements 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 implementation 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 interface:

    interface User
    {
        /** @return string */
        public function getPassword();
    
        /** @return string */
        public function getDisplayName();
    }
    
Loading history...
260
		$summary->addAutoSummaryArgs(
261
			$labelTerm ? $labelTerm->getText() : '',
262
			$descriptionTerm ? $descriptionTerm->getText() : ''
263
		);
264
265
		return $summary;
266
	}
267
268
	protected function displayBeforeForm( OutputPage $output ) {
269
		parent::displayBeforeForm( $output );
270
		$output->addModules( 'wikibase.special.languageLabelDescriptionAliases' );
271
	}
272
273
	/**
274
	 * @inheritDoc
275
	 */
276
	protected function getEntityType() {
277
		return Property::ENTITY_TYPE;
278
	}
279
280
}
281