• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

api-platform / core / 15775135891

20 Jun 2025 08:42AM UTC coverage: 22.065% (+0.2%) from 21.876%
15775135891

push

github

soyuka
Merge 4.1

13 of 103 new or added lines in 10 files covered. (12.62%)

868 existing lines in 35 files now uncovered.

11487 of 52060 relevant lines covered (22.06%)

21.72 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

0.0
/src/Laravel/Eloquent/State/LinksHandler.php
1
<?php
2

3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <dunglas@gmail.com>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11

12
declare(strict_types=1);
13

14
namespace ApiPlatform\Laravel\Eloquent\State;
15

16
use ApiPlatform\Metadata\Exception\OperationNotFoundException;
17
use ApiPlatform\Metadata\Exception\RuntimeException;
18
use ApiPlatform\Metadata\GraphQl\Operation;
19
use ApiPlatform\Metadata\GraphQl\Query;
20
use ApiPlatform\Metadata\HttpOperation;
21
use ApiPlatform\Metadata\Link;
22
use ApiPlatform\Metadata\Resource\Factory\ResourceMetadataCollectionFactoryInterface;
23
use Illuminate\Contracts\Foundation\Application;
24
use Illuminate\Database\Eloquent\Builder;
25
use Illuminate\Database\Eloquent\Model;
26
use Illuminate\Database\Eloquent\Relations\BelongsTo;
27
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
28
use Illuminate\Database\Eloquent\Relations\HasOneOrMany;
29
use Illuminate\Database\Eloquent\Relations\MorphTo;
30
use Illuminate\Database\Eloquent\Relations\Relation;
31

32
/**
33
 * @implements LinksHandlerInterface<Model>
34
 */
35
final class LinksHandler implements LinksHandlerInterface
36
{
37
    public function __construct(
38
        private readonly Application $application,
39
        private readonly ResourceMetadataCollectionFactoryInterface $resourceMetadataCollectionFactory,
40
    ) {
41
    }
×
42

43
    public function handleLinks(Builder $builder, array $uriVariables, array $context): Builder
44
    {
45
        $operation = $context['operation'];
×
46

47
        if ($operation instanceof HttpOperation) {
×
48
            foreach (array_reverse($operation->getUriVariables() ?? []) as $uriVariable => $link) {
×
49
                $builder = $this->buildQuery($builder, $link, $uriVariables[$uriVariable]);
×
50
            }
51

52
            return $builder;
×
53
        }
54

55
        if (!($linkClass = $context['linkClass'] ?? false)) {
×
56
            return $builder;
×
57
        }
58

59
        $newLink = null;
×
60
        $linkedOperation = null;
×
61
        $linkProperty = $context['linkProperty'] ?? null;
×
62

63
        try {
64
            $resourceMetadataCollection = $this->resourceMetadataCollectionFactory->create($linkClass);
×
65
            $linkedOperation = $resourceMetadataCollection->getOperation($operation->getName());
×
66
        } catch (OperationNotFoundException) {
×
67
            // Instead, we'll look for the first Query available.
68
            foreach ($resourceMetadataCollection as $resourceMetadata) {
×
69
                foreach ($resourceMetadata->getGraphQlOperations() as $op) {
×
70
                    if ($op instanceof Query) {
×
71
                        $linkedOperation = $op;
×
72
                    }
73
                }
74
            }
75
        }
76

77
        if (!$linkedOperation instanceof Operation) {
×
78
            return $builder;
×
79
        }
80

81
        $resourceClass = $builder->getModel()::class;
×
82
        foreach ($linkedOperation->getLinks() ?? [] as $link) {
×
83
            if ($resourceClass === $link->getToClass() && $linkProperty === $link->getFromProperty()) {
×
84
                $newLink = $link;
×
85
                break;
×
86
            }
87
        }
88

89
        if (!$newLink) {
×
90
            return $builder;
×
91
        }
92

93
        return $this->buildQuery($builder, $newLink, $uriVariables[$newLink->getIdentifiers()[0]]);
×
94
    }
95

96
    /**
97
     * @param Builder<Model> $builder
98
     *
99
     * @throws \Illuminate\Contracts\Container\BindingResolutionException
100
     *
101
     * @return Builder<Model> $builder
102
     */
103
    private function buildQuery(Builder $builder, Link $link, mixed $identifier): Builder
104
    {
105
        if ($to = $link->getToProperty()) {
×
106
            return $builder->where($builder->getModel()->{$to}()->getQualifiedForeignKeyName(), $identifier);
×
107
        }
108

109
        if ($from = $link->getFromProperty()) {
×
110
            /** @var Model $relatedInstance */
NEW
111
            $relatedInstance = $this->application->make($link->getFromClass());
×
NEW
112
            $relatedInstance->setAttribute($relatedInstance->getKeyName(), $identifier);
×
NEW
113
            $relatedInstance->exists = true;
×
114

115
            /** @var Relation<Model, Model, mixed> $relation */
NEW
116
            $relation = $relatedInstance->{$from}();
×
117

NEW
118
            if ($relation instanceof MorphTo) {
×
NEW
119
                throw new RuntimeException('Cannot query directly from a MorphTo relationship.');
×
120
            }
121

NEW
122
            if ($relation instanceof BelongsTo) {
×
123
                return $builder->getModel()
×
124
                    ->join(
×
NEW
125
                        $relation->getParent()->getTable(),
×
NEW
126
                        $relation->getParent()->getQualifiedKeyName(),
×
127
                        $identifier
×
NEW
128
                    );
×
129
            }
130

NEW
131
            if ($relation instanceof HasOneOrMany || $relation instanceof BelongsToMany) {
×
NEW
132
                return $relation->getQuery();
×
133
            }
134

NEW
135
            if (method_exists($relation, 'getQualifiedForeignKeyName')) {
×
NEW
136
                return $relation->getQuery()->where(
×
NEW
137
                    $relation->getQualifiedForeignKeyName(),
×
NEW
138
                    $identifier
×
NEW
139
                );
×
140
            }
141

NEW
142
            throw new RuntimeException(\sprintf('Unhandled or unknown relationship type: %s for property %s on %s', $relation::class, $from, $relatedInstance::class));
×
143
        }
144

NEW
145
        return $builder->where(
×
NEW
146
            $builder->getModel()->qualifyColumn($link->getIdentifiers()[0]),
×
NEW
147
            $identifier
×
NEW
148
        );
×
149
    }
150
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc