MediaWiki master
benchmarkJsonCodec.php
Go to the documentation of this file.
1<?php
9
10// @codeCoverageIgnoreStart
11require_once __DIR__ . '/../includes/Benchmarker.php';
12// @codeCoverageIgnoreEnd
13
19 protected $defaultCount = 100;
20
21 public function __construct() {
22 parent::__construct();
23 $this->addDescription( 'Benchmarks JsonCodec.' );
24 $this->addOption(
25 'file',
26 'A json file, or a php file that returns a data structure. Default is config-schema.php',
27 false,
28 true
29 );
30 $this->addOption(
31 'assoc',
32 'Whether JSON objects should be represented as associative arrays when loading'
33 );
34 }
35
36 public function execute() {
37 $file = $this->getOption( 'file', MW_INSTALL_PATH . '/includes/config-schema.php' );
38 $data = $this->loadData( $file );
39 $bytes = json_encode( $data );
40
41 $codec = new JsonCodec();
42
43 $this->bench( [
44 "JsonCodec::serialize ($file)" => [
45 'function' => static function ( JsonCodec $codec, $data ) {
46 $codec->serialize( $data );
47 },
48 'args' => [ $codec, $data ]
49 ],
50 "JsonCodec::deserialize ($file)" => [
51 'function' => static function ( JsonCodec $codec, $bytes ) {
52 $codec->deserialize( $bytes );
53 },
54 'args' => [ $codec, $bytes ]
55 ],
56 "JsonCodec::detectNonSerializableData ($file)" => [
57 'function' => static function ( JsonCodec $codec, $data ) {
58 $codec->detectNonSerializableData( $data );
59 },
60 'args' => [ $codec, $data ]
61 ],
62 ] );
63 }
64
66 private function loadData( string $file ) {
67 if ( str_ends_with( $file, '.php' ) ) {
68 $data = include $file;
69 if ( !$data ) {
70 $this->fatalError( "Failed to load data from " . $file );
71 }
72 return $data;
73 }
74
75 $raw = $this->loadFile( $file );
76 $data = json_decode( $raw, $this->getOption( 'assoc', false ) );
77
78 if ( !$data ) {
79 $this->fatalError( "Failed to load data from " . $file );
80 }
81
82 return $data;
83 }
84}
85
86// @codeCoverageIgnoreStart
87$maintClass = BenchmarkJsonCodec::class;
88require_once RUN_MAINTENANCE_IF_MAIN;
89// @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....
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.