1<?php
2
3namespace Elastica\Exception;
4
5\trigger_error('Elastica\Exception\ElasticsearchException is deprecated. Use Elastica\Exception\ResponseException::getResponse::getFullError instead.', E_USER_DEPRECATED);
6
7/**
8 * Elasticsearch exception.
9 *
10 * @author Ian Babrou <ibobrik@gmail.com>
11 */
12class ElasticsearchException extends \Exception implements ExceptionInterface
13{
14    const REMOTE_TRANSPORT_EXCEPTION = 'RemoteTransportException';
15
16    /**
17     * @var string|null Elasticsearch exception name
18     */
19    private $_exception;
20
21    /**
22     * @var bool Whether exception was local to server node or remote
23     */
24    private $_isRemote = false;
25
26    /**
27     * @var array Error array
28     */
29    protected $_error = [];
30
31    /**
32     * Constructs elasticsearch exception.
33     *
34     * @param int    $code  Error code
35     * @param string $error Error message from elasticsearch
36     */
37    public function __construct(int $code, string $error)
38    {
39        $this->_parseError($error);
40        parent::__construct($error, $code);
41    }
42
43    /**
44     * Parse error message from elasticsearch.
45     *
46     * @param string $error Error message
47     */
48    protected function _parseError(string $error)
49    {
50        $errors = \explode(']; nested: ', $error);
51
52        if (1 === \count($errors)) {
53            $this->_exception = $this->_extractException($errors[0]);
54        } else {
55            if (self::REMOTE_TRANSPORT_EXCEPTION === $this->_extractException($errors[0])) {
56                $this->_isRemote = true;
57                $this->_exception = $this->_extractException($errors[1]);
58            } else {
59                $this->_exception = $this->_extractException($errors[0]);
60            }
61        }
62    }
63
64    /**
65     * Extract exception name from error response.
66     *
67     * @param string $error
68     *
69     * @return string|null
70     */
71    protected function _extractException(string $error)
72    {
73        if (\preg_match('/^(\w+)\[.*\]/', $error, $matches)) {
74            return $matches[1];
75        }
76
77        return null;
78    }
79
80    /**
81     * Returns elasticsearch exception name.
82     *
83     * @return string|null
84     */
85    public function getExceptionName()
86    {
87        return $this->_exception;
88    }
89
90    /**
91     * Returns whether exception was local to server node or remote.
92     *
93     * @return bool
94     */
95    public function isRemoteTransportException(): bool
96    {
97        return $this->_isRemote;
98    }
99
100    /**
101     * @return array Error array
102     */
103    public function getError(): array
104    {
105        return $this->_error;
106    }
107}
108