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