blob: 5db87415ff6b6b2b7fc8eab69cfeee1d8723b407 [file] [log] [blame]
Pavel Kvach9f1fb7a2026-03-21 20:45:04 +02001<?php
2
3/*
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
11 *
12 * http://www.apache.org/licenses/LICENSE-2.0
13 *
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
19 * under the License.
20 */
21
22namespace Test\Thrift\Unit\Lib;
23
24trait ReflectionHelper
25{
26 /**
27 * Get a reflection property and make it accessible if needed
28 *
29 * @param object|string $objectOrClass
30 * @param string $propertyName
31 * @return \ReflectionProperty
32 */
33 protected function getAccessibleProperty($objectOrClass, string $propertyName): \ReflectionProperty
34 {
35 $ref = new \ReflectionClass($objectOrClass);
36 $property = $ref->getProperty($propertyName);
37
38 // Only call setAccessible for PHP < 8.1.0
39 if (PHP_VERSION_ID < 80100) {
40 $property->setAccessible(true);
41 }
42
43 return $property;
44 }
45
46 /**
47 * Get the value of a private/protected property
48 *
49 * @param object $object
50 * @param string $propertyName
51 * @return mixed
52 */
53 protected function getPropertyValue($object, string $propertyName)
54 {
55 $property = $this->getAccessibleProperty($object, $propertyName);
56
57 return $property->getValue($object);
58 }
59
60 /**
61 * Set the value of a private/protected property
62 *
63 * @param object $object
64 * @param string $propertyName
65 * @param mixed $value
66 * @return void
67 */
68 protected function setPropertyValue($object, string $propertyName, $value): void
69 {
70 $property = $this->getAccessibleProperty($object, $propertyName);
71 $property->setValue($object, $value);
72 }
73}