Skip to content

Commit

Permalink
Allow the use of propertyPath (#1293)
Browse files Browse the repository at this point in the history
Allow the use of propertyPath
  • Loading branch information
VincentLanglet authored Jun 28, 2022
1 parent 9c6ebfc commit 44fdfbc
Show file tree
Hide file tree
Showing 9 changed files with 140 additions and 16 deletions.
15 changes: 10 additions & 5 deletions src/Form/Type/VichFileType.php
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ protected function buildDeleteField(FormBuilderInterface $builder, array $option
$object = $parent->getData();

// no object or no uploaded file: no delete button
if (null === $object || null === $this->storage->resolveUri($object, $form->getName())) {
if (null === $object || null === $this->storage->resolveUri($object, $this->getFieldName($form))) {
return;
}

Expand All @@ -141,7 +141,7 @@ protected function buildDeleteField(FormBuilderInterface $builder, array $option
return;
}

$this->handler->remove($object, $form->getName());
$this->handler->remove($object, $this->getFieldName($form));
});
}

Expand All @@ -167,6 +167,11 @@ public function getBlockPrefix(): string
return 'vich_file';
}

final protected function getFieldName(FormInterface $form): string
{
return $form->getConfig()->getOption('property_path') ?? $form->getName();
}

/**
* @param bool|callable $uriOption
*
Expand All @@ -175,11 +180,11 @@ public function getBlockPrefix(): string
protected function resolveUriOption($uriOption, object $object, FormInterface $form)
{
if (true === $uriOption) {
return $this->storage->resolveUri($object, $form->getName());
return $this->storage->resolveUri($object, $this->getFieldName($form));
}

if (\is_callable($uriOption)) {
return $uriOption($object, $this->storage->resolveUri($object, $form->getName()));
return $uriOption($object, $this->storage->resolveUri($object, $this->getFieldName($form)));
}

return $uriOption;
Expand All @@ -191,7 +196,7 @@ protected function resolveUriOption($uriOption, object $object, FormInterface $f
protected function resolveDownloadLabel($downloadLabel, object $object, FormInterface $form): array
{
if (true === $downloadLabel) {
$mapping = $this->factory->fromField($object, $form->getName());
$mapping = $this->factory->fromField($object, $this->getFieldName($form));

return ['download_label' => $mapping->readProperty($object, 'originalName'), 'translation_domain' => false];
}
Expand Down
6 changes: 3 additions & 3 deletions src/Form/Type/VichImageType.php
Original file line number Diff line number Diff line change
Expand Up @@ -111,13 +111,13 @@ public function getBlockPrefix(): string
private function resolvePath(int $storageResolveMethod, object $object, FormInterface $form): ?string
{
if (static::STORAGE_RESOLVE_URI === $storageResolveMethod) {
return $this->storage->resolveUri($object, $form->getName());
return $this->storage->resolveUri($object, $this->getFieldName($form));
}
if (static::STORAGE_RESOLVE_PATH_ABSOLUTE === $storageResolveMethod) {
return $this->storage->resolvePath($object, $form->getName());
return $this->storage->resolvePath($object, $this->getFieldName($form));
}
if (static::STORAGE_RESOLVE_PATH_RELATIVE === $storageResolveMethod) {
return $this->storage->resolvePath($object, $form->getName(), null, true);
return $this->storage->resolvePath($object, $this->getFieldName($form), null, true);
}

return null;
Expand Down
20 changes: 20 additions & 0 deletions tests/Fixtures/App/app/config/routing.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,37 @@ upload:
methods: GET
defaults: { _controller: Vich\TestBundle\Controller\DefaultController::uploadAction }

upload_with_property_path:
path: /upload_with_property_path/{formType}
methods: GET
defaults: { _controller: Vich\TestBundle\Controller\DefaultController::uploadWithPropertyPathAction }

upload_send:
path: /upload/{formType}/send
methods: POST
defaults: { _controller: Vich\TestBundle\Controller\DefaultController::submitAction }

upload_send_with_property_path:
path: /upload_with_property_path/{formType}/send
methods: POST
defaults: { _controller: Vich\TestBundle\Controller\DefaultController::submitWithPropertyPathAction }

upload_edit:
path: /upload/{formType}/send/{imageId}
methods: POST
defaults: { _controller: Vich\TestBundle\Controller\DefaultController::submitAction }

upload_edit_with_property_path:
path: /upload_with_property_path/{formType}/send/{imageId}
methods: POST
defaults: { _controller: Vich\TestBundle\Controller\DefaultController::submitWithPropertyPathAction }

view:
path: /upload/{imageId}/{formType}
methods: GET
defaults: { _controller: Vich\TestBundle\Controller\DefaultController::editAction }

view_with_property_path:
path: /upload_with_property_path/{imageId}/{formType}
methods: GET
defaults: { _controller: Vich\TestBundle\Controller\DefaultController::editWithPropertyPathAction }
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{% extends 'base.html.twig' %}

{% block body %}
{{ form(form, {'action': path('upload_edit_with_property_path', {'formType': formType, 'imageId': imageId}), 'method': 'POST'}) }}
{% endblock %}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{% extends 'base.html.twig' %}

{% block body %}
{{ form(form, {'action': path('upload_send_with_property_path', {'formType': formType}), 'method': 'POST'}) }}
{% endblock %}
54 changes: 54 additions & 0 deletions tests/Fixtures/TestBundle/src/Controller/DefaultController.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,16 @@ public function uploadAction(string $formType): Response
]);
}

public function uploadWithPropertyPathAction(string $formType): Response
{
$form = $this->getFormWithPropertyPath($this->getImage());

return $this->render('default/upload_with_property_path.html.twig', [
'formType' => $formType,
'form' => $form->createView(),
]);
}

public function editAction(string $formType, ?int $imageId): Response
{
$form = $this->getForm($this->getImage($imageId));
Expand All @@ -44,6 +54,17 @@ public function editAction(string $formType, ?int $imageId): Response
]);
}

public function editWithPropertyPathAction(string $formType, ?int $imageId): Response
{
$form = $this->getFormWithPropertyPath($this->getImage($imageId));

return $this->render('default/edit_with_property_path.html.twig', [
'imageId' => $imageId,
'formType' => $formType,
'form' => $form->createView(),
]);
}

public function submitAction(Request $request, string $formType, ?int $imageId = null): Response
{
$image = $this->getImage($imageId);
Expand All @@ -67,6 +88,29 @@ public function submitAction(Request $request, string $formType, ?int $imageId =
]);
}

public function submitWithPropertyPathAction(Request $request, string $formType, ?int $imageId = null): Response
{
$image = $this->getImage($imageId);
$form = $this->getFormWithPropertyPath($image)->handleRequest($request);

if ($form->isSubmitted() && $form->isValid()) {
$em = $this->doctrine->getManager();

$em->persist($image);
$em->flush();

return $this->redirect($this->generateUrl('view_with_property_path', [
'formType' => $formType,
'imageId' => $image->getId(),
]));
}

return $this->render('default/upload_with_property_path.html.twig', [
'formType' => $formType,
'form' => $form->createView(),
]);
}

private function getForm(Image $image): FormInterface
{
return $this->createFormBuilder($image)
Expand All @@ -77,6 +121,16 @@ private function getForm(Image $image): FormInterface
;
}

private function getFormWithPropertyPath(Image $image): FormInterface
{
return $this->createFormBuilder($image)
->add('title', Type\TextType::class)
->add('image_file', VichType\VichImageType::class, ['property_path' => 'imageFile'])
->add('save', Type\SubmitType::class)
->getForm()
;
}

private function getImage(?int $imageId = null): Image
{
if (null === $imageId) {
Expand Down
13 changes: 13 additions & 0 deletions tests/Form/Type/VichFileTypeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Vich\UploaderBundle\Tests\Form\Type;

use PHPUnit\Framework\TestCase;
use Symfony\Component\Form\FormConfigInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\OptionsResolver\OptionsResolver;
Expand Down Expand Up @@ -98,6 +99,14 @@ public function testBuildView(Product $object = null, array $options, array $var
->method('getData')
->willReturn($object);

$config = $this->createMock(FormConfigInterface::class);
$config
->expects($this->any())
->method('getOption')
->willReturnCallback(function (string $key) use ($options) {
return $options[$key] ?? null;
});

$form = $this->createMock(FormInterface::class);
$form
->expects($this->any())
Expand All @@ -107,6 +116,10 @@ public function testBuildView(Product $object = null, array $options, array $var
->expects($this->any())
->method('getName')
->willReturn($field);
$form
->expects($this->any())
->method('getConfig')
->willReturn($config);

$uploadHandler = $this->createMock(UploadHandler::class);
$propertyMappingFactory = $this->createMock(PropertyMappingFactory::class);
Expand Down
5 changes: 5 additions & 0 deletions tests/Form/Type/VichImageTypeTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
namespace Vich\UploaderBundle\Tests\Form\Type;

use Liip\ImagineBundle\Imagine\Cache\CacheManager;
use Symfony\Component\Form\FormConfigInterface;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\PropertyAccess\PropertyAccessor;
Expand Down Expand Up @@ -287,6 +288,10 @@ public function testLiipImagineBundleIntegrationThrownExceptionIfNotAvailable():
->expects($this->any())
->method('getParent')
->willReturn($parentForm);
$form
->expects($this->any())
->method('getConfig')
->willReturn($this->createMock(FormConfigInterface::class));

$view = new FormView();
$type = new $testedType($storage, $uploadHandler, $propertyMappingFactory, $propertyAccessor);
Expand Down
33 changes: 25 additions & 8 deletions tests/Functional/UploadTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,15 @@

final class UploadTest extends WebTestCase
{
public function testFileIsUploadedWithFileType(): void
/**
* @dataProvider uploadTypeDataProvider
*/
public function testFileIsUploadedWithFileType(string $uploadType, string $imageFieldName): void
{
$client = static::createClient();
$this->loadFixtures($client);

$crawler = $client->request('GET', '/upload/vich_file');
$crawler = $client->request('GET', sprintf('/%s/vich_file', $uploadType));
self::assertTrue($client->getResponse()->isSuccessful());

$form = $crawler->selectButton('form_save')->form();
Expand All @@ -18,7 +21,7 @@ public function testFileIsUploadedWithFileType(): void
$client->submit($form, [
'form' => [
'title' => 'Test image',
'imageFile' => ['file' => $image],
$imageFieldName => ['file' => $image],
],
]);

Expand All @@ -35,19 +38,22 @@ public function testFileIsUploadedWithFileType(): void
$client->submit($form, [
'form' => [
'title' => 'Test image',
'imageFile' => ['delete' => true],
$imageFieldName => ['delete' => true],
],
]);
self::assertTrue($client->getResponse()->isRedirect());
self::assertFileDoesNotExist($this->getUploadsDir($client).'/symfony_black_03.png', 'The file is deleted');
}

public function testFileIsUploadedWithImageType(): void
/**
* @dataProvider uploadTypeDataProvider
*/
public function testFileIsUploadedWithImageType(string $uploadType, string $imageFieldName): void
{
$client = static::createClient();
$this->loadFixtures($client);

$crawler = $client->request('GET', '/upload/vich_image');
$crawler = $client->request('GET', sprintf('/%s/vich_image', $uploadType));
self::assertTrue($client->getResponse()->isSuccessful());

$form = $crawler->selectButton('form_save')->form();
Expand All @@ -56,7 +62,7 @@ public function testFileIsUploadedWithImageType(): void
$crawler = $client->submit($form, [
'form' => [
'title' => 'Test image',
'imageFile' => ['file' => $image],
$imageFieldName => ['file' => $image],
],
]);

Expand All @@ -73,10 +79,21 @@ public function testFileIsUploadedWithImageType(): void
$client->submit($form, [
'form' => [
'title' => 'Test image',
'imageFile' => ['delete' => true],
$imageFieldName => ['delete' => true],
],
]);
self::assertTrue($client->getResponse()->isRedirect());
self::assertFileDoesNotExist($this->getUploadsDir($client).'/symfony_black_03.png', 'The file is deleted');
}

/**
* @return array<array{string, string}>
*/
public function uploadTypeDataProvider(): array
{
return [
['upload', 'imageFile'],
['upload_with_property_path', 'image_file'],
];
}
}

0 comments on commit 44fdfbc

Please sign in to comment.