/** * @param string|null $typeBase * @param string|null $typeLocal */ public function __construct($typeBase, $typeLocal) { Assert::parameterType('string|null', $typeBase, '$typeBase'); Assert::parameterType('string|null', $typeLocal, '$typeLocal'); $this->typeBase = $typeBase; $this->typeLocal = $typeLocal; }
public function merge(MergeableUpdate $update) { /** @var SiteStatsUpdate $update */ Assert::parameterType(__CLASS__, $update, '$update'); foreach (self::$counters as $field) { $this->{$field} += $update->{$field}; } }
/** * @param string $format One of the SnakFormatter::FORMAT_... constants. * @param SnakFormatter $formatter A formatter returning plain text. * @param callable $escapeCallback A callable taking plain text and returning escaped text. * * @throws ParameterTypeException */ public function __construct($format, SnakFormatter $formatter, $escapeCallback) { Assert::parameterType('string', $format, '$format'); Assert::parameterType('callable', $escapeCallback, '$escapeCallback'); $this->format = $format; $this->formatter = $formatter; $this->escapeCallback = $escapeCallback; }
public function setServices(HttpClient $httpClient, $siteMatrix, $outputFile) { Assert::parameterType('string', $siteMatrix, '$siteMatrix'); Assert::parameterType('string', $outputFile, '$outputFile'); $this->httpClient = $httpClient; $this->siteMatrix = $siteMatrix; $this->outputFile = $outputFile; }
public function __construct($sitesFile) { Assert::parameterType('string', $sitesFile, '$sitesFile'); if (!is_readable($sitesFile)) { throw new \InvalidArgumentException('$sitesFile ' . $sitesFile . ' is not readable'); } $this->sitesFile = $sitesFile; }
/** * Overrides the default new for categorization callback * This is intended for use while testing and will fail if MW_PHPUNIT_TEST is not defined. * * @param callable $callback * @see RecentChange::newForCategorization for callback signiture * * @throws MWException */ public function overrideNewForCategorizationCallback($callback) { if (!defined('MW_PHPUNIT_TEST')) { throw new MWException('Cannot override newForCategorization callback in operation.'); } Assert::parameterType('callable', $callback, '$callback'); $this->newForCategorizationCallback = $callback; }
/** * @param Term $matchedTerm * @param string $matchedTermType * @param EntityId $entityId * @param Term|null $displayLabel * @param Term|null $displayDescription */ public function __construct(Term $matchedTerm, $matchedTermType, EntityId $entityId, Term $displayLabel = null, Term $displayDescription = null) { Assert::parameterType('string', $matchedTermType, '$matchedTermType'); $this->matchedTerm = $matchedTerm; $this->matchedTermType = $matchedTermType; $this->entityId = $entityId; $this->displayLabel = $displayLabel; $this->displayDescription = $displayDescription; }
/** * Saves the change to a database table. * * @note Only supports Change objects that are derived from ChangeRow. * * @param Change $change * * @throws DBQueryError */ public function saveChange(Change $change) { Assert::parameterType('Wikibase\\ChangeRow', $change, '$change'); if ($change->getId() === null) { $this->insertChange($change); } else { $this->updateChange($change); } }
public function __construct(HttpClient $httpClient, $siteMatrixUrl, $outputFile) { Assert::parameterType('string', $siteMatrixUrl, '$siteMatrixUrl'); Assert::parameterType('string', $outputFile, '$outputFile'); $this->dumper = new Dumper(); $this->httpClient = $httpClient; $this->siteMatrixUrl = $siteMatrixUrl; $this->outputFile = $outputFile; }
/** * @param int $revisionId * @param string $mode One of the self::FROM_... constants. * * @return Change|null */ public function loadByRevisionId($revisionId, $mode = self::FROM_SLAVE) { Assert::parameterType('integer', $revisionId, '$revisionId'); $change = $this->loadChanges(array('change_revision_id' => $revisionId), array('LIMIT' => 1), __METHOD__, $mode === self::FROM_MASTER ? DB_MASTER : DB_SLAVE); if (isset($change[0])) { return $change[0]; } else { return null; } }
/** * @param string $format The output format generated by this formatter. All SnakFormatters * provided via $formattersBySnakType and $formattersByDataType must be safe for this * output format. This is checked by comparing the $format with what each SnakFormatter * returns from getFormat(). MIME parameters are ignored for this check, so FORMAT_HTML * is considered compatible with FORMAT_HTML_DIFF, etc. * @param PropertyDataTypeLookup $dataTypeLookup * @param SnakFormatter[] $formattersBySnakType An associative array mapping snak types * to SnakFormatter objects. If no formatter is defined for the a given snak type, * $formattersByDataType will be checked for a SnakFormatter for the snak's data type. * @param SnakFormatter[] $formattersByDataType An associative array mapping data types * to SnakFormatter objects. If no formatter is defined for the a given data type, * the "*" key in this array is checked for a default formatter. * * @throws InvalidArgumentException If any of the given formatters is incompatible * with $format. Formats are assumed to be represented by MIME types, * MIME parameters are ignored. */ public function __construct($format, PropertyDataTypeLookup $dataTypeLookup, array $formattersBySnakType, array $formattersByDataType) { Assert::parameterType('string', $format, '$format'); $this->assertFormatterArray($format, $formattersBySnakType); $this->assertFormatterArray($format, $formattersByDataType); $this->format = $format; $this->dataTypeLookup = $dataTypeLookup; $this->formattersBySnakType = $formattersBySnakType; $this->formattersByDataType = $formattersByDataType; }
/** * @param string $fileName File name, without the File: prefix. * * @return string|null The normalized file name or null if the page does not exist * @throws InvalidArgumentException */ public function lookupFileName($fileName) { Assert::parameterType('string', $fileName, '$pageName'); $cachedValue = $this->cache->get($this->getCacheKey($fileName)); if ($cachedValue !== false) { return $cachedValue; } $actualFileName = $this->doLookup($fileName); $this->cacheResult($fileName, $actualFileName); return $actualFileName; }
/** * Adds data type definitions. The new definitions are merged with the existing definitions. * If a data type in $dataTypeDefinitions was already defined, the old definition is not * replaced but the definitions are merged. * * @param array[] $dataTypeDefinitions An associative array mapping property data type ids * (with the prefix "PT:") and value types (with the prefix "VT:") to data type definitions. * Each data type definitions are associative arrays, refer to the class level documentation * for details. */ public function registerDataTypes(array $dataTypeDefinitions) { Assert::parameterElementType('array', $dataTypeDefinitions, '$dataTypeDefinitions'); foreach ($dataTypeDefinitions as $id => $def) { Assert::parameter(strpos($id, ':'), "\$dataTypeDefinitions[{$id}]", 'Key must start with a prefix like "PT:" or "VT:".'); if (isset($this->dataTypeDefinitions[$id])) { $this->dataTypeDefinitions[$id] = array_merge($this->dataTypeDefinitions[$id], $dataTypeDefinitions[$id]); } else { $this->dataTypeDefinitions[$id] = $dataTypeDefinitions[$id]; } } }
/** * @see SnakFormatter::format * * Formats the given Snak as an wikitext link to an authoritative resource. * The URL of that link is determined using a SnakUrlExpander. * If the snak could not be expanded into a URL, the identifier is returned as simple text. * * @param Snak $snak * * @throws ParameterTypeException if $snak is not a PropertyValueSnak, or if $snak->getDataValue() * does not return a StringValue. * @return string Wikitext */ public function formatSnak(Snak $snak) { Assert::parameterType('Wikibase\\DataModel\\Snak\\PropertyValueSnak', $snak, '$snak'); /** @var PropertyValueSnak $snak */ $id = $snak->getDataValue()->getValue(); $url = $this->urlExpander->expandUrl($snak); if ($url === null) { return wfEscapeWikiText($id); } else { return '[' . $this->escapeWikitextInUrl($url) . ' ' . wfEscapeWikiText($id) . ']'; } }
/** * Constructs a TitleValue. * * @note TitleValue expects a valid DB key; typically, a TitleValue is constructed either * from a database entry, or by a TitleParser. We could apply "some" normalization here, * such as substituting spaces by underscores, but that would encourage the use of * un-normalized text when constructing TitleValues. For constructing a TitleValue from * user input or external sources, use a TitleParser. * * @param int $namespace The namespace ID. This is not validated. * @param string $dbkey The page title in valid DBkey form. No normalization is applied. * @param string $fragment The fragment title. Use '' to represent the whole page. * No validation or normalization is applied. * * @throws InvalidArgumentException */ public function __construct($namespace, $dbkey, $fragment = '') { Assert::parameterType('integer', $namespace, '$namespace'); Assert::parameterType('string', $dbkey, '$dbkey'); Assert::parameterType('string', $fragment, '$fragment'); // Sanity check, no full validation or normalization applied here! Assert::parameter(!preg_match('/^_|[ \\r\\n\\t]|_$/', $dbkey), '$dbkey', 'invalid DB key'); Assert::parameter($dbkey !== '', '$dbkey', 'should not be empty'); $this->namespace = $namespace; $this->dbkey = $dbkey; $this->fragment = $fragment; }
/** * @see SnakUrlExpander::expandUrl * * @param PropertyValueSnak $snak * * @return string|null A URL or URI derived from the Snak, or null if no such URL * could be determined. */ public function expandUrl(PropertyValueSnak $snak) { $propertyId = $snak->getPropertyId(); $value = $snak->getDataValue(); Assert::parameterType('DataValues\\StringValue', $value, '$snak->getDataValue()'); $pattern = $this->infoProvider->getPropertyInfo($propertyId); if ($pattern === null) { return null; } $id = urlencode($value->getValue()); $url = str_replace('$1', $id, $pattern); return $url; }
/** * @param string $dataTypeId * * @throws OutOfBoundsException * @return ValueValidator[] */ public function getValidators($dataTypeId) { if (!isset($this->validatorBuilders[$dataTypeId])) { // NOTE: fail hard, to avoid bypassing validators if the data type is mistyped or some such. throw new OutOfBoundsException('No validators known for data type ' . $dataTypeId); } $validators = call_user_func($this->validatorBuilders[$dataTypeId]); Assert::postcondition(is_array($validators), "Factory function for {$dataTypeId} did not return an array of ValueValidator objects."); foreach ($validators as $v) { Assert::postcondition($v instanceof ValueValidator, "Factory function for {$dataTypeId} did not return an array of ValueValidator objects."); } return $validators; }
/** * @see SnakFormatter::format * * Formats the given Snak's value as a HTML link. * The URL of that link is determined using a SnakUrlExpander. * If the snak could not be expanded into a URL, the identifier is returned as simple text. * * @param Snak $snak * * @throws ParameterTypeException if $snak is not a PropertyValueSnak, or if $snak->getDataValue() * does not return a StringValue. * @return string HTML */ public function formatSnak(Snak $snak) { Assert::parameterType('Wikibase\\DataModel\\Snak\\PropertyValueSnak', $snak, '$snak'); /** @var PropertyValueSnak $snak */ $id = $snak->getDataValue()->getValue(); $url = $this->urlExpander->expandUrl($snak); $attr = array('class' => 'wb-external-id'); if ($url === null) { return Html::element('span', $attr, $id); } else { $attr['href'] = $url; return Html::element('a', $attr, $id); } }
/** * @param Title $title * @param array $params */ public function __construct(Title $title, array $params) { parent::__construct('wikibase-addUsagesForPage', $title, $params); Assert::parameter(isset($params['pageId']) && is_int($params['pageId']) && $params['pageId'] > 0, '$params["pageId"]', 'must be a positive integer'); Assert::parameter(isset($params['usages']) && is_array($params['usages']) && !empty($params['usages']), '$params["usages"]', 'must be a non-empty array'); Assert::parameter(isset($params['touched']) && is_string($params['touched']) && $params['touched'] !== '', '$params["touched"]', 'must be a timestamp string'); Assert::parameterElementType('array', $params['usages'], '$params["usages"]'); $this->pageId = $params['pageId']; $this->usages = $params['usages']; $this->touched = $params['touched']; $wikibaseClient = WikibaseClient::getDefaultInstance(); $usageUpdater = $wikibaseClient->getStore()->getUsageUpdater(); $idParser = $wikibaseClient->getEntityIdParser(); $this->overrideServices($usageUpdater, $idParser); }
/** * Re-uses existing Cache objects from $other. Cache objects are only re-used if the * registered factory function for both is the same. Cache config is not copied, * and only instances of caches defined on this instance with the same config * are copied. * * @see SalvageableService::salvage() * * @param SalvageableService $other The object to salvage state from. $other must have the * exact same type as $this. */ public function salvage(SalvageableService $other) { Assert::parameterType(self::class, $other, '$other'); /** @var ConfigFactory $other */ foreach ($other->factoryFunctions as $name => $otherFunc) { if (!isset($this->factoryFunctions[$name])) { continue; } // if the callback function is the same, salvage the Cache object // XXX: Closures are never equal! if (isset($other->configs[$name]) && $this->factoryFunctions[$name] == $otherFunc) { $this->configs[$name] = $other->configs[$name]; unset($other->configs[$name]); } } // disable $other $other->factoryFunctions = []; $other->configs = []; }
/** * Get a statistically unique 128-bit unsigned integer ID string. * The bits of the UID are prefixed with the time (down to the millisecond). * * These IDs are suitable as globally unique IDs, without any enforced uniqueness. * New rows almost always have higher UIDs, which makes B-TREE updates on INSERT fast. * They can also be stored as "DECIMAL(39) UNSIGNED" or BINARY(16) in MySQL. * * UID generation is serialized on each server (as the node ID is for the whole machine). * * @param int $base Specifies a base other than 10 * @return string Number * @throws MWException */ public static function newTimestampedUID128($base = 10) { Assert::parameterType('integer', $base, '$base'); Assert::parameter($base <= 36, '$base', 'must be <= 36'); Assert::parameter($base >= 2, '$base', 'must be >= 2'); $gen = self::singleton(); $time = $gen->getTimestampAndDelay('lockFile128', 16384, 1048576); return wfBaseConvert($gen->getTimestampedID128($time), 2, $base); }
public function testPostcondition_fail() { $this->setExpectedException('Wikimedia\\Assert\\PostconditionException'); Assert::postcondition(false, 'test'); }
/** * @param EntityChangeFactory $changeFactory * @param ChangeTransmitter[] $changeTransmitters */ public function __construct(EntityChangeFactory $changeFactory, array $changeTransmitters) { Assert::parameterElementType('Wikibase\\Repo\\Notifications\\ChangeTransmitter', $changeTransmitters, '$changeTransmitters'); $this->changeFactory = $changeFactory; $this->changeTransmitters = $changeTransmitters; }
/** * Get a statistically unique 128-bit unsigned integer ID string. * The bits of the UID are prefixed with the time (down to the millisecond). * * These IDs are suitable as globally unique IDs, without any enforced uniqueness. * New rows almost always have higher UIDs, which makes B-TREE updates on INSERT fast. * They can also be stored as "DECIMAL(39) UNSIGNED" or BINARY(16) in MySQL. * * UID generation is serialized on each server (as the node ID is for the whole machine). * * @param int $base Specifies a base other than 10 * @return string Number * @throws RuntimeException */ public static function newTimestampedUID128($base = 10) { Assert::parameterType('integer', $base, '$base'); Assert::parameter($base <= 36, '$base', 'must be <= 36'); Assert::parameter($base >= 2, '$base', 'must be >= 2'); $gen = self::singleton(); $info = $gen->getTimeAndDelay('lockFile128', 16384, 1048576, 1048576); $info['offsetCounter'] = $info['offsetCounter'] % 1048576; return Wikimedia\base_convert($gen->getTimestampedID128($info), 2, $base); }
/** * @param IContextSource $context * @param string $specialPageName * * @return ChangesListSpecialPageHooksHandler */ private static function newFromGlobalState(IContextSource $context, $specialPageName) { Assert::parameterType('string', $specialPageName, '$specialPageName'); $settings = WikibaseClient::getDefaultInstance()->getSettings(); return new self($context->getRequest(), $context->getUser(), LBFactory::singleton()->getMainLB(), $specialPageName, $settings->getSetting('showExternalRecentChanges')); }
/** * @param callable[] $factoryCallbacks Factory callback functions as returned by * DataTypeDefinitions::getRdfBuilderFactoryCallbacks(). Callbacks will be invoked * with the signature ($mode, RdfVocabulary, EntityMentionListener) and must * return a ValueSnakRdfBuilder (or null). */ public function __construct(array $factoryCallbacks) { Assert::parameterElementType('callable', $factoryCallbacks, '$factoryCallbacks'); $this->factoryCallbacks = $factoryCallbacks; }
public function merge(MergeableUpdate $update) { /** @var CdnCacheUpdate $update */ Assert::parameterType(__CLASS__, $update, '$update'); $this->urls = array_merge($this->urls, $update->urls); }
/** * Resize the maximum number of cache entries, removing older entries as needed * * @param int $maxKeys * @return void * @throws UnexpectedValueException */ public function resize($maxKeys) { Assert::parameterType('integer', $maxKeys, '$maxKeys'); Assert::parameter($maxKeys > 0, '$maxKeys', 'must be above zero'); $this->maxCacheKeys = $maxKeys; while (count($this->cache) > $this->maxCacheKeys) { reset($this->cache); $evictKey = key($this->cache); unset($this->cache[$evictKey]); unset($this->cacheTimes[$evictKey]); } }
/** * @param int $maxKeys Maximum number of entries allowed (min 1). * @throws Exception When $maxCacheKeys is not an int or not above zero. */ public function __construct($maxKeys) { Assert::parameterType('integer', $maxKeys, '$maxKeys'); Assert::parameter($maxKeys > 0, '$maxKeys', 'must be above zero'); $this->maxCacheKeys = $maxKeys; }
/** * @param PropertyInfoStore $infoStore * @param string $propertyInfoKey Name of the desired field in the PropertyInfo array. * Use one of the PropertyInfoStore::KEY_XXX constants. */ public function __construct(PropertyInfoStore $infoStore, $propertyInfoKey) { Assert::parameterType('string', $propertyInfoKey, '$propertyInfoKey'); $this->infoStore = $infoStore; $this->propertyInfoKey = $propertyInfoKey; }