CompilesJsonPaths.php 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. <?php
  2. namespace Illuminate\Database\Concerns;
  3. use Illuminate\Support\Str;
  4. trait CompilesJsonPaths
  5. {
  6. /**
  7. * Split the given JSON selector into the field and the optional path and wrap them separately.
  8. *
  9. * @param string $column
  10. * @return array
  11. */
  12. protected function wrapJsonFieldAndPath($column)
  13. {
  14. $parts = explode('->', $column, 2);
  15. $field = $this->wrap($parts[0]);
  16. $path = count($parts) > 1 ? ', '.$this->wrapJsonPath($parts[1], '->') : '';
  17. return [$field, $path];
  18. }
  19. /**
  20. * Wrap the given JSON path.
  21. *
  22. * @param string $value
  23. * @param string $delimiter
  24. * @return string
  25. */
  26. protected function wrapJsonPath($value, $delimiter = '->')
  27. {
  28. $value = preg_replace("/([\\\\]+)?\\'/", "''", $value);
  29. $jsonPath = collect(explode($delimiter, $value))
  30. ->map(fn ($segment) => $this->wrapJsonPathSegment($segment))
  31. ->join('.');
  32. return "'$".(str_starts_with($jsonPath, '[') ? '' : '.').$jsonPath."'";
  33. }
  34. /**
  35. * Wrap the given JSON path segment.
  36. *
  37. * @param string $segment
  38. * @return string
  39. */
  40. protected function wrapJsonPathSegment($segment)
  41. {
  42. if (preg_match('/(\[[^\]]+\])+$/', $segment, $parts)) {
  43. $key = Str::beforeLast($segment, $parts[0]);
  44. if (! empty($key)) {
  45. return '"'.$key.'"'.$parts[0];
  46. }
  47. return $parts[0];
  48. }
  49. return '"'.$segment.'"';
  50. }
  51. }