Completed
Push — master ( cc21f4...3eeaf5 )
by Julien
06:41 queued 03:06
created

SdkClient::createProxy()   B

Complexity

Conditions 9
Paths 3

Size

Total Lines 77
Code Lines 49

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 90

Importance

Changes 0
Metric Value
cc 9
eloc 49
nc 3
nop 1
dl 0
loc 77
ccs 0
cts 40
cp 0
crap 90
rs 7.5571
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
namespace Mapado\RestClientSdk;
4
5
use Mapado\RestClientSdk\Model\ModelHydrator;
6
use Mapado\RestClientSdk\Model\Serializer;
7
use ProxyManager\Configuration;
8
use ProxyManager\Factory\LazyLoadingGhostFactory;
9
use ProxyManager\Proxy\GhostObjectInterface;
10
use Psr\Cache\CacheItemPoolInterface;
11
12
/**
13
 * Sdk Client
14
 */
15
class SdkClient
16
{
17
    /**
18
     * @var RestClient
19
     */
20
    protected $restClient;
21
22
    /**
23
     * Cache item pool.
24
     *
25
     * @var ?CacheItemPoolInterface
26
     */
27
    protected $cacheItemPool;
28
29
    /**
30
     * Cache prefix.
31
     *
32
     * @var string
33
     */
34
    protected $cachePrefix;
35
36
    /**
37
     * @var Mapping
38
     */
39
    private $mapping;
40
41
    /**
42
     * @var Serializer
43
     */
44
    private $serializer;
45
46
    /**
47
     * @var ModelHydrator
48
     */
49
    private $modelHydrator;
50
51
    /**
52
     * @var array
53
     */
54
    private $repositoryList = [];
55
56
    /**
57
     * proxyManagerConfig
58
     *
59
     * @var ?Configuration
60
     */
61
    private $proxyManagerConfig;
62
63
    /**
64
     * unitOfWork
65
     *
66
     * @var UnitOfWork
67
     */
68
    private $unitOfWork;
69
70
    /**
71
     * Constructor.
72
     *
73
     * @param RestClient      $restClient
74
     * @param Mapping         $mapping
75
     * @param UnitOfWork|null $unitOfWork
76
     * @param Serializer|null $serializer
77
     */
78
    public function __construct(
79
        RestClient $restClient,
80
        Mapping $mapping,
81
        UnitOfWork $unitOfWork = null,
82
        Serializer $serializer = null
83
    ) {
84 1
        $this->restClient = $restClient;
85 1
        $this->mapping = $mapping;
86 1
        if (!$unitOfWork) {
87
            $unitOfWork = new UnitOfWork($this->mapping);
88
        }
89 1
        $this->unitOfWork = $unitOfWork;
90 1
        if (!$serializer) {
91
            $serializer = new Serializer($this->mapping, $this->unitOfWork);
92
        }
93 1
        $this->serializer = $serializer;
94 1
        $this->serializer->setSdk($this);
95
96 1
        $this->modelHydrator = new ModelHydrator($this);
97 1
    }
98
99
    /**
100
     * setCacheItemPool
101
     *
102
     * @param CacheItemPoolInterface $cacheItemPool
103
     *
104
     * @return SdkClient
105
     */
106
    public function setCacheItemPool(
107
        CacheItemPoolInterface $cacheItemPool,
108
        $cachePrefix = ''
109
    ) {
110
        $this->cacheItemPool = $cacheItemPool;
111
        $this->cachePrefix = $cachePrefix;
112
113
        return $this;
114
    }
115
116
    /**
117
     * getCacheItemPool
118
     *
119
     * @return ?CacheItemPoolInterface
120
     */
121
    public function getCacheItemPool()
122
    {
123
        return $this->cacheItemPool;
124
    }
125
126
    /**
127
     * getCachePrefix
128
     *
129
     * @return string
130
     */
131
    public function getCachePrefix()
132
    {
133
        return $this->cachePrefix;
134
    }
135
136
    /**
137
     * getRepository
138
     *
139
     * @param string $modelName
140
     *
141
     * @return EntityRepository
142
     */
143
    public function getRepository($modelName)
144
    {
145
        // get repository by key
146 1
        $metadata = $this->mapping->getClassMetadataByKey($modelName);
147 1
        if (!$metadata) {
148
            // get by classname
149 1
            $metadata = $this->mapping->getClassMetadata($modelName);
150
        }
151
152 1
        $modelName = $metadata->getModelName();
153
154 1
        if (!isset($this->repositoryList[$modelName])) {
155
            $repositoryName =
156 1
                $metadata->getRepositoryName()
157 1
                ?: '\Mapado\RestClientSdk\EntityRepository';
158 1
            $this->repositoryList[$modelName] = new $repositoryName(
159 1
                $this,
160 1
                $this->restClient,
161 1
                $this->unitOfWork,
162 1
                $modelName
163
            );
164
        }
165
166 1
        return $this->repositoryList[$modelName];
167
    }
168
169
    /**
170
     * getRestClient
171
     *
172
     * @return RestClient
173
     */
174
    public function getRestClient()
175
    {
176 1
        return $this->restClient;
177
    }
178
179
    /**
180
     * getMapping
181
     *
182
     * @return Mapping
183
     */
184
    public function getMapping()
185
    {
186 1
        return $this->mapping;
187
    }
188
189
    /**
190
     * getSerializer
191
     *
192
     * @return Serializer
193
     */
194
    public function getSerializer()
195
    {
196 1
        return $this->serializer;
197
    }
198
199
    /**
200
     * getModelHydrator
201
     *
202
     * @return ModelHydrator
203
     */
204
    public function getModelHydrator()
205
    {
206
        return $this->modelHydrator;
207
    }
208
209
    /**
210
     * createProxy
211
     *
212
     * @param string $id
213
     *
214
     * @return \ProxyManager\Proxy\GhostObjectInterface
215
     */
216
    public function createProxy($id)
217
    {
218
        $key = $this->mapping->getKeyFromId($id);
219
        $classMetadata = $this->mapping->getClassMetadataByKey($key);
220
221
        if (null === $classMetadata) {
222
            throw new \RuntimeException(
223
                "Unable to get classMetadata for key {$key}. This should not happen."
224
            );
225
        }
226
227
        $modelName = $classMetadata->getModelName();
228
229
        $sdk = $this;
230
231
        if ($this->proxyManagerConfig) {
232
            $factory = new LazyLoadingGhostFactory($this->proxyManagerConfig);
233
        } else {
234
            $factory = new LazyLoadingGhostFactory();
235
        }
236
237
        $proxyModelName = preg_replace('/^\\\\*/', '', $modelName);
238
239
        $initializer = function (
240
            GhostObjectInterface $proxy,
241
            string $method,
242
            array $parameters,
243
            &$initializer,
244
            array $properties
245
        ) use ($sdk, $classMetadata, $id, $proxyModelName) {
246
            $isAllowedMethod =
247
                'jsonSerialize' === $method ||
248
                '__set' === $method ||
249
                '__isset' === $method && 'id' === $parameters['name'];
250
251
            if (!$isAllowedMethod) {
252
                $initializer = null; // disable initialization
253
                // load data and modify the object here
254
                if ($id) {
255
                    $repository = $sdk->getRepository(
256
                        $classMetadata->getModelName()
257
                    );
258
                    $model = $repository->find($id);
259
260
                    $attributeList = $classMetadata->getAttributeList();
261
262
                    foreach ($attributeList as $attribute) {
263
                        $getter =
264
                            'get' . ucfirst($attribute->getAttributeName());
265
                        $value = $model->{$getter}();
266
                        $properties[
267
                            "\0" .
268
                            $proxyModelName .
269
                            "\0" .
270
                            $attribute->getAttributeName()
271
                        ] = $value;
272
                    }
273
                }
274
275
                return true; // confirm that initialization occurred correctly
276
            }
277
        };
278
279
        // initialize the proxy instance
280
        $instance = $factory->createProxy($modelName, $initializer, [
281
            'skippedProperties' => ["\0" . $proxyModelName . "\0id"],
282
        ]);
283
284
        // set the id of the object
285
        $idReflexion = new \ReflectionProperty(
286
            $modelName,
287
            $classMetadata->getIdentifierAttribute()->getAttributeName()
288
        );
289
        $idReflexion->setAccessible(true);
290
        $idReflexion->setValue($instance, $id);
291
292
        return $instance;
293
    }
294
295
    /**
296
     * Setter for fileCachePath
297
     *
298
     * @param string $fileCachePath
299
     *
300
     * @return SdkClient
301
     */
302
    public function setFileCachePath($fileCachePath)
303
    {
304
        $this->proxyManagerConfig = new Configuration();
305
        $this->proxyManagerConfig->setProxiesTargetDir($fileCachePath);
306
307
        return $this;
308
    }
309
}
310