MediaWiki master
benchmarkJsonCodec.php
Go to the documentation of this file.
1<?php
23
24// @codeCoverageIgnoreStart
25require_once __DIR__ . '/../includes/Benchmarker.php';
26// @codeCoverageIgnoreEnd
27
33 protected $defaultCount = 100;
34
35 public function __construct() {
36 parent::__construct();
37 $this->addDescription( 'Benchmarks JsonCodec.' );
38 $this->addOption(
39 'file',
40 'A json file, or a php file that returns a data structure. Default is config-schema.php',
41 false,
42 true
43 );
44 $this->addOption(
45 'assoc',
46 'Whether JSON objects should be represented as associative arrays when loading'
47 );
48 }
49
50 public function execute() {
51 $file = $this->getOption( 'file', MW_INSTALL_PATH . '/includes/config-schema.php' );
52 $data = $this->loadData( $file );
53 $bytes = json_encode( $data );
54
55 $codec = new JsonCodec();
56
57 $this->bench( [
58 "JsonCodec::serialize ($file)" => [
59 'function' => static function ( JsonCodec $codec, $data ) {
60 $codec->serialize( $data );
61 },
62 'args' => [ $codec, $data ]
63 ],
64 "JsonCodec::deserialize ($file)" => [
65 'function' => static function ( JsonCodec $codec, $bytes ) {
66 $codec->deserialize( $bytes );
67 },
68 'args' => [ $codec, $bytes ]
69 ],
70 "JsonCodec::detectNonSerializableData ($file)" => [
71 'function' => static function ( JsonCodec $codec, $data ) {
72 $codec->detectNonSerializableData( $data );
73 },
74 'args' => [ $codec, $data ]
75 ],
76 ] );
77 }
78
80 private function loadData( string $file ) {
81 if ( str_ends_with( $file, '.php' ) ) {
82 $data = include $file;
83 if ( !$data ) {
84 $this->fatalError( "Failed to load data from " . $file );
85 }
86 return $data;
87 }
88
89 $raw = $this->loadFile( $file );
90 $data = json_decode( $raw, $this->getOption( 'assoc', false ) );
91
92 if ( !$data ) {
93 $this->fatalError( "Failed to load data from " . $file );
94 }
95
96 return $data;
97 }
98}
99
100// @codeCoverageIgnoreStart
101$maintClass = BenchmarkJsonCodec::class;
102require_once RUN_MAINTENANCE_IF_MAIN;
103// @codeCoverageIgnoreEnd
execute()
Do the actual work.
__construct()
Default constructor.
deserialize( $json, ?string $expectedClass=null)
Restore an instance of simple type or JsonDeserializable subclass from the JSON serialization.
serialize( $value)
Encode $value as JSON with an intent to use JsonDeserializer::unserialize to decode it back.
detectNonSerializableData( $value, bool $expectDeserialize=false)
Checks if the $value is JSON-serializable (contains only scalar values) and returns a JSON-path to th...
Base class for benchmark scripts.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getOption( $name, $default=null)
Get an option, or return the default.
addDescription( $text)
Set the description text.