Debian Codegraph @

vendor/wikimedia/parsoid/src/Wt2Html/TT/TraceProxy.php

raw
1 <?php
2
3 declare( strict_types = 1 );
4
5 namespace Wikimedia\Parsoid\Wt2Html\TT;
6
7 use Wikimedia\Parsoid\Tokens\EOFTk;
8 use Wikimedia\Parsoid\Tokens\NlTk;
9 use Wikimedia\Parsoid\Tokens\Token;
10 use Wikimedia\Parsoid\Utils\PHPUtils;
11 use Wikimedia\Parsoid\Wt2Html\TokenTransformManager;
12
13 class TraceProxy extends TokenHandler {
14 private $traceType;
15 private $handler;
16 private $name;
17
18 public function __construct( TokenTransformManager $manager, array $options,
19 string $traceType, TokenHandler $handler
20 ) {
21 parent::__construct( $manager, $options );
22 $this->traceType = $traceType;
23 $this->handler = $handler;
24 $this->name = ( new \ReflectionClass( $handler ) )->getShortName();
25 // Copy onAnyEnabled for TraceProxy::process() to read
26 $this->onAnyEnabled = $this->handler->onAnyEnabled;
27 }
28
29 /**
30 * @param string $func
31 * @param string|Token $token
32 * @return TokenHandlerResult|null
33 */
34 private function traceEvent( string $func, $token ) {
35 $this->env->log(
36 $this->traceType, $this->pipelineId,
37 function () {
38 return str_pad( $this->name, 23, ' ', STR_PAD_LEFT ) . "|";
39 },
40 static function () use ( $token ) {
41 return PHPUtils::jsonEncode( $token );
42 }
43 );
44
45 $profile = $this->manager->profile;
46 if ( $profile ) {
47 $s = microtime( true );
48 $res = $this->handler->$func( $token );
49 $t = (int)( ( microtime( true ) - $s ) * 1000 );
50 $traceName = "{$this->name}::$func";
51 $profile->bumpTimeUse( $traceName, $t, "TT" );
52 $profile->bumpCount( $traceName );
53 $this->manager->tokenTimes += $t;
54 } else {
55 $res = $this->handler->$func( $token );
56 }
57 // Copy onAnyEnabled for TraceProxy::process() to read
58 $this->onAnyEnabled = $this->handler->onAnyEnabled;
59 return $res;
60 }
61
62 public function onEnd( EOFTk $token ): ?TokenHandlerResult {
63 return $this->traceEvent( 'onEnd', $token );
64 }
65
66 public function onNewline( NlTk $token ): ?TokenHandlerResult {
67 return $this->traceEvent( 'onNewline', $token );
68 }
69
70 public function onTag( Token $token ): ?TokenHandlerResult {
71 return $this->traceEvent( 'onTag', $token );
72 }
73
74 /**
75 * @param string|Token $token
76 * @return TokenHandlerResult|null
77 */
78 public function onAny( $token ): ?TokenHandlerResult {
79 return $this->traceEvent( 'onAny', $token );
80 }
81
82 public function resetState( array $options ): void {
83 $this->handler->resetState( $options );
84 // Copy onAnyEnabled for TraceProxy::process() to read
85 $this->onAnyEnabled = $this->handler->onAnyEnabled;
86 }
87
88 public function setPipelineId( int $id ): void {
89 $this->pipelineId = $id;
90 $this->handler->setPipelineId( $id );
91 }
92
93 public function isDisabled(): bool {
94 return $this->handler->isDisabled();
95 }
96 }