File: RemoteObjectFunctionalTest.php

package info (click to toggle)
php-proxy-manager 2.11.1%2B1.0.18-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,624 kB
  • sloc: php: 14,438; makefile: 25
file content (452 lines) | stat: -rw-r--r-- 14,579 bytes parent folder | download
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
<?php

declare(strict_types=1);

namespace ProxyManagerTest\Functional;

use Generator;
use Laminas\Server\Client;
use PHPUnit\Framework\TestCase;
use ProxyManager\Factory\RemoteObject\Adapter\JsonRpc as JsonRpcAdapter;
use ProxyManager\Factory\RemoteObject\Adapter\XmlRpc as XmlRpcAdapter;
use ProxyManager\Factory\RemoteObject\AdapterInterface;
use ProxyManager\Factory\RemoteObjectFactory;
use ProxyManagerTestAsset\ClassWithPublicStringNullableNullDefaultTypedProperty;
use ProxyManagerTestAsset\ClassWithPublicStringNullableTypedProperty;
use ProxyManagerTestAsset\ClassWithPublicStringTypedProperty;
use ProxyManagerTestAsset\ClassWithSelfHint;
use ProxyManagerTestAsset\NeverCounter;
use ProxyManagerTestAsset\OtherObjectAccessClass;
use ProxyManagerTestAsset\RemoteProxy\BazServiceInterface;
use ProxyManagerTestAsset\RemoteProxy\Foo;
use ProxyManagerTestAsset\RemoteProxy\FooEnum;
use ProxyManagerTestAsset\RemoteProxy\FooServiceInterface;
use ProxyManagerTestAsset\RemoteProxy\RemoteServiceWithDefaultsAndVariadicArguments;
use ProxyManagerTestAsset\RemoteProxy\RemoteServiceWithDefaultsInterface;
use ProxyManagerTestAsset\RemoteProxy\RemoteServiceWithPhp81DefaultsInterface;
use ProxyManagerTestAsset\RemoteProxy\VariadicArgumentsServiceInterface;
use ProxyManagerTestAsset\VoidCounter;
use ReflectionClass;
use RuntimeException;
use stdClass;

use function assert;
use function get_class;
use function is_callable;
use function random_int;
use function ucfirst;
use function uniqid;

use const PHP_VERSION_ID;

/**
 * Tests for {@see \ProxyManager\ProxyGenerator\RemoteObjectGenerator} produced objects
 *
 * @group Functional
 * @coversNothing
 */
final class RemoteObjectFunctionalTest extends TestCase
{
    /**
     * @param mixed[] $parametersExpectedByClient
     */
    protected function getXmlRpcAdapter($expectedValue, string $method, array $parametersExpectedByClient): XmlRpcAdapter
    {
        $client = $this->getMockBuilder(Client::class)->getMock();

        $client
            ->method('call')
            ->with(self::stringEndsWith($method), $parametersExpectedByClient)
            ->willReturn($expectedValue);

        return new XmlRpcAdapter(
            $client,
            ['ProxyManagerTestAsset\RemoteProxy\Foo.foo' => 'ProxyManagerTestAsset\RemoteProxy\FooServiceInterface.foo']
        );
    }

    /**
     * @param mixed[] $params
     */
    protected function getJsonRpcAdapter($expectedValue, string $method, array $params): JsonRpcAdapter
    {
        $client = $this->getMockBuilder(Client::class)->getMock();

        $client
            ->method('call')
            ->with(self::stringEndsWith($method), $params)
            ->willReturn($expectedValue);

        return new JsonRpcAdapter(
            $client,
            ['ProxyManagerTestAsset\RemoteProxy\Foo.foo' => 'ProxyManagerTestAsset\RemoteProxy\FooServiceInterface.foo']
        );
    }

    /**
     * @param array|mixed[] $passedParams
     * @param mixed[]       $callParametersExpectedByAdapter
     * @psalm-param class-string<OriginalClass>|OriginalClass $instanceOrClassName
     *
     * @dataProvider getProxyMethods
     * @psalm-template OriginalClass of object
     */
    public function testXmlRpcMethodCalls(
        $instanceOrClassName,
        string $method,
        array $passedParams,
        array $callParametersExpectedByAdapter,
        $expectedValue
    ): void {
        $proxy = (new RemoteObjectFactory($this->getXmlRpcAdapter($expectedValue, $method, $callParametersExpectedByAdapter)))
            ->createProxy($instanceOrClassName);

        $callback = [$proxy, $method];

        self::assertIsCallable($callback);
        self::assertSame($expectedValue, $callback(...$passedParams));
    }

    /**
     * @param array|mixed[] $passedParams
     * @param mixed[]       $parametersForProxy
     * @psalm-param class-string<OriginalClass>|OriginalClass $instanceOrClassName
     *
     * @dataProvider getProxyMethods
     * @psalm-template OriginalClass of object
     */
    public function testJsonRpcMethodCalls(
        $instanceOrClassName,
        string $method,
        array $passedParams,
        array $parametersForProxy,
        $expectedValue
    ): void {
        $proxy = (new RemoteObjectFactory($this->getJsonRpcAdapter($expectedValue, $method, $parametersForProxy)))
            ->createProxy($instanceOrClassName);

        $callback = [$proxy, $method];

        self::assertIsCallable($callback);
        self::assertSame($expectedValue, $callback(...$passedParams));
    }

    /**
     * @psalm-param class-string<OriginalClass>|OriginalClass $instanceOrClassName
     *
     * @dataProvider getPropertyAccessProxies
     * @psalm-template OriginalClass of object
     */
    public function testJsonRpcPropertyReadAccess($instanceOrClassName, string $publicProperty, $propertyValue): void
    {
        if (false !== strpos($instanceOrClassName, 'TypedProp') && \PHP_VERSION_ID < 70400) {
            self::markTestSkipped('PHP 7.4 required.');
        }

        $proxy = (new RemoteObjectFactory($this->getJsonRpcAdapter($propertyValue, '__get', [$publicProperty])))
            ->createProxy($instanceOrClassName);

        self::assertSame($propertyValue, $proxy->$publicProperty);
    }

    /**
     * Generates a list of object | invoked method | parameters | expected result
     *
     * @return string[][]|bool[][]|object[][]|mixed[][][]
     */
    public static function getProxyMethods(): array
    {
        $selfHintParam = new ClassWithSelfHint();

        $methods = [
            [
                FooServiceInterface::class,
                'foo',
                [],
                [],
                'bar remote',
            ],
            [
                Foo::class,
                'foo',
                [],
                [],
                'bar remote',
            ],
            [
                new Foo(),
                'foo',
                [],
                [],
                'bar remote',
            ],
            [
                BazServiceInterface::class,
                'baz',
                ['baz'],
                ['baz'],
                'baz remote',
            ],
            [
                new ClassWithSelfHint(),
                'selfHintMethod',
                [$selfHintParam],
                [$selfHintParam],
                $selfHintParam,
            ],
            [
                VariadicArgumentsServiceInterface::class,
                'method',
                ['aaa', 1, 2, 3, 4, 5],
                ['aaa', 1, 2, 3, 4, 5],
                true,
            ],
            [
                RemoteServiceWithDefaultsInterface::class,
                'optionalNonNullable',
                ['aaa'],
                ['aaa', 'Optional parameter to be kept during calls'],
                200,
            ],
            [
                RemoteServiceWithDefaultsInterface::class,
                'optionalNullable',
                ['aaa'],
                ['aaa', null],
                200,
            ],
            'when passing only the required parameters' => [
                RemoteServiceWithDefaultsInterface::class,
                'manyRequiredWithManyOptional',
                ['aaa', 100],
                [
                    'aaa',
                    100,
                    'Optional parameter to be kept during calls',
                    100,
                    'Yet another optional parameter to be kept during calls',
                ],
                200,
            ],
            'when passing required params and one optional params' => [
                RemoteServiceWithDefaultsInterface::class,
                'manyRequiredWithManyOptional',
                ['aaa', 100, 'passed'],
                [
                    'aaa',
                    100,
                    'passed',
                    100,
                    'Yet another optional parameter to be kept during calls',
                ],
                200,
            ],
            'when passing required params and some optional params' => [
                RemoteServiceWithDefaultsInterface::class,
                'manyRequiredWithManyOptional',
                ['aaa', 100, 'passed', 90],
                [
                    'aaa',
                    100,
                    'passed',
                    90,
                    'Yet another optional parameter to be kept during calls',
                ],
                200,
            ],
            'when passing only required for method with optional and variadic params' => [
                RemoteServiceWithDefaultsAndVariadicArguments::class,
                'optionalWithVariadic',
                ['aaa'],
                [
                    'aaa',
                    'Optional param to be kept on proxy call',
                ],
                200,
            ],
            'when passing required, optional and variadic params' => [
                RemoteServiceWithDefaultsAndVariadicArguments::class,
                'optionalWithVariadic',
                ['aaa', 'Optional param to be kept on proxy call', 10, 20, 30, 50, 90],
                [
                    'aaa',
                    'Optional param to be kept on proxy call',
                    10,
                    20,
                    30,
                    50,
                    90,
                ],
                200,
            ],
        ];

        if (PHP_VERSION_ID >= 80100) {
            $methods['when using php8.1 defaults'] = [
                RemoteServiceWithPhp81DefaultsInterface::class,
                'php81Defaults',
                [],
                [
                    FooEnum::bar,
                    new stdClass(),
                ],
                200,
            ];
        }

        return $methods;
    }

    /**
     * Generates proxies and instances with a public property to feed to the property accessor methods
     *
     * @return string[][]
     */
    public static function getPropertyAccessProxies(): array
    {
        return [
            [
                FooServiceInterface::class,
                'publicProperty',
                'publicProperty remote',
            ],
            [
                ClassWithPublicStringTypedProperty::class,
                'typedProperty',
                'typedProperty remote',
            ],
            [
                ClassWithPublicStringNullableTypedProperty::class,
                'typedNullableProperty',
                'typedNullableProperty remote',
            ],
            [
                ClassWithPublicStringNullableNullDefaultTypedProperty::class,
                'typedNullableNullDefaultProperty',
                'typedNullableNullDefaultProperty remote',
            ],
        ];
    }

    /**
     * @group        276
     * @dataProvider getMethodsThatAccessPropertiesOnOtherObjectsInTheSameScope
     */
    public function testWillInterceptAccessToPropertiesViaFriendClassAccess(
        $callerObject,
        $realInstance,
        string $method,
        string $expectedValue,
        string $propertyName
    ): void {
        $adapter = $this->createMock(AdapterInterface::class);

        $adapter
            ->expects(self::once())
            ->method('call')
            ->with(get_class($realInstance), '__get', [$propertyName])
            ->willReturn($expectedValue);

        $proxy = (new RemoteObjectFactory($adapter))
            ->createProxy($realInstance);

        $accessor = [$callerObject, $method];
        assert(is_callable($accessor));

        self::assertSame($expectedValue, $accessor($proxy));
    }

    /**
     * @group        276
     * @dataProvider getMethodsThatAccessPropertiesOnOtherObjectsInTheSameScope
     */
    public function testWillInterceptAccessToPropertiesViaFriendClassAccessEvenIfCloned(
        $callerObject,
        $realInstance,
        string $method,
        string $expectedValue,
        string $propertyName
    ): void {
        $adapter = $this->createMock(AdapterInterface::class);

        $adapter
            ->expects(self::once())
            ->method('call')
            ->with(get_class($realInstance), '__get', [$propertyName])
            ->willReturn($expectedValue);

        $proxy = clone (new RemoteObjectFactory($adapter))
            ->createProxy($realInstance);

        $accessor = [$callerObject, $method];
        assert(is_callable($accessor));

        self::assertSame($expectedValue, $accessor($proxy));
    }

    /**
     * @group 327
     */
    public function testWillExecuteLogicInAVoidMethod(): void
    {
        $adapter = $this->createMock(AdapterInterface::class);

        $increment = random_int(10, 1000);

        $adapter
            ->expects(self::once())
            ->method('call')
            ->with(VoidCounter::class, 'increment', [$increment])
            ->willReturn(random_int(10, 1000));

        $proxy = clone (new RemoteObjectFactory($adapter))
            ->createProxy(VoidCounter::class);

        $proxy->increment($increment);
    }

    /**
     * @requires PHP 8.1
     */
    public function testWillExecuteLogicInANeverMethod(): void
    {
        $adapter = $this->createMock(AdapterInterface::class);

        $increment = random_int(10, 1000);

        $adapter
            ->expects(self::once())
            ->method('call')
            ->with(NeverCounter::class, 'increment', [$increment])
            ->willThrowException(new RuntimeException());

        $proxy = clone (new RemoteObjectFactory($adapter))
            ->createProxy(NeverCounter::class);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('');

        $proxy->increment($increment);
    }

    public static function getMethodsThatAccessPropertiesOnOtherObjectsInTheSameScope(): Generator
    {
        foreach ((new ReflectionClass(OtherObjectAccessClass::class))->getProperties() as $property) {
            $property->setAccessible(true);

            $propertyName  = $property->getName();
            $realInstance  = new OtherObjectAccessClass();
            $expectedValue = uniqid('', true);

            $property->setValue($realInstance, $expectedValue);

            yield OtherObjectAccessClass::class . '#$' . $propertyName => [
                new OtherObjectAccessClass(),
                $realInstance,
                'get' . ucfirst($propertyName),
                $expectedValue,
                $propertyName,
            ];
        }
    }
}