Skip to content

Commit

Permalink
Merge 18eb9a9 into db52758
Browse files Browse the repository at this point in the history
  • Loading branch information
soyuka committed Sep 23, 2021
2 parents db52758 + 18eb9a9 commit 6980fd1
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 16 deletions.
2 changes: 2 additions & 0 deletions src/Metadata/ApiResource.php
Expand Up @@ -22,6 +22,8 @@
#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::IS_REPEATABLE)]
final class ApiResource
{
use WithResourceTrait;

private $operations;
private $uriTemplate;
private $shortName;
Expand Down
24 changes: 8 additions & 16 deletions src/Metadata/WithResourceTrait.php
Expand Up @@ -28,22 +28,14 @@ public function withResource(ApiResource $resource): self
private function copyFrom($resource): self
{
$self = clone $this;
foreach (get_class_methods($resource) as $methodName) {
if (0 !== strpos($methodName, 'get')) {
continue;
}

if (!method_exists($self, $methodName)) {
continue;
}

$operationValue = $self->{$methodName}();
if (null !== $operationValue && [] !== $operationValue) {
continue;
}

if ($resource->{$methodName}() !== null) {
$self = $self->{'with'.substr($methodName, 3)}($resource->{$methodName}());
foreach (get_class_methods($resource) as $method) {
if (
method_exists($self, $method) &&
preg_match('/^(?:get|is|can)(.*)/', $method, $matches) &&
null === $self->{$method}() &&
null !== $val = $resource->{$method}()
) {
$self = $self->{"with{$matches[1]}"}($val);
}
}

Expand Down
29 changes: 29 additions & 0 deletions tests/Metadata/Resource/OperationTest.php
@@ -0,0 +1,29 @@
<?php

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

declare(strict_types=1);

namespace ApiPlatform\Tests\Metadata\Resource;

use ApiPlatform\Metadata\Operation;
use PHPUnit\Framework\TestCase;

final class OperationTest extends TestCase
{
public function testWithResourceTrait()
{
$operation = (new Operation())->withOperation((new Operation())->withShortName('test')->withRead(false)->withCollection(true));

$this->assertEquals($operation->getShortName(), 'test');
$this->assertEquals($operation->canRead(), false);
$this->assertEquals($operation->isCollection(), true);
}
}

0 comments on commit 6980fd1

Please sign in to comment.