rob-revisited/ide/tests/ApiPlatformTest.php

418 lines
27 KiB
PHP

<?php
namespace JumPHP\Ide\Tests;
use JumPHP\Ide\ApiPlatform\ApiCommands;
use JumPHP\Ide\ApiPlatform\ApiReader;
use JumPHP\Ide\ApiPlatform\ApiWriter;
use JumPHP\Ide\ApiPlatform\Edit;
use JumPHP\Ide\ApiPlatform\RequestGenerator;
use JumPHP\Ide\ApiPlatform\Routes;
use JumPHP\Ide\ApiPlatform\StateClasses;
use JumPHP\Ide\HttpClient\Collections;
use PHPUnit\Framework\TestCase;
/**
* The API Platform window's core (ide/src/ApiPlatform): the attributes read from several shapes of code, the changes written
* (exact texts in tests/fixtures/api-platform-expected, every untouched line kept byte for byte), the property grid (groups,
* #[ApiProperty], #[ApiFilter]), State Providers / Processors, and the HTTP Client requests made from the resources with the
* rules of their regeneration (a file somebody edited is never overwritten).
*/
final class ApiPlatformTest extends TestCase
{
private const ROOT = __DIR__ . '/fixtures/api-platform';
private const EXPECTED = __DIR__ . '/fixtures/api-platform-expected';
private string $tmp = '';
protected function tearDown(): void
{
if ($this->tmp !== '') {
exec('rm -rf ' . escapeshellarg($this->tmp));
}
}
private static function source(string $name): string
{
return (string)file_get_contents(self::ROOT . "/src/$name.php");
}
private function assertSameAsExpected(string $file, string $actual): void
{
if (is_file(self::EXPECTED . '/.write')) {
@mkdir(dirname(self::EXPECTED . "/$file"), 0777, true);
file_put_contents(self::EXPECTED . "/$file", $actual);
}
self::assertFileExists(self::EXPECTED . "/$file");
self::assertSame((string)file_get_contents(self::EXPECTED . "/$file"), $actual, $file);
}
/** the project copied to a temporary folder, to write into */
private function project(): string
{
$this->tmp = sys_get_temp_dir() . '/api-platform-test-' . getmypid() . '-' . uniqid();
mkdir($this->tmp);
exec('cp -a ' . escapeshellarg(self::ROOT) . '/. ' . escapeshellarg($this->tmp));
return $this->tmp;
}
/** the lines of $after that are not in $before, in order */
private static function added(string $before, string $after): array
{
$b = explode("\n", $before);
return array_values(array_filter(explode("\n", $after), function (string $l) use (&$b) {
$i = array_search($l, $b, true);
if ($i === false) {
return true;
}
unset($b[$i]);
return false;
}));
}
// reading ---------------------------------------------------------------------------------------------------------
public function testTheProjectsClassesAreListedWithTheirApiResources(): void
{
$classes = array_column((new ApiReader(self::ROOT))->classes(), null, 'name');
self::assertSame(['Author', 'Book', 'BookInput', 'BookImporter', 'Genre'], array_slice(array_keys($classes + ['Genre' => 1]), 0, 5));
self::assertTrue($classes['Book']['api']);
self::assertSame(2, $classes['Book']['resources']);
self::assertSame('Livre', $classes['Book']['shortName']);
self::assertSame('entity', $classes['Author']['kind']);
self::assertSame('dto', $classes['BookInput']['kind']);
self::assertFalse($classes['BookImporter']['api']);
self::assertSame(['ApiPlatform\\State\\ProcessorInterface'], $classes['BookImporter']['implements']);
// the State tab's "used by": the state / input classes a class's resources name
self::assertSame([['App\\State\\BookImporter', 'processor (Post)']], $classes['BookInput']['uses']);
self::assertSame([], $classes['Author']['uses']);
}
public function testAnAttributeIsReadWithItsOperationsContextsAndExpressions(): void
{
$book = (new ApiReader(self::ROOT))->detail('App\Entity\Book');
$res = $book['resources'][0];
self::assertSame('Livre', $res['args']['shortName']);
self::assertSame(10, $res['args']['paginationItemsPerPage']);
self::assertSame(['groups' => ['book:write']], $res['args']['denormalizationContext']);
self::assertSame(['GetCollection', 'Get', 'Post'], array_column($res['operations'], 'type'));
self::assertSame("is_granted('ROLE_ADMIN')", $res['operations'][2]['args']['security']);
// the second attribute: a subresource with a Link
$sub = $book['resources'][1];
self::assertSame('/authors/{authorId}/books', $sub['args']['uriTemplate']);
self::assertSame('App\Entity\Author', $sub['args']['uriVariables']['authorId']['fromClass']);
self::assertSame('ApiPlatform\Metadata\Link', $sub['args']['uriVariables']['authorId']['@class']);
// a class-level filter
self::assertSame('order', $book['classFilters'][0]['key']);
self::assertSame(['title', 'pages'], $book['classFilters'][0]['properties']);
}
public function testNonConstantValuesAreKeptAsExpressions(): void
{
$code = "<?php\nnamespace App;\nuse ApiPlatform\\Metadata\\ApiResource;\n#[ApiResource(security: self::RULE, paginationItemsPerPage: 5 * 2, normalizationContext: ['groups' => [Book::READ]])]\nclass Book { const RULE = 'x'; }\n";
$res = (new ApiReader('/none'))->parse($code)[0]['resources'][0];
self::assertSame(['@expr' => 'self::RULE'], $res['args']['security']);
self::assertSame(['@expr' => '5 * 2'], $res['args']['paginationItemsPerPage']);
self::assertSame(['groups' => [['@expr' => 'Book::READ']]], $res['args']['normalizationContext']);
}
public function testPropertiesCarryTheirGroupsApiPropertyFiltersAndMapping(): void
{
$props = array_column((new ApiReader(self::ROOT))->detail('App\Entity\Book')['properties'], null, 'name');
self::assertSame(['book:read', 'book:write'], $props['title']['groups']);
self::assertNull($props['internalNote']['groups']);
self::assertSame('search', $props['title']['filters'][0]['key']);
self::assertSame('partial', $props['title']['filters'][0]['strategy']);
self::assertSame(['description' => 'Publication date'], $props['publishedAt']['apiProperty']);
self::assertTrue($props['id']['id']);
self::assertSame('relation', $props['author']['orm']['kind']);
self::assertSame('App\Entity\Genre', $props['genre']['orm']['enum']);
// a promoted constructor parameter of a DTO
$dto = array_column((new ApiReader(self::ROOT))->detail('App\Dto\BookInput')['properties'], null, 'name');
self::assertSame(['import'], $dto['isbn']['groups']);
self::assertTrue($dto['isbn']['promoted']);
self::assertSame('bool', $dto['overwrite']['phpType']);
}
public function testTheRoutesAreWorkedOutFromTheCode(): void
{
$reader = new ApiReader(self::ROOT);
$lines = fn (string $class) => array_map(fn ($r) => "{$r['method']} {$r['path']}", Routes::of($reader->detail($class), '/api', $reader->defaultOperations()));
self::assertSame(['GET /api/livres', 'GET /api/livres/{id}', 'POST /api/livres', 'GET /api/authors/{authorId}/books'], $lines('App\Entity\Book'));
self::assertSame(['GET /api/authors/{id}', 'GET /api/authors', 'POST /api/authors', 'PATCH /api/authors/{id}', 'DELETE /api/authors/{id}'], $lines('App\Entity\Author'));
self::assertSame(['POST /api/book_imports'], $lines('App\Dto\BookInput'));
// API Platform before 4 also made a PUT
$old = Routes::of($reader->detail('App\Entity\Author'), '/api', ['Get', 'GetCollection', 'Post', 'Put', 'Patch', 'Delete']);
self::assertContains('PUT /api/authors/{id}', array_map(fn ($r) => "{$r['method']} {$r['path']}", $old));
self::assertSame('book_reviews', Routes::segment('BookReview'));
self::assertSame('categories', Routes::segment('Category'));
self::assertSame('/api', $reader->prefix());
self::assertTrue($reader->jwt());
self::assertTrue(ApiReader::detect(self::ROOT));
self::assertFalse(ApiReader::detect(__DIR__ . '/fixtures/doctrine'));
}
// editing: the list helpers -------------------------------------------------------------------------------------
public function testArgumentsAreAddedAndRemovedInTheStyleOfTheList(): void
{
$one = new \JumPHP\Ide\Doctrine\PhpSource("<?php\n#[A(x: 1, y: 2)]\nclass C {}\n");
$locate = fn () => $one->class->attrGroups[0]->attrs[0];
Edit::setArg($one, $locate, 'z', '3');
Edit::setArg($one, $locate, 'x', null);
Edit::setArg($one, $locate, 'y', "['a' => 1]");
self::assertSame("<?php\n#[A(y: ['a' => 1], z: 3)]\nclass C {}\n", $one->code);
$none = new \JumPHP\Ide\Doctrine\PhpSource("<?php\n#[A]\nclass C {}\n");
Edit::setArg($none, fn () => $none->class->attrGroups[0]->attrs[0], 'x', '1');
self::assertSame("<?php\n#[A(x: 1)]\nclass C {}\n", $none->code);
$multi = new \JumPHP\Ide\Doctrine\PhpSource("<?php\n#[A(\n x: 1,\n y: 2\n)]\nclass C {}\n");
$m = fn () => $multi->class->attrGroups[0]->attrs[0];
Edit::setArg($multi, $m, 'z', '3');
Edit::setArg($multi, $m, 'x', null);
self::assertSame("<?php\n#[A(\n y: 2,\n z: 3\n)]\nclass C {}\n", $multi->code);
Edit::setArg($multi, $m, 'y', null);
Edit::setArg($multi, $m, 'z', null);
self::assertSame("<?php\n#[A()]\nclass C {}\n", $multi->code);
}
// editing: resources ------------------------------------------------------------------------------------------------
public function testAResourceIsEditedArgumentByArgumentAndItsOperationsAreMerged(): void
{
$before = self::source('Entity/Book');
$after = ApiWriter::resource($before, ['index' => 0,
'args' => ['paginationItemsPerPage' => 25, 'paginationClientEnabled' => true, 'security' => "is_granted('ROLE_USER')", 'order' => ['title' => 'ASC'],
'formats' => ['jsonld', 'json'], 'validationGroups' => ['create'], 'denormalizationGroups' => ['book:write', 'book:create'], 'shortName' => null],
'operations' => [
['index' => 0, 'type' => 'GetCollection', 'args' => ['name' => 'books_list']],
['index' => 2, 'type' => 'Put', 'args' => ['security' => null, 'input' => 'App\Dto\BookInput']],
['index' => null, 'type' => 'Patch', 'args' => ['security' => "is_granted('ROLE_ADMIN')", 'processor' => 'App\State\BookProcessor', 'validationGroups' => ['patch']]],
]]);
$this->assertSameAsExpected('book-resource-edited.php', $after);
self::assertSame($after, ApiWriter::resource($after, ['index' => 0, 'args' => ['paginationClientEnabled' => true]]), 'a value that did not change is not rewritten');
// the second attribute and the rest of the file are as they were
self::assertStringContainsString("uriVariables: ['authorId' => new Link(fromClass: Author::class, toProperty: 'author')],", $after);
self::assertStringContainsString("#[ApiFilter(OrderFilter::class, properties: ['title', 'pages'])]", $after);
}
public function testAResourceIsAddedAndRemoved(): void
{
$author = self::source('Entity/Author');
$added = ApiWriter::resource($author, ['index' => null, 'args' => ['uriTemplate' => '/books/{bookId}/authors', 'shortName' => 'BookAuthor',
'uriVariables' => ['bookId' => ['fromClass' => 'App\Entity\Book', 'fromProperty' => 'author']], 'security' => "is_granted('ROLE_ADMIN')"],
'operations' => [['type' => 'GetCollection', 'args' => []], ['type' => 'Get', 'args' => ['security' => null]]]]);
$this->assertSameAsExpected('author-resource-added.php', $added);
$removed = ApiWriter::resource($author, ['index' => 0, 'remove' => true]);
self::assertSame(self::lines($author, 1), self::lines($removed, 0));
self::assertStringNotContainsString('#[ApiResource]', $removed);
$plain = "<?php\n\nnamespace App\\Entity;\n\nclass Tag\n{\n}\n";
self::assertSame("<?php\n\nnamespace App\\Entity;\n\nuse ApiPlatform\\Metadata\\ApiResource;\n\n#[ApiResource]\nclass Tag\n{\n}\n", ApiWriter::resource($plain, ['index' => null]));
}
/** the line count: the text without the lines holding one of the given texts */
private static function lines(string $code, int $unused): string
{
return implode("\n", array_values(array_filter(explode("\n", $code), fn ($l) => !str_contains($l, 'ApiResource'))));
}
public function testOnlyTheTouchedArgumentChanges(): void
{
$before = self::source('Entity/Book');
$after = ApiWriter::resource($before, ['index' => 0, 'args' => ['paginationItemsPerPage' => 30]]);
self::assertSame([' paginationItemsPerPage: 30,'], self::added($before, $after));
self::assertSame([' paginationItemsPerPage: 10,'], self::added($after, $before));
// the groups of a context change inside its array, its other entries stay
$c = "<?php\nnamespace App;\nuse ApiPlatform\\Metadata\\ApiResource;\n#[ApiResource(normalizationContext: ['groups' => ['a'], 'enable_max_depth' => true])]\nclass X {}\n";
self::assertStringContainsString("normalizationContext: ['groups' => ['a', 'b'], 'enable_max_depth' => true]", ApiWriter::resource($c, ['index' => 0, 'args' => ['normalizationGroups' => ['a', 'b']]]));
self::assertStringContainsString("normalizationContext: ['enable_max_depth' => true]", ApiWriter::resource($c, ['index' => 0, 'args' => ['normalizationGroups' => null]]));
// a line that would get too long: one argument per line
self::assertStringContainsString("#[ApiResource(\n normalizationContext: ['groups' => ['a'], 'enable_max_depth' => true],\n denormalizationContext: ['groups' => ['w']],\n)]",
ApiWriter::resource($c, ['index' => 0, 'args' => ['denormalizationGroups' => ['w']]]));
$short = "<?php\nnamespace App;\nuse ApiPlatform\\Metadata\\ApiResource;\n#[ApiResource(shortName: 'A')]\nclass X {}\n";
self::assertStringContainsString("#[ApiResource(shortName: 'A', paginationItemsPerPage: 5)]", ApiWriter::resource($short, ['index' => 0, 'args' => ['paginationItemsPerPage' => 5]]));
}
public function testTheOperationsOfAResourceWithoutAnyAreWrittenAsAList(): void
{
$out = ApiWriter::resource(self::source('Entity/Author'), ['index' => 0, 'operations' => [['type' => 'GetCollection', 'args' => []], ['type' => 'Post', 'args' => ['security' => "is_granted('ROLE_USER')"]]]]);
self::assertStringContainsString("#[ApiResource(operations: [\n new GetCollection(),\n new Post(security: \"is_granted('ROLE_USER')\"),\n])]", str_replace(' ', ' ', $out));
self::assertStringContainsString("use ApiPlatform\\Metadata\\GetCollection;\nuse ApiPlatform\\Metadata\\Post;\n", $out);
}
// editing: properties -------------------------------------------------------------------------------------------------
public function testThePropertyGridEditsGroupsApiPropertyAndFilters(): void
{
$before = self::source('Entity/Book');
$after = ApiWriter::property($before, 'pages', ['groups' => ['book:read'], 'apiProperty' => ['description' => 'Number of pages', 'example' => '300', 'writable' => false],
'filters' => [['index' => 0, 'filter' => 'numeric']]]);
$after = ApiWriter::property($after, 'title', ['groups' => ['book:read', 'book:write', 'search'], 'filters' => [['index' => 0, 'filter' => 'search', 'strategy' => 'start'], ['index' => null, 'filter' => 'order']]]);
$after = ApiWriter::property($after, 'internalNote', ['groups' => ['book:write'], 'apiProperty' => ['readable' => false]]);
$after = ApiWriter::property($after, 'genre', ['filters' => []]);
$after = ApiWriter::property($after, 'publishedAt', ['apiProperty' => ['description' => null]]);
$this->assertSameAsExpected('book-properties-edited.php', $after);
}
public function testGroupsComeAndGoWithoutTouchingTheOtherLines(): void
{
$before = self::source('Entity/Book');
$after = ApiWriter::property($before, 'price', ['groups' => ['book:read', 'book:write']]);
self::assertSame([" #[Groups(['book:read', 'book:write'])]"], self::added($before, $after));
$none = ApiWriter::property($before, 'price', ['groups' => []]);
self::assertStringNotContainsString('private ?string $price = null;' . "\n" . ' #[Groups', $none);
self::assertSame(1, count(explode("\n", $before)) - count(explode("\n", $none)));
// a property without attributes gets the attribute above it, with its use line
$plain = "<?php\n\nnamespace App;\n\nclass T\n{\n private string \$a = '';\n}\n";
self::assertSame("<?php\n\nnamespace App;\n\nuse Symfony\\Component\\Serializer\\Attribute\\Groups;\n\nclass T\n{\n #[Groups(['t:read'])]\n private string \$a = '';\n}\n",
ApiWriter::property($plain, 'a', ['groups' => ['t:read']]));
self::assertSame("<?php\n\nnamespace App;\n\nuse Symfony\\Component\\Serializer\\Annotation\\Groups;\n\nclass T\n{\n #[Groups(['t:read'])]\n private string \$a = '';\n}\n",
ApiWriter::property($plain, 'a', ['groups' => ['t:read'], 'groupsClass' => 'Symfony\Component\Serializer\Annotation\Groups']));
}
public function testAPromotedConstructorParameterGetsItsAttributes(): void
{
$before = self::source('Dto/BookInput');
$after = ApiWriter::property($before, 'contactEmail', ['groups' => ['import', 'contact'], 'apiProperty' => ['description' => 'Who to write to']]);
$after = ApiWriter::property($after, 'isbn', ['groups' => ['import', 'isbn']]);
$this->assertSameAsExpected('book-input-edited.php', $after);
}
public function testAnUnknownPropertyIsRefused(): void
{
$this->expectException(\InvalidArgumentException::class);
ApiWriter::property(self::source('Entity/Book'), 'nope', ['groups' => ['a']]);
}
// State Providers / Processors ----------------------------------------------------------------------------------------
public function testStateClassesAreMadeFromTemplates(): void
{
$plain = StateClasses::make(self::ROOT, ['kind' => 'processor', 'name' => 'BookArchiver', 'resource' => 'App\Entity\Book']);
self::assertSame('src/State/BookArchiver.php', $plain['path']);
$this->assertSameAsExpected('state-processor.php', $plain['code']);
$this->assertSameAsExpected('state-provider.php', StateClasses::make(self::ROOT, ['kind' => 'provider', 'name' => 'BookProvider'])['code']);
$this->assertSameAsExpected('state-processor-decorating.php', StateClasses::make(self::ROOT, ['kind' => 'processor', 'name' => 'BookPersist', 'decorate' => true])['code']);
$this->assertSameAsExpected('state-provider-decorating.php', StateClasses::make(self::ROOT, ['kind' => 'provider', 'name' => 'BookReader', 'decorate' => true, 'namespace' => 'App\Provider'])['code']);
}
public function testAStateClassIsWiredToTheResourceOrAnOperation(): void
{
$handlers = [];
ApiCommands::register(function (string $name, callable $h) use (&$handlers) {
$handlers[$name] = $h;
}, self::ROOT, null);
$r = $handlers['apiplatform.state.new'](['kind' => 'processor', 'name' => 'BookArchiver', 'resource' => 'App\Entity\Book', 'wire' => ['resource' => 0, 'operation' => 2]]);
self::assertSame(['src/State/BookArchiver.php', 'src/Entity/Book.php'], array_column($r['changes'], 'path'));
self::assertStringContainsString("new Post(security: \"is_granted('ROLE_ADMIN')\", processor: BookArchiver::class),", $r['changes'][1]['after']);
self::assertStringContainsString("use App\\State\\BookArchiver;\n", $r['changes'][1]['after']);
$whole = $handlers['apiplatform.state.new'](['kind' => 'provider', 'name' => 'BookProvider', 'resource' => 'App\Entity\Author', 'wire' => ['resource' => 0]]);
self::assertStringContainsString("#[ApiResource(provider: AuthorProvider::class)]", str_replace('BookProvider', 'AuthorProvider', $whole['changes'][1]['after']));
}
// requests ------------------------------------------------------------------------------------------------------------
private function generator(string $root): RequestGenerator
{
return new RequestGenerator($root, new ApiReader($root), new Collections($root), ['App\Entity\Genre' => 'fantasy']);
}
public function testTheRequestsOfTheResourcesAreWrittenExactly(): void
{
$plan = $this->generator(self::ROOT)->plan();
$files = [];
foreach ($plan as $p) {
self::assertContains($p['action'], ['create', 'settings', 'env']);
$files["{$p['collection']}/{$p['path']}"] = $p['after'];
}
self::assertContains('Livre/list.http', array_keys($files));
self::assertContains('Livre/sub-authors-authorid-books/list.http', array_keys($files));
self::assertContains('BookInput/post-book-imports.http', array_keys($files));
foreach ($files as $path => $content) {
$this->assertSameAsExpected("requests/$path", $content);
}
// every request parses back as one request with the method and URL it was made for
$parsed = \JumPHP\Ide\HttpClient\HttpFile::parse($files['Livre/create.http']);
self::assertSame('POST', $parsed['method']);
self::assertSame('{{baseUrl}}/api/livres', $parsed['url']);
self::assertSame([['Accept', 'application/ld+json'], ['Content-Type', 'application/ld+json']], $parsed['headers']);
self::assertSame(['title' => 'example title', 'pages' => 1, 'publishedAt' => '2026-01-01T12:00:00+00:00', 'genre' => 'fantasy', 'author' => '/api/authors/1'], json_decode($parsed['body'], true));
self::assertStringContainsString('client.global.set("livreId"', $parsed['post']);
}
public function testTheBodyHoldsOnlyWhatTheOperationWrites(): void
{
$plan = array_column($this->generator(self::ROOT)->plan(['App\Entity\Book']), 'after', 'path');
$body = json_decode(\JumPHP\Ide\HttpClient\HttpFile::parse($plan['create.http'])['body'], true);
self::assertArrayNotHasKey('price', $body, 'book:read only');
self::assertArrayNotHasKey('internalNote', $body, 'no group');
self::assertArrayNotHasKey('id', $body);
$dto = json_decode(\JumPHP\Ide\HttpClient\HttpFile::parse(array_column($this->generator(self::ROOT)->plan(['App\Dto\BookInput']), 'after', 'path')['post-book-imports.http'])['body'], true);
self::assertSame(['isbn', 'contactEmail', 'overwrite'], array_keys($dto));
}
public function testRequestsAreRegeneratedOnlyWhileNobodyTouchedThem(): void
{
$root = $this->project();
$g = $this->generator($root);
$first = $g->plan(['App\Entity\Author']);
$written = $g->apply($first);
self::assertContains('Author/list.http', $written);
self::assertFileExists("$root/http-requests/Author/" . RequestGenerator::MANIFEST);
self::assertFileExists("$root/http-requests/Author/collection.json");
// nothing changed: nothing to do
self::assertSame(['unchanged'], array_values(array_unique(array_column($g->plan(['App\Entity\Author']), 'action'))));
// the class changes: the untouched files follow
$author = (string)file_get_contents("$root/src/Entity/Author.php");
file_put_contents("$root/src/Entity/Author.php", ApiWriter::property($author, 'name', ['apiProperty' => ['example' => 'Frank Herbert']]));
$plan = array_column($this->generator($root)->plan(['App\Entity\Author']), 'action', 'path');
self::assertSame('update', $plan['create.http']);
self::assertSame('update', $plan['update.http']);
self::assertSame('unchanged', $plan['list.http']);
// somebody edits a request in the HTTP Client: it stays, the new version goes beside it
$mine = "# @name My create\nPOST {{baseUrl}}/api/authors\n\n{\"name\": \"mine\"}\n";
file_put_contents("$root/http-requests/Author/create.http", $mine);
$plan = array_column($this->generator($root)->plan(['App\Entity\Author']), null, 'path');
self::assertSame('conflict', $plan['create.http']['action']);
self::assertSame('update', $plan['update.http']['action']);
$this->generator($root)->apply(array_values($plan));
self::assertSame($mine, file_get_contents("$root/http-requests/Author/create.http"));
self::assertStringContainsString('"name": "Frank Herbert"', (string)file_get_contents("$root/http-requests/Author/create.theirs.http"));
// and again: nothing new to say, the .theirs file is left alone
self::assertSame('keep', array_column($this->generator($root)->plan(['App\Entity\Author']), 'action', 'path')['create.http']);
// a file the tool never wrote, with a name it wants, is not overwritten either
unlink("$root/http-requests/Author/get.http");
file_put_contents("$root/http-requests/Author/get.http", "GET {{baseUrl}}/mine\n");
$this->generator($root)->apply($this->generator($root)->plan(['App\Entity\Author']));
self::assertSame("GET {{baseUrl}}/mine\n", file_get_contents("$root/http-requests/Author/get.http"));
}
public function testRequestsOfARemovedOperationGoUnlessEdited(): void
{
$root = $this->project();
$this->generator($root)->apply($this->generator($root)->plan(['App\Entity\Author']));
file_put_contents("$root/http-requests/Author/delete.http", "DELETE {{baseUrl}}/mine\n");
$author = (string)file_get_contents("$root/src/Entity/Author.php");
file_put_contents("$root/src/Entity/Author.php", ApiWriter::resource($author, ['index' => 0, 'operations' => [['index' => null, 'type' => 'GetCollection', 'args' => []], ['index' => null, 'type' => 'Post', 'args' => []]]]));
$plan = array_column($this->generator($root)->plan(['App\Entity\Author']), 'action', 'path');
self::assertSame('delete', $plan['get.http']);
self::assertSame('forget', $plan['delete.http']);
$this->generator($root)->apply($this->generator($root)->plan(['App\Entity\Author']));
self::assertFileDoesNotExist("$root/http-requests/Author/get.http");
self::assertSame("DELETE {{baseUrl}}/mine\n", file_get_contents("$root/http-requests/Author/delete.http"));
self::assertFileExists("$root/http-requests/Author/list.http");
}
public function testTheCollectionKeepsItsOwnSettingsAndEnvironmentVariables(): void
{
$root = $this->project();
$c = new Collections($root);
$id = $c->create('Author');
$c->saveEnvironments($id, ['local' => ['baseUrl' => 'https://api.test', 'authorId' => '42']]);
$before = (string)file_get_contents("$root/http-requests/Author/collection.json");
$this->generator($root)->apply($this->generator($root)->plan(['App\Entity\Author']));
self::assertSame($before, file_get_contents("$root/http-requests/Author/collection.json"));
$env = $c->environments('Author')['local'];
self::assertSame('https://api.test', $env['baseUrl']);
self::assertSame('42', $env['authorId']);
self::assertSame('change-me', $env['password'], 'the missing variables of the login are added');
}
}