ExceptionConverter.php 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /*
  3. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  4. * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  5. * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  6. * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  7. * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  8. * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  9. * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  10. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  11. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  12. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  13. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  14. */
  15. namespace Alcaeus\MongoDbAdapter;
  16. use MongoDB\Driver\Exception;
  17. /**
  18. * @internal
  19. */
  20. class ExceptionConverter
  21. {
  22. /**
  23. * @param Exception\Exception $e
  24. * @param string $fallbackClass
  25. *
  26. * @return \MongoException
  27. */
  28. public static function toLegacy(Exception\Exception $e, $fallbackClass = 'MongoException')
  29. {
  30. $message = $e->getMessage();
  31. $code = $e->getCode();
  32. switch (get_class($e)) {
  33. case Exception\AuthenticationException::class:
  34. case Exception\ConnectionException::class:
  35. case Exception\ConnectionTimeoutException::class:
  36. case Exception\SSLConnectionException::class:
  37. $class = 'MongoConnectionException';
  38. break;
  39. case Exception\BulkWriteException::class:
  40. case Exception\WriteException::class:
  41. $writeResult = $e->getWriteResult();
  42. if ($writeResult) {
  43. $writeError = $writeResult->getWriteErrors()[0];
  44. $message = $writeError->getMessage();
  45. $code = $writeError->getCode();
  46. }
  47. switch ($code) {
  48. // see https://github.com/mongodb/mongo-php-driver-legacy/blob/ad3ed45739e9702ae48e53ddfadc482d9c4c7e1c/cursor_shared.c#L540
  49. case 11000:
  50. case 11001:
  51. case 12582:
  52. $class = 'MongoDuplicateKeyException';
  53. break;
  54. default:
  55. $class = 'MongoCursorException';
  56. }
  57. break;
  58. case Exception\ExecutionTimeoutException::class:
  59. $class = 'MongoExecutionTimeoutException';
  60. break;
  61. default:
  62. $class = $fallbackClass;
  63. }
  64. if (strpos($message, 'No suitable servers found') !== false) {
  65. return new \MongoConnectionException($message, $code, $e);
  66. }
  67. if ($message === "cannot use 'w' > 1 when a host is not replicated") {
  68. return new \MongoWriteConcernException($message, $code, $e);
  69. }
  70. return new $class($message, $code, $e);
  71. }
  72. }