MongoRegex.php 2.2 KB

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