forked from CopernicaMarketingSoftware/PHP-CPP
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathclassimpl.cpp
1468 lines (1263 loc) · 48 KB
/
classimpl.cpp
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* ClassImpl.cpp
*
* Implementation file for the ClassImpl class
*
* @author Emiel Bruijntjes <[email protected]>
* @copyright 2014 - 2019 Copernica BV
*/
#include "includes.h"
#include <cstring>
/**
* Set up namespace
*/
namespace Php {
/**
* Destructor
*/
ClassImpl::~ClassImpl()
{
// destruct the entries
delete[] _entries;
// free the stored pointer
if (_self) zend_string_release(_self);
}
/**
* @todo refactor so that methods become simpler
*/
/**
* Retrieve our C++ implementation object
* @param entry
* @return ClassImpl
*/
static ClassImpl *self(zend_class_entry *entry)
{
/**
* somebody could have extended this class from PHP userland, in which
* case trying to dereference the doc_comment would result in a disaster
* because it does not point to a class implemented by PHP-CPP at all!
*
* if this happens we need to keep going until we find the object that
* was implemented by us. For this we are going to make the assumption
* that we are the only ones misusing the doc_comment the way we do.
*
* Usually the doc_comment is not set (it equals the nullptr) and if it
* is set, the accompanying doc_comment_len should be non-zero to
* indicate the number of characters in it.
*
* When, however, we use the doc_comment from inside PHP-CPP to store
* the classimpl, we store a null-character (to immediately terminate
* the string, in case PHP tries to read it) and after that the pointer
* and we leave the doc_comment_len at 0.
*/
while (entry->parent && (entry->info.user.doc_comment == nullptr || ZSTR_LEN(entry->info.user.doc_comment) > 0))
{
// we did not create this class entry, but luckily we have a parent
entry = entry->parent;
}
// retrieve the comment (it has a pointer hidden in it to the ClassBase object)
const char *comment = ZSTR_VAL(entry->info.user.doc_comment);
// the first byte of the comment is an empty string (null character), but
// the next bytes contain a pointer to the ClassBase class
return *((ClassImpl **)(comment + 1));
}
/**
* Extended zend_internal_function structure that we use to store an
* instance of the ClassBase object. We need this for static method calls
*/
struct CallData
{
// the internal function is the first member, so
// that it is possible to cast an instance of this
// struct to a zend_internal_function
zend_internal_function func;
// and a pointer to the ClassImpl object
ClassImpl *self;
};
/**
* Handler function that runs the __call function
* @param ... All normal parameters for function calls
*/
void ClassImpl::callMethod(INTERNAL_FUNCTION_PARAMETERS)
{
// retrieve the originally called (and by us allocated) function object
auto *data = (CallData *)execute_data->func;
auto *func = &data->func;
// retrieve the function name
const char *name = ZSTR_VAL(func->function_name);
ClassBase *meta = data->self->_base;
// the data structure was allocated by ourselves in the getMethod or
// getStaticMethod functions, we no longer need it when the function falls
// out of scope
DelayedFree df(data);
// the function could throw an exception
try
{
// construct parameters
ParametersImpl params(getThis(), ZEND_NUM_ARGS());
// retrieve the base object
Base *base = params.object();
// is this a static, or a non-static call?
Php::Value result = base ? meta->callCall(base, name, params) : meta->callCallStatic(name, params);
// return a full copy of the zval, and do not destruct it
RETVAL_ZVAL(result._val, 1, 0);
}
catch (const NotImplemented &exception)
{
// because of the two-step nature, we are going to report the error ourselves
zend_error(E_ERROR, "Undefined method %s", name);
}
catch (Throwable &throwable)
{
// object was not caught by the extension, let it end up in user space
throwable.rethrow();
}
}
/**
* Handler function that runs the __invoke function
* @param ... All normal parameters for function calls
*/
void ClassImpl::callInvoke(INTERNAL_FUNCTION_PARAMETERS)
{
// retrieve the originally called (and by us allocated) function object
auto *data = (CallData *)execute_data->func;
// get self reference
ClassBase *meta = data->self->_base;
// the data structure was allocated by ourselves in the getMethod or
// getStaticMethod functions, we no longer need it when the function falls
// out of scope
DelayedFree df(data);
// the function could throw an exception
try
{
// construct parameters
ParametersImpl params(getThis(), ZEND_NUM_ARGS());
// retrieve the base object
Base *base = params.object();
// call the actual __invoke method on the base object
auto result = meta->callInvoke(base, params);
// return a full copy of the zval, and do not destruct it
RETVAL_ZVAL(result._val, 1, 0);
}
catch (const NotImplemented &exception)
{
// because of the two-step nature, we are going to report the error ourselves
zend_error(E_ERROR, "Function name must be a string");
}
catch (Throwable &throwable)
{
// object was not caught by the extension, let it end up in user space
throwable.rethrow();
}
}
/**
* Method that returns the function definition of the __call function
*
* @param object Pointer to the object from which we want to retrieve the member function
* @param method The method that we want information about
* @param key ???
* @return zend_function
*/
zend_function *ClassImpl::getMethod(zend_object **object, zend_string *method, const zval *key)
{
// something strange about the Zend engine (once more). The structure with
// object-handlers has a get_method and call_method member. When a function is
// called, the get_method function is called first, to retrieve information
// about the method (like the handler that should be called to execute it),
// after that, this returned handler is also called. The call_method property
// of the object_handlers structure however, never gets called. Typical.
// first we'll check if the default handler does not have an implementation,
// in that case the method is probably already implemented as a regular method
auto *defaultFunction = std_object_handlers.get_method(object, method, key);
// did the default implementation do anything?
if (defaultFunction) return defaultFunction;
// retrieve the class entry linked to this object
auto *entry = (*object)->ce;
// this is peculiar behavior of the zend engine, we first are going to dynamically
// allocate memory holding all the properties of the __call method (we initially
// had an implementation here that used a static variable, and that worked too,
// but we'll follow thread safe implementation of the Zend engine here, although
// it is strange to allocate and free memory in one and the same method call (free()
// call happens in call_method())
auto *data = (CallData *)emalloc(sizeof(CallData));
auto *function = &data->func;
// set all properties
function->type = ZEND_INTERNAL_FUNCTION;
function->arg_flags[0] = 0;
function->arg_flags[1] = 0;
function->arg_flags[2] = 0;
function->fn_flags = ZEND_ACC_CALL_VIA_HANDLER;
function->function_name = method;
function->scope = entry;
function->prototype = nullptr;
function->num_args = 0;
function->required_num_args = 0;
function->arg_info = nullptr;
function->handler = &ClassImpl::callMethod;
// store pointer to ourselves
data->self = self(entry);
// done (cast to zend_function* is allowed, because a zend_function is a union
// that has one member being a zend_internal_function)
return (zend_function *)data;
}
/**
* Method that is called right before a static method call is attempted
*
* @param entry The class entry to find the static function in
* @param method The method to get information about
* @param key ???
* @return zend_function
*/
zend_function *ClassImpl::getStaticMethod(zend_class_entry *entry, zend_string *method)
{
// first we'll check if the default handler does not have an implementation,
// in that case the method is probably already implemented as a regular method
auto *defaultFunction = zend_std_get_static_method(entry, method, nullptr);
// did the default implementation do anything?
if (defaultFunction) return defaultFunction;
// just like we did in getMethod() (see comment there) we are going to dynamically
// allocate data holding information about the function
auto *data = (CallData *)emalloc(sizeof(CallData));
auto *function = &data->func;
// set all properties for the function
function->type = ZEND_INTERNAL_FUNCTION;
function->arg_flags[0] = 0;
function->arg_flags[1] = 0;
function->arg_flags[2] = 0;
function->fn_flags = ZEND_ACC_CALL_VIA_HANDLER;
function->function_name = nullptr;
function->scope = nullptr;
function->prototype = nullptr;
function->num_args = 0;
function->required_num_args = 0;
function->arg_info = nullptr;
function->handler = &ClassImpl::callMethod;
// store pointer to ourselves
data->self = self(entry);
// done (cast to zend_function* is allowed, because a zend_function is a union
// that has one member being a zend_internal_function)
return (zend_function *)data;
}
/**
* Method that returns the closure -- this is the __invoke handler!
* @param object
* @param entry_ptr
* @param func
* @param object_ptr
* @return int
*/
int ClassImpl::getClosure(zval *object, zend_class_entry **entry_ptr, zend_function **func, zend_object **object_ptr)
{
// it is really unbelievable how the Zend engine manages to implement every feature
// in a complete different manner. You would expect the __invoke() and the
// __call() functions not to be very different from each other. However, they
// both have a completely different API. This getClosure method is supposed
// to fill the function parameter with all information about the invoke()
// method that is going to get called
// just like we did for getMethod(), we're going to dynamically allocate memory
// with all information about the function
auto *data = (CallData *)emalloc(sizeof(CallData));
auto *function = &data->func;
// we're going to set all properties of the zend_internal_function struct
function->type = ZEND_INTERNAL_FUNCTION;
function->arg_flags[0] = 0;
function->arg_flags[1] = 0;
function->arg_flags[2] = 0;
function->fn_flags = ZEND_ACC_CALL_VIA_HANDLER;
function->function_name = zend_empty_string; // should not be null, as this is free'ed by zend when doing exception handling
function->scope = *entry_ptr;
function->prototype = nullptr;
function->num_args = 0;
function->required_num_args = 0;
function->arg_info = nullptr;
function->handler = &ClassImpl::callInvoke;
// store pointer to ourselves (note that the entry_ptr is useless
// inside this function as it is always uninitialized for some reason)
data->self = self(Z_OBJCE_P(object));
// assign this dynamically allocated variable to the func parameter
// the cast is ok, because zend_internal_function is a member of the
// zend_function union
*func = (zend_function *)data;
// the object_ptr should be filled with the object on which the method is
// called (otherwise the Zend engine tries to call the method statically)
*object_ptr = Z_OBJ_P(object);
// done
return SUCCESS;
};
/**
* Retrieve pointer to our own object handlers
* @return zend_object_handlers
*/
zend_object_handlers *ClassImpl::objectHandlers()
{
// already initialized?
if (_initialized) return &_handlers;
// initialize the handlers
memcpy(&_handlers, &std_object_handlers, sizeof(zend_object_handlers));
// install custom clone function
if (!_base->clonable()) _handlers.clone_obj = nullptr;
else _handlers.clone_obj = &ClassImpl::cloneObject;
// functions for the Countable interface
_handlers.count_elements = &ClassImpl::countElements;
// functions for the ArrayAccess interface
_handlers.write_dimension = &ClassImpl::writeDimension;
_handlers.read_dimension = &ClassImpl::readDimension;
_handlers.has_dimension = &ClassImpl::hasDimension;
_handlers.unset_dimension = &ClassImpl::unsetDimension;
// functions for the magic properties handlers (__get, __set, __isset and __unset)
_handlers.write_property = &ClassImpl::writeProperty;
_handlers.read_property = &ClassImpl::readProperty;
_handlers.has_property = &ClassImpl::hasProperty;
_handlers.unset_property = &ClassImpl::unsetProperty;
// when a method is called (__call and __invoke)
_handlers.get_method = &ClassImpl::getMethod;
_handlers.get_closure = &ClassImpl::getClosure;
// register destructor and deallocator
_handlers.dtor_obj = &ClassImpl::destructObject;
_handlers.free_obj = &ClassImpl::freeObject;
// handler to cast to a different type
_handlers.cast_object = &ClassImpl::cast;
// method to compare two objects
_handlers.compare_objects = &ClassImpl::compare;
// set the offset between our class implementation and
// the zend_object member in the allocated structure
_handlers.offset = ObjectImpl::offset();
// remember that object is now initialized
_initialized = true;
// done
return &_handlers;
}
/**
* Alternative way to retrieve object handlers, given a class entry
* @param entry
* @return zend_object_handlers
*/
zend_object_handlers *ClassImpl::objectHandlers(zend_class_entry *entry)
{
return self(entry)->objectHandlers();
}
/**
* Function to compare two objects
* @param val1
* @param val2
* @return int
*/
int ClassImpl::compare(zval *val1, zval *val2)
{
// prevent exceptions
try
{
// retrieve the class entry linked to this object
auto *entry = Z_OBJCE_P(val1);
// other object must be of the same type
if (entry != Z_OBJCE_P(val2)) throw NotImplemented();
// we need the C++ class meta-information object
ClassBase *meta = self(entry)->_base;
// get the base objects
Base *object1 = ObjectImpl::find(val1)->object();
Base *object2 = ObjectImpl::find(val2)->object();
// run the compare method
return meta->callCompare(object1, object2);
}
catch (const NotImplemented &exception)
{
// it was not implemented, do we have a default?
if (!std_object_handlers.compare_objects) return 1;
// call default
return std_object_handlers.compare_objects(val1, val2);
}
catch (Throwable &throwable)
{
// object was not caught by the extension, let it end up in user space
throwable.rethrow();
// what shall we return here...
return 1;
}
}
/**
* Function to cast the object to a different type
* @param val
* @param retval
* @param type
* @return int
*/
int ClassImpl::cast(zval *val, zval *retval, int type)
{
// get the base c++ object
Base *object = ObjectImpl::find(val)->object();
// retrieve the class entry linked to this object
auto *entry = Z_OBJCE_P(val);
// we need the C++ class meta-information object
ClassBase *meta = self(entry)->_base;
// when the magic function it not implemented, an exception will be thrown,
// and the extension may throw a Php::Exception
try
{
// the result value
Value result;
// check type
switch ((Type)type) {
case Type::Numeric: result = meta->callToInteger(object); break;
case Type::Float: result = meta->callToFloat(object); break;
case Type::Bool: result = meta->callToBool(object); break;
case Type::String: result = meta->callToString(object); break;
default: throw NotImplemented(); break;
}
// @todo do we turn into endless conversion if the __toString object returns 'this' ??
// (and if it does: who cares? If the extension programmer is stupid, why do we have to suffer?)
// overwrite the result
ZVAL_DUP(retval, result._val);
// done
return SUCCESS;
}
catch (const NotImplemented &exception)
{
// is there a default?
if (!std_object_handlers.cast_object) return FAILURE;
// call default
return std_object_handlers.cast_object(val, retval, type);
}
catch (Throwable &throwable)
{
// object was not caught by the extension, let it end up in user space
throwable.rethrow();
// done
return FAILURE;
}
}
/**
* Function that is called to create space for a cloned object
*
* @param val The object to be cloned
* @return zend_object The object to be created
*/
zend_object *ClassImpl::cloneObject(zval *val)
{
// retrieve the class entry linked to this object
auto *entry = Z_OBJCE_P(val);
// we need the C++ class meta-information object
ClassImpl *impl = self(entry);
ClassBase *meta = impl->_base;
// retrieve the old object, which we are going to copy
ObjectImpl *old_object = ObjectImpl::find(val);
// create a new base c++ object
auto *cpp = meta->clone(old_object->object());
// report error on failure (this does not occur because the cloneObject()
// method is only installed as handler when we have seen that there is indeed
// a copy constructor). Because this function is directly called from the
// Zend engine, we can call zend_error() (which does a longjmp()) to throw
// an exception back to the Zend engine)
if (!cpp) zend_error(E_ERROR, "Unable to clone %s", entry->name->val);
// store the object
auto *new_object = new ObjectImpl(entry, cpp, impl->objectHandlers(), 1);
// clone the members (this will also call the __clone() function if the user
// had registered that as a visible method)
zend_objects_clone_members(new_object->php(), old_object->php());
// was a custom clone method installed? If not we call the magic c++ __clone method
if (!entry->clone) meta->callClone(cpp);
// done
return new_object->php();
}
/**
* Function that is used to count the number of elements in the object
*
* If the user has implemented the Countable interface, this method will
* call the count() method
*
* @param val
* @param count
* @return int
*/
int ClassImpl::countElements(zval *object, zend_long *count)
{
// does it implement the countable interface?
Countable *countable = dynamic_cast<Countable*>(ObjectImpl::find(object)->object());
// if it does not implement the Countable interface, we rely on the default implementation
if (countable)
{
// the user function may throw an exception that needs to be processed
try
{
// call the count function
*count = countable->count();
// done
return SUCCESS;
}
catch (Throwable &throwable)
{
// object was not caught by the extension, let it end up in user space
throwable.rethrow();
// unreachable
return FAILURE;
}
}
else
{
// Countable interface was not implemented, check if there is a default
if (!std_object_handlers.count_elements) return FAILURE;
// call default
return std_object_handlers.count_elements(object, count);
}
}
/**
* Function that is called when the object is used as an array in PHP
*
* This is the [] operator in PHP, and mapped to the offsetGet() method
* of the ArrayAccess interface
*
* @param object The object on which it is called
* @param offset The name of the property
* @param type The type of the variable???
* @param rv Pointer to where to store the data
* @return zval
*/
zval *ClassImpl::readDimension(zval *object, zval *offset, int type, zval *rv)
{
// what to do with the type?
//
// the type parameter tells us whether the dimension was read in READ
// mode, WRITE mode, READWRITE mode or UNSET mode.
//
// In 99 out of 100 situations, it is called in regular READ mode (value 0),
// only when it is called from a PHP script that has statements like
// $x =& $object["x"], $object["x"]["y"] = "something" or unset($object["x"]["y"]),
// the type parameter is set to a different value.
//
// But we must ask ourselves the question what we should be doing with such
// cases. Internally, the object most likely has a full native implementation,
// and the property that is returned is just a string or integer or some
// other value, that is temporary WRAPPED into a zval to make it accessible
// from PHP. If someone wants to get a reference to such an internal variable,
// that is in most cases simply impossible.
// does it implement the arrayaccess interface?
ArrayAccess *arrayaccess = dynamic_cast<ArrayAccess*>(ObjectImpl::find(object)->object());
// if it does not implement the ArrayAccess interface, we rely on the default implementation
if (arrayaccess)
{
// the C++ code may throw an exception
try
{
// ArrayAccess is implemented, call function
return toZval(arrayaccess->offsetGet(offset), type, rv);
}
catch (Throwable &throwable)
{
// object was not caught by the extension, let it end up in user space
throwable.rethrow();
// unreachable
return Value(nullptr).detach(false);
}
}
else
{
// ArrayAccess not implemented, check if there is a default handler
if (!std_object_handlers.read_dimension) return nullptr;
// call default
return std_object_handlers.read_dimension(object, offset, type, rv);
}
}
/**
* Function that is called when the object is used as an array in PHP
*
* This is the [] operator in PHP, and mapped to the offsetSet() method
* of the ArrayAccess interface
*
* @param object The object on which it is called
* @param offset The name of the property
* @param value The new value
* @return zval
*/
void ClassImpl::writeDimension(zval *object, zval *offset, zval *value)
{
// does it implement the arrayaccess interface?
ArrayAccess *arrayaccess = dynamic_cast<ArrayAccess*>(ObjectImpl::find(object)->object());
// if it does not implement the ArrayAccess interface, we rely on the default implementation
if (arrayaccess)
{
// method may throw an exception
try
{
// set the value
arrayaccess->offsetSet(offset, value);
}
catch (Throwable &throwable)
{
// object was not caught by the extension, let it end up in user space
throwable.rethrow();
}
}
else
{
// ArrayAccess not interface, check if there is a default handler
if (!std_object_handlers.write_dimension) return;
// call the default
std_object_handlers.write_dimension(object, offset, value);
}
}
/**
* Function that is called when the object is used as an array in PHP
*
* This is the [] operator in PHP, and mapped to the offsetExists() method
* of the ArrayAccess interface
*
* @param object The object on which it is called
* @param member The member to check
* @param check_empty Was this an isset() call, or an empty() call?
* @return bool
*/
int ClassImpl::hasDimension(zval *object, zval *member, int check_empty)
{
// does it implement the arrayaccess interface?
ArrayAccess *arrayaccess = dynamic_cast<ArrayAccess*>(ObjectImpl::find(object)->object());
// if it does not implement the ArrayAccess interface, we rely on the default implementation
if (arrayaccess)
{
// user implemented callbacks could throw an exception
try
{
// check if the member exists
if (!arrayaccess->offsetExists(member)) return false;
// we know for certain that the offset exists, but should we check
// more, like whether the value is empty or not?
if (!check_empty) return true;
// the user wants to know if the property is empty
return empty(arrayaccess->offsetGet(member));
}
catch (Throwable &throwable)
{
// object was not caught by the extension, let it end up in user space
throwable.rethrow();
// unreachable
return false;
}
}
else
{
// ArrayAccess interface is not implemented, check if there is a default handler
if (!std_object_handlers.has_dimension) return 0;
// call default
return std_object_handlers.has_dimension(object, member, check_empty);
}
}
/**
* Function that is called when the object is used as an array in PHP
*
* This is the [] operator in PHP, and mapped to the offsetUnset() method
* of the ArrayAccess interface
*
* @param object The object on which it is called
* @param member The member to remove
*/
void ClassImpl::unsetDimension(zval *object, zval *member)
{
// does it implement the arrayaccess interface?
ArrayAccess *arrayaccess = dynamic_cast<ArrayAccess*>(ObjectImpl::find(object)->object());
// if it does not implement the ArrayAccess interface, we rely on the default implementation
if (arrayaccess)
{
// user implemented code could throw an exception
try
{
// remove the member
arrayaccess->offsetUnset(member);
}
catch (Throwable &throwable)
{
// object was not caught by the extension, let it end up in user space
throwable.rethrow();
}
}
else
{
// ArrayAccess is not implemented, is a default handler available?
if (!std_object_handlers.unset_dimension) return;
// call the default
std_object_handlers.unset_dimension(object, member);
}
}
/**
* Helper method to turn a property into a zval
*
* @param value The value to convert to a zval
* @param type The type of operation (read or write)
* @param rv Pointer to where to store the data
* @return The result (same as the ptr input)
*/
zval *ClassImpl::toZval(Value &&value, int type, zval *rv)
{
// the result zval that needs to be copied over
Zval result;
/**
* Because we do not want the value object to destruct the zval when
* it falls out of scope, we detach the zval from it, if this is a regular
* read operation we can do this right away.
*
* For write operations we need to check the refcount. If the refcount is
* only 1 (meaning the value object has the only reference) we cannot return
* a reference because there _is_ nothing to reference (the value will destruct)
*/
if (type == 0 || value.refcount() <= 1)
{
// first retrieve the value so we can copy it
result = value.detach(true);
}
// this is an editable zval, return a reference to it
else
{
// we're dealing with an editable zval, retrieve a reference variable
result = Value(value.detach(false), true).detach(true);
}
// now copy the value over to the pointer
ZVAL_COPY_VALUE(rv, result);
// return the pointer to the value
return rv;
}
/**
* Function that is called when a property is read
*
* @param object The object on which it is called
* @param offset The name of the property
* @param type The type of the variable???
* @param cache_slot The cache slot used
* @param rv Pointer to where to store the data
* @return val
*/
zval *ClassImpl::readProperty(zval *object, zval *name, int type, void **cache_slot, zval *rv)
{
// what to do with the type?
//
// the type parameter tells us whether the property was read in READ
// mode, WRITE mode, READWRITE mode or UNSET mode.
//
// In 99 out of 100 situations, it is called in regular READ mode (value 0),
// only when it is called from a PHP script that has statements like
// $x =& $object->x, $object->x->y = "something" or unset($object->x->y)
// the type parameter is set to a different value.
//
// But we must ask ourselves the question what we should be doing with such
// cases. Internally, the object most likely has a full native implementation,
// and the property that is returned is just a string or integer or some
// other value, that is temporary WRAPPED into a zval to make it accessible
// from PHP. If someone wants to get a reference to such an internal variable,
// that is in most cases simply impossible.
// retrieve the object and class
Base *base = ObjectImpl::find(object)->object();
// retrieve the class entry linked to this object
auto *entry = Z_OBJCE_P(object);
// we need the C++ class meta-information object
ClassImpl *impl = self(entry);
ClassBase *meta = impl->_base;
// the default implementation throws an exception, so by catching
// the exception we know if the object was implemented by the user or not
try
{
// convert name to a Value object
Value key(name);
// is it a property with a callback?
auto iter = impl->_properties.find(key);
// was it found?
if (iter == impl->_properties.end())
{
// retrieve value from the __get method
return toZval(meta->callGet(base, key), type, rv);
}
else
{
// get the value
return toZval(iter->second->get(base), type, rv);
}
}
catch (const NotImplemented &exception)
{
// __get() function was not overridden by the user
if (!std_object_handlers.read_property) return nullptr;
// call default
return std_object_handlers.read_property(object, name, type, cache_slot, rv);
}
catch (Throwable &throwable)
{
// object was not caught by the extension, let it end up in user space
throwable.rethrow();
// unreachable (or is it?)
return Value(nullptr).detach(false);
}
}
/**
* Function that is called when a property is set / updated
*
* This is the handler for the __set() function, and is called when a property
* is updated.
*
* @param object The object on which it is called
* @param name The name of the property
* @param value The new value
* @param cache_slot The cache slot used
* @return zval
*/
PHP_WRITE_PROP_HANDLER_TYPE ClassImpl::writeProperty(zval *object, zval *name, zval *value, void **cache_slot)
{
// retrieve the object and class
Base *base = ObjectImpl::find(object)->object();
// retrieve the class entry linked to this object
auto *entry = Z_OBJCE_P(object);
// we need the C++ class meta-information object
ClassImpl *impl = self(entry);
ClassBase *meta = impl->_base;
// the default implementation throws an exception, if we catch that
// we know for sure that the user has not overridden the __set method
try
{
// wrap the name
Value key(name);
// check if the property has a callback
auto iter = impl->_properties.find(key);
// is it set?
if (iter == impl->_properties.end())
{
// use the __set method
meta->callSet(base, key, value);
}
else
{
// check if it could be set
if (iter->second->set(base, value)) {
#if PHP_VERSION_ID >= 70400
return value;
#else
return;
#endif
}
// read-only property
zend_error(E_ERROR, "Unable to write to read-only property %s", (const char *)key);
}
}
catch (const NotImplemented &exception)
{
// __set() function was not overridden by user, check if there is a default
if (!std_object_handlers.write_property) {
#if PHP_VERSION_ID >= 70400
return value;
#else
return;
#endif
}
// call the default
std_object_handlers.write_property(object, name, value, cache_slot);
#if PHP_VERSION_ID >= 70400
return value;
#else
return;
#endif
}
catch (Throwable &throwable)
{
// object was not caught by the extension, let it end up in user space
throwable.rethrow();
}
#if PHP_VERSION_ID >= 70400
return value;
#endif
}
/**
* Function that is called to check whether a certain property is set
* for an object
*
* This is the handler for the __isset() function, and is called when a PHP
* script checks if a certain property is set.
*
* The has_set_exists parameter can have the following values:
*
* 0 (has) whether property exists and is not NULL
* 1 (set) whether property exists and is true