Skip to content

Commit

Permalink
Initial version of the Sonata Clone Action extension
Browse files Browse the repository at this point in the history
  • Loading branch information
jorrit committed Jul 23, 2020
0 parents commit badea11
Show file tree
Hide file tree
Showing 13 changed files with 362 additions and 0 deletions.
19 changes: 19 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
; top-most EditorConfig file
root = true

; Unix-style newlines
[*]
charset = utf-8
end_of_line = LF
insert_final_newline = true
trim_trailing_whitespace = true

[*.{php,html,twig,json}]
indent_style = space
indent_size = 4

[*.md]
max_line_length = 80

[COMMIT_EDITMSG]
max_line_length = 0
4 changes: 4 additions & 0 deletions .gitattributes
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
.* export-ignore
*.md export-ignore
tests export-ignore
docs export-ignore
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
/vendor/
composer.lock
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2020 Jorrit Schippers

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
63 changes: 63 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
# Sonata Admin Clone Action

Adds a clone action to Sonata Admin. This allows you to add a clone button to
your list action that leads to a create form with the values of the cloned item
prefilled.

The clone action does not create the clone in the database, this happens only
when the create form is submitted.

## Installation

```bash
$ composer require jorrit/sonata-clone-extension-bundle
```

## Setup

The extension is registered just like any other Sonata Admin extension.
For more information regarding extensions, see the [Sonata Admin documentation](https://sonata-project.org/bundles/admin/3-x/doc/reference/extensions.html).

### Add to specific admins

Add the following code to services.yml to add the extension to one or more admin classes.

Replace `admin1` and `admin2` with the service names of your admin classes.

```yaml
admin.clone.extension:
class: Jorrit\SonataCloneActionBundle\Admin\Extension\CloneAdminExtension
tags:
- { name: sonata.admin.extension, target: admin1 }
- { name: sonata.admin.extension, target: admin2 }
```

### Add to all admins

Add the following code to services.yml to add the extension all admin classes.

```yaml
admin.clone.extension:
class: Jorrit\SonataCloneActionBundle\Admin\Extension\CloneAdminExtension
tags:
- { name: sonata.admin.extension, global: true }
```

### Add the action to your admin list

Edit your admin class to add `clone` to the list of actions:

```php
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
...
->add('_action', null, [
'actions' => [
'edit' => [],
'delete' => [],
'clone' => [],
]
]);
}
```
39 changes: 39 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"name": "jorrit/sonata-clone-action-bundle",
"description": "Sonata Admin extension that adds a clone action.",
"keywords": [
"sonata",
"admin",
"extension",
"clone"
],
"type": "library",
"license": "MIT",
"authors": [
{
"name": "Jorrit Schippers",
"email": "jorrit@ncode.nl"
}
],
"require": {
"php": "^7.2",
"sonata-project/admin-bundle": "^3.72.0",
"symfony/framework-bundle": "^4.4",
"symfony/http-kernel": "^4.4",
"symfony/property-access": "^4.4",
"symfony/property-info": "^4.4"
},
"config": {
"sort-packages": true
},
"autoload": {
"psr-4": {
"Jorrit\\SonataCloneActionBundle\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Jorrit\\SonataCloneActionBundle\\Tests\\": "tests/"
}
}
}
100 changes: 100 additions & 0 deletions src/Admin/Extension/CloneAdminExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
<?php

namespace Jorrit\SonataCloneActionBundle\Admin\Extension;

use Sonata\AdminBundle\Admin\AbstractAdminExtension;
use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Route\RouteCollection;
use Jorrit\SonataCloneActionBundle\Controller\CloneController;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyInfo\PropertyListExtractorInterface;

class CloneAdminExtension extends AbstractAdminExtension
{
const REQUEST_ATTRIBUTE = '_clone_subject';

/**
* @var PropertyListExtractorInterface
*/
private $propertyInfoExtractor;

/**
* @var RequestStack
*/
private $requestStack;

public function __construct(
PropertyListExtractorInterface $propertyInfoExtractor,
RequestStack $requestStack
) {
$this->propertyInfoExtractor = $propertyInfoExtractor;
$this->requestStack = $requestStack;
}

public function getAccessMapping(AdminInterface $admin)
{
return [
'clone' => 'CREATE',
];
}

public function alterNewInstance(AdminInterface $admin, $object)
{
$request = $this->requestStack->getCurrentRequest();
if ($request === null || !$request->attributes->has(self::REQUEST_ATTRIBUTE)) {
return;
}

$subject = $request->attributes->get(self::REQUEST_ATTRIBUTE);

$idfields = $admin->getModelManager()->getIdentifierFieldNames($admin->getClass());
$propertyAccessor = PropertyAccess::createPropertyAccessor();

$properties = $this->propertyInfoExtractor->getProperties($subject);

foreach ($properties as $property) {
// Skip identifier fields.
if (in_array($property, $idfields)) {
continue;
}

// Skip unwritable fields.
if (!$propertyAccessor->isWritable($object, $property)) {
continue;
}

// Skip unreadable fields.
if (!$propertyAccessor->isReadable($subject, $property)) {
continue;
}

$propertyAccessor->setValue($object, $property, $propertyAccessor->getValue($subject, $property));
}
}

public function configureRoutes(AdminInterface $admin, RouteCollection $collection)
{
$collection->add(
'clone',
$admin->getRouterIdParameter().'/clone',
[
'_controller' => CloneController::class,
]
);
}

public function configureListFields(ListMapper $listMapper)
{
$itemkeys = $listMapper->keys();

foreach ($itemkeys as $itemkey) {
$item = $listMapper->get($itemkey);
if (($actions = $item->getOption('actions')) && isset($actions['clone'])) {
$actions['clone']['template'] = '@SonataCloneAction/SonataAdmin/CRUD/list__action_clone.html.twig';
$item->setOption('actions', $actions);
}
}
}
}
57 changes: 57 additions & 0 deletions src/Controller/CloneController.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<?php

namespace Jorrit\SonataCloneActionBundle\Controller;

use Jorrit\SonataCloneActionBundle\Admin\Extension\CloneAdminExtension;
use Sonata\AdminBundle\Admin\Pool;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException;
use Symfony\Component\HttpFoundation\Request;

class CloneController extends AbstractController
{
/**
* @var Pool
*/
private $pool;

public function __construct(Pool $pool)
{
$this->pool = $pool;
}

public function __invoke(Request $request)
{
if (!$request->attributes->has('_sonata_admin')) {
return $this->createNotFoundException('Route should have _sonata_admin attribute');
}

try {
$admin = $this->pool->getAdminByAdminCode($request->attributes->get('_sonata_admin'));
} catch (ServiceNotFoundException $e) {
throw new \RuntimeException('Unable to find the Admin instance', $e->getCode(), $e);
}

// Check if the user has clone permission.
$admin->checkAccess('clone');

// Fetch the original item and check SHOW access.
$id = $request->get($admin->getIdParameter());
$subject = $admin->getObject($id);
if (!$subject) {
throw $this->createNotFoundException(sprintf('unable to find the object with id: %s', $id));
}

$admin->checkAccess('show', $subject);

$controllerName = $admin->getBaseControllerName();

return $this->forward(
$controllerName.'::createAction',
[
'_sonata_admin' => $request->attributes->get('_sonata_admin'),
CloneAdminExtension::REQUEST_ATTRIBUTE => $subject,
]
);
}
}
20 changes: 20 additions & 0 deletions src/DependencyInjection/SonataCloneActionExtension.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace Jorrit\SonataCloneActionBundle\DependencyInjection;

use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;

class SonataCloneActionExtension extends Extension {

public function load(array $configs, ContainerBuilder $container)
{
$loader = new YamlFileLoader(
$container,
new FileLocator(__DIR__.'/../Resources/config')
);
$loader->load('services.yaml');
}
}
6 changes: 6 additions & 0 deletions src/Resources/config/services.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
services:
Jorrit\SonataCloneActionBundle\Controller\CloneController:
class: Jorrit\SonataCloneActionBundle\Controller\CloneController
public: true
arguments:
- '@sonata.admin.pool'
11 changes: 11 additions & 0 deletions src/Resources/translations/SonataCloneActionBundle.en.xliff
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<xliff xmlns="urn:oasis:names:tc:xliff:document:1.2" version="1.2">
<file source-language="en" datatype="plaintext" original="">
<body>
<trans-unit id="action_clone">
<source>action_clone</source>
<target>Clone</target>
</trans-unit>
</body>
</file>
</xliff>
10 changes: 10 additions & 0 deletions src/Resources/views/SonataAdmin/CRUD/list__action_clone.html.twig
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{% if admin.hasAccess('clone', object) and admin.hasRoute('clone') %}
<a
href="{{ admin.generateObjectUrl('clone', object, actions.link_parameters|default([])) }}"
class="btn btn-sm btn-default clone_link"
title="{{ 'action_clone'|trans({}, 'SonataCloneActionBundle') }}"
>
<i class="fa fa-clone" aria-hidden="true"></i>
{{ 'action_clone'|trans({}, 'SonataCloneActionBundle') }}
</a>
{% endif %}
10 changes: 10 additions & 0 deletions src/SonataCloneActionBundle.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<?php

namespace Jorrit\SonataCloneActionBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class SonataCloneActionBundle extends Bundle
{

}

0 comments on commit badea11

Please sign in to comment.