PocketMine-MP 5.16.1 git-585aee9386a787c95e73dd0a05ffca8329606b68
ItemIdMetaUpgradeSchemaUtils.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
24namespace pocketmine\data\bedrock\item\upgrade;
25
28use Symfony\Component\Filesystem\Path;
29use function gettype;
30use function is_object;
31use function json_decode;
32use function ksort;
33use const JSON_THROW_ON_ERROR;
34use const SORT_NUMERIC;
35
37
42 public static function loadSchemas(string $path, int $maxSchemaId) : array{
43 $iterator = new \RegexIterator(
44 new \FilesystemIterator(
45 $path,
46 \FilesystemIterator::KEY_AS_FILENAME | \FilesystemIterator::SKIP_DOTS
47 ),
48 '/^(\d{4}).*\.json$/',
49 \RegexIterator::GET_MATCH,
50 \RegexIterator::USE_KEY
51 );
52
53 $result = [];
54
56 foreach($iterator as $matches){
57 $filename = $matches[0];
58 $schemaId = (int) $matches[1];
59 if($schemaId > $maxSchemaId){
60 continue;
61 }
62
63 $fullPath = Path::join($path, $filename);
64
65 $raw = Filesystem::fileGetContents($fullPath);
66
67 try{
68 $schema = self::loadSchemaFromString($raw, $schemaId);
69 }catch(\RuntimeException $e){
70 throw new \RuntimeException("Loading schema file $fullPath: " . $e->getMessage(), 0, $e);
71 }
72
73 $result[$schemaId] = $schema;
74 }
75
76 ksort($result, SORT_NUMERIC);
77 return $result;
78 }
79
80 public static function loadSchemaFromString(string $raw, int $schemaId) : ItemIdMetaUpgradeSchema{
81 try{
82 $json = json_decode($raw, false, flags: JSON_THROW_ON_ERROR);
83 }catch(\JsonException $e){
84 throw new \RuntimeException($e->getMessage(), 0, $e);
85 }
86 if(!is_object($json)){
87 throw new \RuntimeException("Unexpected root type of schema file " . gettype($json) . ", expected object");
88 }
89
90 $jsonMapper = new \JsonMapper();
91 $jsonMapper->bExceptionOnMissingData = true;
92 $jsonMapper->bExceptionOnUndefinedProperty = true;
93 $jsonMapper->bStrictObjectTypeChecking = true;
94 try{
95 $model = $jsonMapper->map($json, new ItemIdMetaUpgradeSchemaModel());
96 }catch(\JsonMapper_Exception $e){
97 throw new \RuntimeException($e->getMessage(), 0, $e);
98 }
99
100 return new ItemIdMetaUpgradeSchema($model->renamedIds, $model->remappedMetas, $schemaId);
101 }
102}
static fileGetContents(string $fileName, bool $useIncludePath=false, $context=null, int $offset=0, ?int $length=null)
Definition: Filesystem.php:305