Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
| 1 | <?php |
||
| 10 | use function trim; |
||
| 11 | |||
| 12 | use const LIBXML_ERR_ERROR; |
||
| 13 | use const LIBXML_ERR_FATAL; |
||
| 14 | use const LIBXML_ERR_WARNING; |
||
| 15 | |||
| 16 | /** |
||
| 17 | * Represents an exception thrown on XML load. |
||
| 18 | */ |
||
| 19 | class XmlLoadException extends Exception |
||
| 20 | { |
||
| 21 | private string $response; |
||
|
|
|||
| 22 | |||
| 23 | /** |
||
| 24 | * @param LibXMLError[] $errors |
||
| 25 | */ |
||
| 26 | public function __construct(string $response, array $errors) |
||
| 27 | { |
||
| 28 | parent::__construct(); |
||
| 29 | |||
| 30 | $this->response = $response; |
||
| 31 | $this->message = ''; |
||
| 32 | |||
| 33 | foreach ($errors as $error) { |
||
| 34 | $this->message .= $this->decodeXmlError($error, $response); |
||
| 35 | } |
||
| 36 | } |
||
| 37 | |||
| 38 | public function __toString(): string |
||
| 39 | { |
||
| 40 | return '[' . static::class . '] ' . $this->message . "\n" . |
||
| 41 | 'Response: ' . "\n" . |
||
| 42 | $this->response; |
||
| 43 | } |
||
| 44 | |||
| 45 | private function decodeXmlError(LibXMLError $error, string $xml): string |
||
| 46 | { |
||
| 47 | $return = $xml[$error->line - 1] . "\n"; |
||
| 48 | |||
| 49 | switch ($error->level) { |
||
| 50 | case LIBXML_ERR_WARNING: |
||
| 51 | $return .= sprintf('Warning %u: ', $error->code); |
||
| 52 | break; |
||
| 53 | |||
| 54 | case LIBXML_ERR_ERROR: |
||
| 55 | $return .= sprintf('Error %u: ', $error->code); |
||
| 56 | break; |
||
| 57 | |||
| 58 | case LIBXML_ERR_FATAL: |
||
| 59 | $return .= sprintf('Fatal Error %u: ', $error->code); |
||
| 60 | break; |
||
| 61 | } |
||
| 62 | |||
| 63 | $return .= sprintf("%s\n Line: %u\n Column: %u ", trim($error->message), $error->line, $error->column); |
||
| 64 | if ($error->file) { |
||
| 65 | $return .= sprintf("\n File: %s", $error->file); |
||
| 66 | } |
||
| 67 | |||
| 68 | return $return . "\n\n"; |
||
| 69 | } |
||
| 70 | } |
||
| 71 |