|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * Error related utilities. |
| 5 | + * |
| 6 | + * @package SqlParser |
| 7 | + * @subpackage Utils |
| 8 | + */ |
| 9 | +namespace SqlParser\Utils; |
| 10 | + |
| 11 | +use SqlParser\Lexer; |
| 12 | +use SqlParser\Parser; |
| 13 | + |
| 14 | +/** |
| 15 | + * Error related utilities. |
| 16 | + * |
| 17 | + * @category Exceptions |
| 18 | + * @package SqlParser |
| 19 | + * @subpackage Utils |
| 20 | + * @author Dan Ungureanu <udan1107@gmail.com> |
| 21 | + * @license http://opensource.org/licenses/GPL-2.0 GNU Public License |
| 22 | + */ |
| 23 | +class Error |
| 24 | +{ |
| 25 | + |
| 26 | + /** |
| 27 | + * Gets the errors of a lexer and a parser. |
| 28 | + * |
| 29 | + * @param array $objs |
| 30 | + * |
| 31 | + * @return array Each element of the array represents an error. |
| 32 | + * `$err[0]` holds the error message. |
| 33 | + * `$err[1]` holds the error code. |
| 34 | + * `$err[2]` holds the string that caused the issue. |
| 35 | + * `$err[3]` holds the position of the string. |
| 36 | + * (i.e. `array($msg, $code, $str, $pos)`) |
| 37 | + */ |
| 38 | + public static function get($objs) |
| 39 | + { |
| 40 | + $ret = array(); |
| 41 | + |
| 42 | + foreach ($objs as $obj) { |
| 43 | + if ($obj instanceof Lexer) { |
| 44 | + foreach ($obj->errors as $err) { |
| 45 | + $ret[] = array( |
| 46 | + $err->getMessage(), |
| 47 | + $err->getCode(), |
| 48 | + $err->ch, |
| 49 | + $err->pos |
| 50 | + ); |
| 51 | + } |
| 52 | + } elseif ($obj instanceof Parser) { |
| 53 | + foreach ($obj->errors as $err) { |
| 54 | + $ret[] = array( |
| 55 | + $err->getMessage(), |
| 56 | + $err->getCode(), |
| 57 | + $err->token->token, |
| 58 | + $err->token->position |
| 59 | + ); |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | + |
| 64 | + return $ret; |
| 65 | + } |
| 66 | + |
| 67 | + /** |
| 68 | + * Formats the specified errors |
| 69 | + * |
| 70 | + * @param array $errors The errors to be formatted. |
| 71 | + * @param string $format The format of an error. |
| 72 | + * '$1$d' is replaced by the position of this error. |
| 73 | + * '$2$s' is replaced by the error message. |
| 74 | + * '$3$d' is replaced by the error code. |
| 75 | + * '$4$s' is replaced by the string that caused the |
| 76 | + * issue. |
| 77 | + * '$5$d' is replaced by the position of the string. |
| 78 | + * @return array |
| 79 | + */ |
| 80 | + public static function format( |
| 81 | + $errors, $format = '#%1$d: %2$s (near "%4$s" at position %5$d)' |
| 82 | + ) { |
| 83 | + $ret = array(); |
| 84 | + |
| 85 | + $i = 0; |
| 86 | + foreach ($errors as $key => $err) { |
| 87 | + $ret[$key] = sprintf( |
| 88 | + $format, ++$i, $err[0], $err[1], $err[2], $err[3] |
| 89 | + ); |
| 90 | + } |
| 91 | + |
| 92 | + return $ret; |
| 93 | + } |
| 94 | +} |
0 commit comments