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