-
Notifications
You must be signed in to change notification settings - Fork 0
/
ResourceUtil.php
68 lines (60 loc) · 2.63 KB
/
ResourceUtil.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<?php
/*
* This file is part of the Klipper package.
*
* (c) François Pluchino <[email protected]>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Klipper\Component\Resource;
use Klipper\Component\Resource\Domain\WrapperInterface;
use Klipper\Component\Resource\Exception\InvalidResourceException;
use Klipper\Component\Resource\Exception\UnexpectedTypeException;
use Symfony\Component\Form\FormInterface;
/**
* Util for resource.
*
* @author François Pluchino <[email protected]>
*/
abstract class ResourceUtil
{
/**
* Convert the object data of resource to resource list.
*
* @param FormInterface[]|object[] $objects The resource object instance or form of object instance
* @param string $requireClass The require class name
* @param bool $allowForm Check if the form is allowed
*
* @throws InvalidResourceException When the instance object in the list is not an instance of the required class
*/
public static function convertObjectsToResourceList(array $objects, string $requireClass, bool $allowForm = true): ResourceList
{
$list = new ResourceList();
foreach ($objects as $i => $object) {
static::validateObjectResource($object, $requireClass, $i, $allowForm);
$list->add(new ResourceItem((object) $object));
}
return $list;
}
/**
* Validate the resource object.
*
* @param FormInterface|mixed $object The resource object or form of resource object
* @param string $requireClass The required class
* @param int $i The position of the object in the list
* @param bool $allowForm Check if the form is allowed
*
* @throws UnexpectedTypeException When the object parameter is not an object or a form instance
* @throws InvalidResourceException When the object in form is not an object
* @throws InvalidResourceException When the object instance is not an instance of the required class
*/
public static function validateObjectResource($object, string $requireClass, int $i, bool $allowForm = true): void
{
$object = $object instanceof WrapperInterface ? $object->getData() : $object;
$object = $allowForm && $object instanceof FormInterface ? $object = $object->getData() : $object;
if (!\is_object($object) || !$object instanceof $requireClass) {
throw new UnexpectedTypeException($object, $requireClass, $i);
}
}
}