summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/SemanticMediaWiki/src/Utils/ErrorCodeFormatter.php
blob: 354902adde9dbbb5c481e2a11bef15519f598e84 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
<?php

namespace SMW\Utils;

/**
 * Convenience method to retrieved stringified error codes.
 *
 * @license GNU GPL v2+
 * @since 2.5
 *
 * @author mwjames
 */
class ErrorCodeFormatter {

	/**
	 * @var array
	 */
	private static $constants = [];

	/**
	 * @var array
	 */
	private static $jsonErrors = [];

	/**
	 * @see http://php.net/manual/en/function.json-decode.php
	 * @since 2.5
	 *
	 * @param integer $errorCode
	 *
	 * @return string
	 */
	public static function getStringFromJsonErrorCode( $errorCode ) {

		if ( self::$constants === [] ) {
			self::$constants = get_defined_constants( true );
		}

		if ( isset( self::$constants["json"] ) && self::$jsonErrors === [] ) {
			foreach ( self::$constants["json"] as $name => $value ) {
				if ( !strncmp( $name, "JSON_ERROR_", 11 ) ) {
					self::$jsonErrors[$value] = $name;
				}
			}
		}

		return isset( self::$jsonErrors[$errorCode] ) ? self::$jsonErrors[$errorCode] : 'UNKNOWN';
	}

	/**
	 * @since 2.5
	 *
	 * @param integer $errorCode
	 *
	 * @return string
	 */
	public static function getMessageFromJsonErrorCode( $errorCode ) {

		$errorMessages = [
			JSON_ERROR_STATE_MISMATCH => 'Underflow or the modes mismatch, malformed JSON',
			JSON_ERROR_CTRL_CHAR => 'Unexpected control character found, possibly incorrectly encoded',
			JSON_ERROR_SYNTAX => 'Syntax error, malformed JSON',
			JSON_ERROR_UTF8   => 'Malformed UTF-8 characters, possibly incorrectly encoded',
			JSON_ERROR_DEPTH  => 'The maximum stack depth has been exceeded'
		];

		if ( !isset( $errorMessages[$errorCode] ) ) {
			return self::getStringFromJsonErrorCode( $errorCode );
		}

		return sprintf(
			"Expected a JSON compatible format but failed with '%s'",
			$errorMessages[$errorCode]
		);
	}

}