MongoRegex.php 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  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. if (class_exists('MongoRegex', false)) {
  16. return;
  17. }
  18. use Alcaeus\MongoDbAdapter\TypeInterface;
  19. use MongoDB\BSON\Regex;
  20. class MongoRegex implements TypeInterface
  21. {
  22. /**
  23. * @var string
  24. */
  25. public $regex;
  26. /**
  27. * @var string
  28. */
  29. public $flags;
  30. /**
  31. * Creates a new regular expression.
  32. *
  33. * @link http://php.net/manual/en/mongoregex.construct.php
  34. * @param string|Regex $regex Regular expression string of the form /expr/flags
  35. */
  36. public function __construct($regex)
  37. {
  38. if ($regex instanceof Regex) {
  39. $this->regex = $regex->getPattern();
  40. $this->flags = $regex->getFlags();
  41. return;
  42. }
  43. if (! preg_match('#^/(.*)/([imxslu]*)$#', $regex, $matches)) {
  44. throw new MongoException('invalid regex', 9);
  45. }
  46. $this->regex = $matches[1];
  47. $this->flags = $matches[2];
  48. }
  49. /**
  50. * Returns a string representation of this regular expression.
  51. * @return string This regular expression in the form "/expr/flags".
  52. */
  53. public function __toString()
  54. {
  55. return '/' . $this->regex . '/' . $this->flags;
  56. }
  57. /**
  58. * Converts this MongoRegex to the new BSON Regex type
  59. *
  60. * @return Regex
  61. * @internal This method is not part of the ext-mongo API
  62. */
  63. public function toBSONType()
  64. {
  65. return new Regex($this->regex, $this->flags);
  66. }
  67. }