Validate Wikidata IDs before attempting to fetch from Wikidata

Close #8
This commit is contained in:
Joshua Ramon Enslin 2022-03-05 13:58:18 +01:00
parent b1bd14bc56
commit 6347de2635
Signed by: jrenslin
GPG Key ID: 46016F84501B70AE

View File

@ -86,6 +86,26 @@ final class NodaWikidataFetcher {
/** @var MDMysqli */
private MDMysqli $_mysqli_noda;
/**
* Validates a Wikidata ID. A Wikidata ID must start with a capital Q and be
* numeric otherwise.
*
* @param string $wikidata_id Input ID to validate.
*
* @return void
*/
public static function validateWikidataId(string $wikidata_id):void {
if (substr($wikidata_id, 0, 1) !== 'Q') {
throw new MDgenericInvalidInputsException("Wikidata IDs start with Q");
}
if (!is_numeric(substr($wikidata_id, 1))) {
throw new MDgenericInvalidInputsException("Wikidata IDs are numeric following the Q");
}
}
/**
* Attempts to fetch a Wikidata ID from a provided URL.
*
@ -714,6 +734,8 @@ final class NodaWikidataFetcher {
*/
public function retrievePersinstInfoFromWikidataID(string $lang, string $wikidata_id, int $persinst_id, string $erfasst_von) {
self::validateWikidataId($wikidata_id);
$data = json_decode(MD_STD::runCurl("https://www.wikidata.org/wiki/Special:EntityData/" . $wikidata_id . ".json", 10000), true);
if ($data === null) {
throw new MDhttpFailedException("Failed fetching from Wikidata. Try again later.");
@ -1054,6 +1076,8 @@ final class NodaWikidataFetcher {
*/
public function retrievePlaceInfoFromWikidataID(string $lang, string $wikidata_id, int $onum, string $erfasst_von) {
self::validateWikidataId($wikidata_id);
$data = MD_STD::runCurl("https://www.wikidata.org/wiki/Special:EntityData/" . urlencode($wikidata_id) . ".json", 10000);
if (!$data = json_decode($data, true)) {
throw new MDhttpFailedException("Failed fetching from Wikidata. Try again later.");
@ -1455,6 +1479,8 @@ final class NodaWikidataFetcher {
*/
public function retrieveTagInfoFromWikidataID(string $lang, string $wikidata_id, int $tag_id, string $erfasst_von) {
self::validateWikidataId($wikidata_id);
$data = MD_STD::runCurl("https://www.wikidata.org/wiki/Special:EntityData/" . $wikidata_id . ".json", 10000);
$data = json_decode($data, true);
if ($data === null) {