Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
80.00% covered (warning)
80.00%
56 / 70
50.00% covered (danger)
50.00%
2 / 4
CRAP
0.00% covered (danger)
0.00%
0 / 1
MhchemParser
80.00% covered (warning)
80.00%
56 / 70
50.00% covered (danger)
50.00%
2 / 4
28.61
0.00% covered (danger)
0.00%
0 / 1
 __construct
75.00% covered (warning)
75.00%
3 / 4
0.00% covered (danger)
0.00%
0 / 1
2.06
 getPatterns
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 toTex
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 go
79.37% covered (warning)
79.37%
50 / 63
0.00% covered (danger)
0.00%
0 / 1
23.51
1<?php
2/**
3 * Copyright (c) 2023 Johannes Stegmüller
4 *
5 * This file is a port of mhchemParser originally authored by Martin Hensel in javascript/typescript.
6 * The original license for this software can be found in the accompanying LICENSE.mhchemParser-ts.txt file.
7 */
8
9declare( strict_types = 1 );
10
11namespace MediaWiki\Extension\Math\WikiTexVC\Mhchem;
12
13use MediaWiki\Logger\LoggerFactory;
14use Psr\Log\LoggerInterface;
15use RuntimeException;
16
17/**
18 * Port of mhchemParser v4.2.2 by Martin Hensel (https://github.com/mhchem/mhchemParser)
19 * from typescript/javascript to PHP.
20 *
21 * This class contains the go (¸l.89 in mhchemParser.js)
22 * and the toTex function (l.39 of mhchemParser.js)
23 *
24 * For usage of mhchemParser in PHP instantiate this class and call toTex-Function.
25 *
26 * @author Johannes Stegmüller
27 * @license GPL-2.0-or-later
28 */
29class MhchemParser {
30
31    private MhchemPatterns $mhchemPatterns;
32
33    private MhchemStateMachines $mhchemStateMachines;
34
35    /** @var LoggerInterface */
36    private $logger;
37
38    /**
39     * Instantiate Mhchemparser, required for usage of "toTex" functionality
40     * @param bool $doLogging debug log internal state changes and input output for each state
41     */
42    public function __construct( bool $doLogging = false ) {
43        $this->mhchemPatterns = new MhchemPatterns();
44        $this->mhchemStateMachines = new MhchemStateMachines( $this );
45        if ( $doLogging ) {
46            $this->logger = LoggerFactory::getInstance( 'Math' );
47        }
48    }
49
50    public function getPatterns(): MhchemPatterns {
51        return $this->mhchemPatterns;
52    }
53
54    /**
55     * @param string $input input formula in tex eventually containing chemical environments or physical units
56     * @param string $type currently ce or pu (physical units)
57     * @param bool $optimizeMhchemForTexVC optimize the output of mhchem for usage in WikiTexVC, usually extra curlies
58     * surrounding parameters which specify dimensions
59     * @return string
60     */
61    public function toTex( $input, $type, bool $optimizeMhchemForTexVC = false ): string {
62        $parsed = $this->go( $input, $type );
63        return ( new MhchemTexify( $optimizeMhchemForTexVC ) )->go( $parsed, $type !== "tex" );
64    }
65
66    /**
67     * @param mixed|null $input
68     * @param mixed|null $stateMachine
69     */
70    public function go( $input, $stateMachine ): array {
71        if ( !MhchemUtil::issetJS( $input ) ) {
72            return [];
73        }
74
75        if ( !MhchemUtil::issetJS( $stateMachine ) ) {
76            $stateMachine = 'ce';
77        }
78
79        $state = '0';
80        $buffer = [];
81
82        $buffer['parenthesisLevel'] = 0;
83
84        if ( $input != null ) {
85            $input = preg_replace( "/\n+/", "", $input );
86            $input = preg_replace( "/[\x{2212}\x{2013}\x{2014}\x{2010}]/u", "-", $input );
87            $input = preg_replace( "/[\x{2026}]/u", "...", $input );
88        }
89
90        // Looks through _mhchemParser.transitions, to execute a matching action
91        // (recursive)actions
92        $lastInput = "";
93        $watchdog = 10;
94        $output = [];
95        while ( true ) {
96            if ( $lastInput !== $input ) {
97                $watchdog = 10;
98                $lastInput = $input;
99            } else {
100                $watchdog--;
101            }
102
103            // Find actions in transition table
104            $machine = $this->mhchemStateMachines->stateMachines[$stateMachine];
105            $t = $machine["transitions"][$state] ?? $machine["transitions"]['*'];
106
107            foreach ( $t as $i => $value ) {
108                $matches = $this->mhchemPatterns->match( $value["pattern"], $input ?? "" );
109
110                if ( $matches ) {
111                    if ( $this->logger ) {
112                        $this->logger->debug( "\n Match at: " . $i . "\tPattern: " . $value["pattern"] .
113                            "\t State-machine: " . $stateMachine );
114                    }
115
116                    // Execute actions
117                    $task = $value["task"];
118                    for ( $iA = 0, $iAMax = count( $task["action_"] ); $iA < $iAMax; $iA++ ) {
119                        $o = null;
120
121                        // Find and execute action
122                        if ( array_key_exists( $task["action_"][$iA]["type_"], $machine["actions"] ) ) {
123                            // tbd, setting null ok ?
124                            $option = $task["action_"][$iA]["option"] ?? null;
125                            if ( $this->logger ) {
126                                $this->logger->debug( "\n action: \t" . $task["action_"][$iA]["type_"] );
127                            }
128                            $o = $machine["actions"][$task["action_"][$iA]["type_"]]
129                                ( $buffer, $matches["match_"], $option );
130                        } elseif ( array_key_exists(
131                                $task["action_"][$iA]["type_"],
132                                $this->mhchemStateMachines->getGenericActions()
133                            )
134                        ) {
135                            $option = $task["action_"][$iA]["option"] ?? null;
136                            if ( $this->logger ) {
137                                $this->logger->debug( "\n action: \t" . $task["action_"][$iA]["type_"] );
138                            }
139                            $o = $this->mhchemStateMachines->getGenericActions()
140                                [$task["action_"][$iA]["type_"]]( $buffer, $matches["match_"], $option );
141                        } else {
142                            // Unexpected character
143                            throw new RuntimeException( "MhchemBugA: mhchem bug A. Please report. ("
144                                . $task->action_[$iA]->type_ . ")" );
145                        }
146
147                        // Add output
148                        MhchemUtil::concatArray( $output, $o );
149
150                        if ( $this->logger ) {
151                            $this->logger->debug( "\n State: " . $state );
152                            $this->logger->debug( "\n Buffer: " . json_encode( $buffer ) );
153                            $this->logger->debug( "\n Input: " . $input );
154                            $this->logger->debug( "\n Output: " . json_encode( $output ) );
155                            $this->logger->debug( "\n" );
156                        }
157
158                    }
159
160                    // Set next state,
161                    // Shorten input,
162                    // Continue with next character concatArray
163                    //   (= apply only one transition per position)
164                    $state = $task["nextState"] ?? $state;
165
166                    if ( $input != null && strlen( $input ) > 0 ) {
167                        if ( !array_key_exists( "revisit", $task ) ) {
168                            $input = $matches["remainder"];
169                        }
170                        if ( !array_key_exists( "toContinue", $task ) ) {
171                            // this breaks the two for loops
172                            break 1;
173                        }
174                    } else {
175                        return $output;
176                    }
177                }
178            }
179
180            // Prevent infinite loop
181            if ( $watchdog <= 0 ) {
182                // Unexpected character
183                throw new RunTimeException( "MhchemBugU: mhchem-PHP bug U. Please report." );
184            }
185        }
186    }
187}