MongoRegex.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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. */
  33. public function __construct($regex)
  34. {
  35. if ($regex instanceof Regex) {
  36. $this->regex = $regex->getPattern();
  37. $this->flags = $regex->getFlags();
  38. return;
  39. }
  40. if (! preg_match('#^/(.*)/([imxslu]*)$#', $regex, $matches)) {
  41. throw new MongoException('invalid regex', 9);
  42. }
  43. $this->regex = $matches[1];
  44. $this->flags = $matches[2];
  45. }
  46. /**
  47. * Returns a string representation of this regular expression.
  48. * @return string This regular expression in the form "/expr/flags".
  49. */
  50. public function __toString()
  51. {
  52. return '/' . $this->regex . '/' . $this->flags;
  53. }
  54. /**
  55. * Converts this MongoRegex to the new BSON Regex type
  56. *
  57. * @return Regex
  58. * @internal This method is not part of the ext-mongo API
  59. */
  60. public function toBSONType()
  61. {
  62. return new Regex($this->regex, $this->flags);
  63. }
  64. }