Passed
Push — master ( a1de92...1a465b )
by Robbie
03:52
created

src/GraphQL/SortBlockMutationCreator.php (1 issue)

1
<?php
2
namespace DNADesign\Elemental\GraphQL;
3
4
use DNADesign\Elemental\Models\BaseElement;
5
use DNADesign\Elemental\Services\ReorderElements;
6
use GraphQL\Type\Definition\ResolveInfo;
7
use GraphQL\Type\Definition\Type;
8
use SilverStripe\Core\Convert;
9
use SilverStripe\Core\Injector\Injector;
10
use SilverStripe\GraphQL\MutationCreator;
11
use SilverStripe\GraphQL\OperationResolver;
12
use SilverStripe\GraphQL\Scaffolding\StaticSchema;
13
use SilverStripe\ORM\DataObject;
14
use SilverStripe\ORM\Queries\SQLUpdate;
15
16
/**
17
 * Given a source block ID and the ID of the block to reorder the source block after, update all affected sort
18
 * orders for the block and its siblings. Only the source block will have a new version written, all siblings
19
 * will be updated underneath the ORM to avoid this.
20
 */
21
class SortBlockMutationCreator extends MutationCreator implements OperationResolver
22
{
23
    public function attributes()
24
    {
25
        return [
26
            'name' => 'sortBlock',
27
            'description' => 'Changes the sort position of an element'
28
        ];
29
    }
30
31
    public function type()
32
    {
33
        return $this->manager->getType(StaticSchema::inst()->typeNameForDataObject(BaseElement::class));
34
    }
35
36
    public function args()
37
    {
38
        return [
39
            'ID' => ['type' => Type::nonNull(Type::id())],
40
            'AfterBlockID' => ['type' => Type::nonNull(Type::id())],
41
        ];
42
    }
43
44
    public function resolve($object, array $args, $context, ResolveInfo $info)
45
    {
46
        $element = BaseElement::get()->byID($args['ID']);
47
        
48
        if (!$element) {
49
            throw new InvalidArgumentException(sprintf(
0 ignored issues
show
The type DNADesign\Elemental\Grap...nvalidArgumentException was not found. Did you mean InvalidArgumentException? If so, make sure to prefix the type with \.
Loading history...
50
                '%s#%s not found',
51
                BaseElement::class,
52
                $args['ID']
53
            ));
54
        }
55
56
        if (!$element->canEdit($context['currentUser'])) {
57
            throw new InvalidArgumentException(
58
                'Changing the sort order of blocks is not allowed for the current user'
59
            );
60
        }
61
62
        $reorderingService = Injector::inst()->create(ReorderElements::class, $element);
63
        return $reorderingService->reorder($args['AfterBlockID']);
64
    }
65
}
66