Completed
Push — master ( 8faaeb...8ada5a )
by
06:40
created

ResourceController::stringToBoolean()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 10
rs 9.4286
cc 3
eloc 5
nc 4
nop 1
1
<?php
2
3
namespace DoS\ResourceBundle\Controller;
4
5
use Doctrine\ORM\EntityManager;
6
use DoS\ResourceBundle\Doctrine\ORM\EntityRepository;
7
use Sylius\Bundle\ResourceBundle\Controller\ResourceController as BaseResourceController;
8
use Sylius\Component\Resource\Event\ResourceEvent;
9
use Sylius\Component\Resource\Exception\UnexpectedTypeException;
10
use Symfony\Component\HttpFoundation\RedirectResponse;
11
use Symfony\Component\HttpFoundation\Request;
12
use Symfony\Component\HttpFoundation\Response;
13
use Symfony\Component\HttpKernel\Exception\HttpException;
14
use Symfony\Component\PropertyAccess\PropertyAccess;
15
16
class ResourceController extends BaseResourceController
17
{
18
    protected $activedPath = 'actived';
19
    protected $enabledPath = 'enabled';
20
21
    /**
22
     * @return EntityManager
23
     */
24
    protected function getManager()
25
    {
26
        return $this->get($this->config->getServiceName('manager'));
27
    }
28
29
    /**
30
     * @param $resource
31
     * @param bool|true $dosRepository
32
     *
33
     * @return \Doctrine\ORM\EntityRepository|EntityRepository
34
     */
35
    protected function getEntityRepository($resource, $dosRepository = true)
36
    {
37
        $er = $this->getManager()->getRepository(get_class($resource));
38
39
        if ($dosRepository) {
40
            if (!$er instanceof EntityRepository) {
41
                throw new UnexpectedTypeException($er, EntityRepository::class);
42
            }
43
        }
44
45
        return $er;
46
    }
47
48
    /**
49
     * @param $string
50
     *
51
     * @return bool
52
     */
53
    protected function stringToBoolean($string)
54
    {
55
        $string = is_string($string) ? strtolower($string) : $string;
56
57
        if (in_array($string, array(true, 1, '1', 'yes', 'true'), true)) {
58
            return true;
59
        }
60
61
        return false;
62
    }
63
64
    /**
65
     * @inheritdoc
66
     */
67
    public function findOr404(Request $request, array $criteria = array())
68
    {
69
        $resource = parent::findOr404($request, $criteria);
70
71
        if ($roles = $this->config->getParameters()->get('is_granted')) {
72
            $this->denyAccessUnlessGranted((array) $roles, $resource);
73
        }
74
75
        return $resource;
76
    }
77
78
    /**
79
     * @param Request $request
80
     * @param $state
81
     * @param null $path
82
     *
83
     * @return RedirectResponse|Response
84
     */
85
    public function activeStateAction(Request $request, $state, $path = null)
86
    {
87
        $path = $path ?: $this->activedPath;
88
        $resource = $this->findOr404($request);
89
        $accessor = PropertyAccess::createPropertyAccessor();
90
        $accessor->setValue($resource, $path, $this->stringToBoolean($state));
91
92
        $this->getManager()->transactional(function () use ($state, $resource, $path) {
93
            if ($state) {
94
                // reset other to false
95
                $this->getEntityRepository($resource)->bulkUpdate(array($path => false));
96
            }
97
98
            $this->domainManager->update($resource);
99
        });
100
101 View Code Duplication
        if ($this->config->isApiRequest()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
102
            if ($resource instanceof ResourceEvent) {
103
                throw new HttpException($resource->getErrorCode(), $resource->getMessage());
104
            }
105
106
            return $this->handleView($this->view($resource, 204));
107
        }
108
109
        return $this->redirectHandler->redirectToReferer();
110
    }
111
112
    /**
113
     * @param Request $request
114
     * @param $state
115
     * @param null $path
116
     *
117
     * @return RedirectResponse|Response
118
     */
119
    public function enableStateAction(Request $request, $state, $path = null)
120
    {
121
        $path = $path ?: $this->enabledPath;
122
        $resource = $this->findOr404($request);
123
        $accessor = PropertyAccess::createPropertyAccessor();
124
        $accessor->setValue($resource, $path, $this->stringToBoolean($state));
125
126
        $this->domainManager->update($resource);
0 ignored issues
show
Bug introduced by
It seems like $resource can also be of type array; however, Sylius\Bundle\ResourceBu...DomainManager::update() does only seem to accept object, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
127
128 View Code Duplication
        if ($this->config->isApiRequest()) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
129
            if ($resource instanceof ResourceEvent) {
130
                throw new HttpException($resource->getErrorCode(), $resource->getMessage());
131
            }
132
133
            return $this->handleView($this->view($resource, 204));
134
        }
135
136
        return $this->redirectHandler->redirectToReferer();
137
    }
138
139
    public function batchDeleteAction(Request $request, array $ids = null)
140
    {
141
        if (null == $ids) {
142
            $ids = $request->get('ids');
143
        }
144
145
        if (is_string($ids)) {
146
            $ids = explode( ',', $ids);
147
        }
148
149
        $this->isGrantedOr403('delete');
150
151
        $resources = $this->get('toro.repository.match')->findBy(array(
152
            'id' => $ids
153
        ));
154
155
        if (!count($resources)) {
156
            throw new NotFoundHttpException(
157
                sprintf(
158
                    'Requested %s does not exist with these ids: %s.',
159
                    $this->config->getResourceName(),
160
                    json_encode($this->config->getCriteria($ids))
161
                )
162
            );
163
        }
164
165
        /** @var MatchInterface $resource */
166
        foreach ($resources as $resource) {
167
            /** @var ResourceEvent $resource */
168
            $resource = $this->domainManager->delete($resource);
169
170
            if ($this->config->isApiRequest()) {
171
                if ($resource instanceof ResourceEvent) {
172
                    throw new HttpException($resource->getErrorCode(), $resource->getMessage());
173
                }
174
            }
175
        }
176
177
        if ($this->config->isApiRequest()) {
178
            return $this->handleView($this->view());
179
        }
180
181
        return $this->redirectHandler->redirectToIndex();
182
    }
183
}
184