summaryrefslogtreecommitdiff
path: root/php/src/IcePHP/Util.cpp
blob: 693d8a5385c4233ce679685f71d17a90c5a8d982 (plain)
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
// **********************************************************************
//
// Copyright (c) 2003-2009 ZeroC, Inc. All rights reserved.
//
// This copy of Ice is licensed to you under the terms described in the
// ICE_LICENSE file included in this distribution.
//
// **********************************************************************

#include <Util.h>
#include <IceUtil/DisableWarnings.h>
#include <algorithm>
#include <ctype.h>

using namespace std;
using namespace IcePHP;

static string
lookupKwd(const string& name)
{
    string lower = lowerCase(name); // PHP is case insensitive.

    //
    // Keyword list. *Must* be kept in alphabetical order.
    //
    static const string keywordList[] = 
    {       
        "abstract", "and", "array", "as", "break", "case", "catch", "class", "clone", "const", "continue", "declare",
        "default", "die", "do", "echo", "else", "elseif", "empty", "enddeclare", "endfor", "endforeach", "endif",
        "endswitch", "endwhile", "eval", "exit", "extends", "final", "for", "foreach", "function", "global", "if",
        "implements", "include", "include_once", "interface", "isset", "list", "new", "or", "print", "private",
        "protected", "public", "require", "require_once", "return", "static", "switch", "this", "throw", "try",
        "unset", "use", "var", "while", "xor"
    };
    bool found =  binary_search(&keywordList[0],
                                &keywordList[sizeof(keywordList) / sizeof(*keywordList)],
                                lower);
    return found ? "_" + name : name;
}

//
// Split a scoped name into its components and return the components as a list of (unscoped) identifiers.
//
static vector<string>
splitScopedName(const string& scoped)
{
    assert(scoped[0] == ':');
    vector<string> ids;
    string::size_type next = 0;
    string::size_type pos;
    while((pos = scoped.find("::", next)) != string::npos)
    {
        pos += 2;
        if(pos != scoped.size())
        {
            string::size_type endpos = scoped.find("::", pos);
            if(endpos != string::npos)
            {
                ids.push_back(scoped.substr(pos, endpos - pos));
            }
        }
        next = pos;
    }
    if(next != scoped.size())
    {
        ids.push_back(scoped.substr(next));
    }
    else
    {
        ids.push_back("");
    }

    return ids;
}

bool
IcePHP::createIdentity(zval* zv, const Ice::Identity& id TSRMLS_DC)
{
    zend_class_entry* cls = findClass("Ice_Identity" TSRMLS_CC);
    assert(cls);

    if(object_init_ex(zv, cls) != SUCCESS)
    {
        php_error_docref(0 TSRMLS_CC, E_ERROR, "unable to initialize Ice::Identity");
        return false;
    }

    zend_update_property_string(cls, zv, "name", sizeof("name") - 1, const_cast<char*>(id.name.c_str()) TSRMLS_CC);
    zend_update_property_string(cls, zv, "category", sizeof("category") - 1,
                                const_cast<char*>(id.category.c_str()) TSRMLS_CC);

    return true;
}

bool
IcePHP::extractIdentity(zval* zv, Ice::Identity& id TSRMLS_DC)
{
    if(Z_TYPE_P(zv) != IS_OBJECT)
    {
        php_error_docref(0 TSRMLS_CC, E_ERROR, "value does not contain an object");
        return false;
    }

    zend_class_entry* cls = findClass("Ice_Identity" TSRMLS_CC);
    assert(cls);

    zend_class_entry* ce = Z_OBJCE_P(zv);
    if(ce != cls)
    {
        php_error_docref(0 TSRMLS_CC, E_ERROR, "expected an identity but received %s", ce->name);
        return false;
    }

    //
    // Category is optional, but name is required.
    //
    void* categoryData = 0;
    void* nameData;
    if(zend_hash_find(Z_OBJPROP_P(zv), "name", sizeof("name"), &nameData) == FAILURE)
    {
        php_error_docref(0 TSRMLS_CC, E_ERROR, "identity value does not contain member `name'");
        return false;
    }
    zend_hash_find(Z_OBJPROP_P(zv), "category", sizeof("category"), &categoryData);
    zval** categoryVal = reinterpret_cast<zval**>(categoryData);
    zval** nameVal = reinterpret_cast<zval**>(nameData);

    if(Z_TYPE_PP(nameVal) != IS_STRING)
    {
        string s = zendTypeToString(Z_TYPE_PP(nameVal));
        php_error_docref(0 TSRMLS_CC, E_ERROR, "expected a string value for identity member `name' but received %s",
                         s.c_str());
        return false;
    }

    if(categoryVal && Z_TYPE_PP(categoryVal) != IS_STRING && Z_TYPE_PP(categoryVal) != IS_NULL)
    {
        string s = zendTypeToString(Z_TYPE_PP(categoryVal));
        php_error_docref(0 TSRMLS_CC, E_ERROR,
                         "expected a string value for identity member `category' but received %s", s.c_str());
        return false;
    }

    id.name = Z_STRVAL_PP(nameVal);
    if(categoryVal && Z_TYPE_PP(categoryVal) == IS_STRING)
    {
        id.category = Z_STRVAL_PP(categoryVal);
    }
    else
    {
        id.category = "";
    }

    return true;
}

bool
IcePHP::createContext(zval* zv, const Ice::Context& ctx TSRMLS_DC)
{
    array_init(zv);
    for(Ice::Context::const_iterator p = ctx.begin(); p != ctx.end(); ++p)
    {
        zval* val;
        MAKE_STD_ZVAL(val);
        ZVAL_STRINGL(val, const_cast<char*>(p->second.c_str()), p->second.length(), 1);
        add_assoc_zval_ex(zv, const_cast<char*>(p->first.c_str()), p->first.length() + 1, val);
    }

    return true;
}

bool
IcePHP::extractContext(zval* zv, Ice::Context& ctx TSRMLS_DC)
{
    if(Z_TYPE_P(zv) != IS_ARRAY)
    {
        string s = zendTypeToString(Z_TYPE_P(zv));
        php_error_docref(0 TSRMLS_CC, E_ERROR, "expected an array for the context argument but received %s",
                         s.c_str());
        return false;
    }

    HashTable* arr = Z_ARRVAL_P(zv);
    void* data;
    HashPosition pos;

    zend_hash_internal_pointer_reset_ex(arr, &pos);
    while(zend_hash_get_current_data_ex(arr, &data, &pos) != FAILURE)
    {
        zval** val = reinterpret_cast<zval**>(data);

        //
        // Get the key (which can be a long or a string).
        //
        char* keyStr;
        uint keyLen;
        ulong keyNum;
        int keyType = zend_hash_get_current_key_ex(arr, &keyStr, &keyLen, &keyNum, 0, &pos);

        //
        // Store the key in a zval, so that we can reuse the PrimitiveMarshaler logic.
        //
        if(keyType != HASH_KEY_IS_STRING)
        {
            php_error_docref(0 TSRMLS_CC, E_ERROR, "context key must be a string");
            return false;
        }

        if(Z_TYPE_PP(val) != IS_STRING)
        {
            php_error_docref(0 TSRMLS_CC, E_ERROR, "context value must be a string");
            return false;
        }

        ctx[keyStr] = Z_STRVAL_PP(val);

        zend_hash_move_forward_ex(arr, &pos);
    }

    return true;
}

#ifdef _WIN32
extern "C"
#endif
static void
dtor_wrapper(void* p)
{
    zval_ptr_dtor(static_cast<zval**>(p));
}

ice_object*
IcePHP::newObject(zend_class_entry* ce TSRMLS_DC)
{
    ice_object* obj;
    zval* tmp;

    obj = static_cast<ice_object*>(emalloc(sizeof(ice_object)));
    obj->zobj.ce = ce;
    obj->zobj.guards = 0;
    obj->ptr = 0;

    obj->zobj.properties = static_cast<HashTable*>(emalloc(sizeof(HashTable)));
    zend_hash_init(obj->zobj.properties, 0, 0, dtor_wrapper, 0);
    zend_hash_copy(obj->zobj.properties, &ce->default_properties, (copy_ctor_func_t) zval_add_ref, &tmp,
                   sizeof(zval*));

    return obj;
}

ice_object*
IcePHP::getObject(zval* zv TSRMLS_DC)
{
    if(!zv)
    {
        php_error_docref(0 TSRMLS_CC, E_ERROR, "method %s() must be invoked on an object",
                         get_active_function_name(TSRMLS_C));
        return 0;
    }

    ice_object* obj = static_cast<ice_object*>(zend_object_store_get_object(zv TSRMLS_CC));
    if(!obj)
    {
        php_error_docref(0 TSRMLS_CC, E_ERROR, "no object found in %s()", get_active_function_name(TSRMLS_C));
        return 0;
    }

    return obj;
}

void
IcePHP::throwException(const IceUtil::Exception& ex TSRMLS_DC)
{
    try
    {
        try
        {
            ex.ice_throw();
        }
        catch(const Ice::TwowayOnlyException& e)
        {
            string name = e.ice_name();
            zend_class_entry* cls = findClassScoped(name TSRMLS_CC);
            if(!cls)
            {
                throw;
            }

            zval* zex;
            MAKE_STD_ZVAL(zex);
            if(object_init_ex(zex, cls) != SUCCESS)
            {
                php_error_docref(0 TSRMLS_CC, E_ERROR, "unable to create exception %s", cls->name);
                return;
            }

            //
            // Set the unknown member.
            //
            zend_update_property_string(cls, zex, "operation", sizeof("operation") - 1,
                                        const_cast<char*>(e.operation.c_str()) TSRMLS_CC);

            //
            // Throw the exception.
            //
            zend_throw_exception_object(zex TSRMLS_CC);
        }
        catch(const Ice::UnknownException& e)
        {
            string name = e.ice_name();
            zend_class_entry* cls = findClassScoped(name TSRMLS_CC);
            if(!cls)
            {
                throw;
            }

            zval* zex;
            MAKE_STD_ZVAL(zex);
            if(object_init_ex(zex, cls) != SUCCESS)
            {
                php_error_docref(0 TSRMLS_CC, E_ERROR, "unable to create exception %s", cls->name);
                return;
            }

            //
            // Set the unknown member.
            //
            zend_update_property_string(cls, zex, "unknown", sizeof("unknown") - 1,
                                        const_cast<char*>(e.unknown.c_str()) TSRMLS_CC);

            //
            // Throw the exception.
            //
            zend_throw_exception_object(zex TSRMLS_CC);
        }
        catch(const Ice::RequestFailedException& e)
        {
            string name = e.ice_name();
            zend_class_entry* cls = findClassScoped(name TSRMLS_CC);
            if(!cls)
            {
                throw;
            }

            zval* zex;
            MAKE_STD_ZVAL(zex);
            if(object_init_ex(zex, cls) != SUCCESS)
            {
                php_error_docref(0 TSRMLS_CC, E_ERROR, "unable to create exception %s", cls->name);
                return;
            }

            //
            // Set the id member.
            //
            zval* id;
            MAKE_STD_ZVAL(id);
            if(!createIdentity(id, e.id TSRMLS_CC))
            {
                return;
            }
            zend_update_property(cls, zex, "id", sizeof("id") - 1, id TSRMLS_CC);

            //
            // Set the facet member.
            //
            zval* facet;
            MAKE_STD_ZVAL(facet);
            ZVAL_STRINGL(facet, const_cast<char*>(e.facet.c_str()), e.facet.length(), 1);
            zend_update_property(cls, zex, "facet", sizeof("facet") - 1, facet TSRMLS_CC);

            //
            // Set the operation member.
            //
            zend_update_property_string(cls, zex, "operation", sizeof("operation") - 1,
                                        const_cast<char*>(e.operation.c_str()) TSRMLS_CC);

            //
            // Throw the exception.
            //
            zend_throw_exception_object(zex TSRMLS_CC);
        }
        catch(const Ice::NoObjectFactoryException& e)
        {
            string name = e.ice_name();
            zend_class_entry* cls = findClassScoped(name TSRMLS_CC);
            if(!cls)
            {
                throw;
            }

            zval* zex;
            MAKE_STD_ZVAL(zex);
            if(object_init_ex(zex, cls) != SUCCESS)
            {
                php_error_docref(0 TSRMLS_CC, E_ERROR, "unable to create exception %s", cls->name);
                return;
            }

            //
            // Set the reason member.
            //
            zend_update_property_string(cls, zex, "reason", sizeof("reason") - 1,
                                        const_cast<char*>(e.reason.c_str()) TSRMLS_CC);

            //
            // Set the type member.
            //
            zend_update_property_string(cls, zex, "type", sizeof("type") - 1, const_cast<char*>(e.type.c_str())
                                        TSRMLS_CC);

            //
            // Throw the exception.
            //
            zend_throw_exception_object(zex TSRMLS_CC);
        }
        catch(const Ice::UnexpectedObjectException& e)
        {
            string name = e.ice_name();
            zend_class_entry* cls = findClassScoped(name TSRMLS_CC);
            if(!cls)
            {
                throw;
            }

            zval* zex;
            MAKE_STD_ZVAL(zex);
            if(object_init_ex(zex, cls) != SUCCESS)
            {
                php_error_docref(0 TSRMLS_CC, E_ERROR, "unable to create exception %s", cls->name);
                return;
            }

            //
            // Set the reason member.
            //
            zend_update_property_string(cls, zex, "reason", sizeof("reason") - 1,
                                        const_cast<char*>(e.reason.c_str()) TSRMLS_CC);

            //
            // Set the type and exptected type members.
            //
            zend_update_property_string(cls, zex, "type", sizeof("type") - 1, const_cast<char*>(e.type.c_str())
                                        TSRMLS_CC);
            zend_update_property_string(cls, zex, "expectedType", sizeof("expectedType") - 1,
                                        const_cast<char*>(e.expectedType.c_str()) TSRMLS_CC);

            //
            // Throw the exception.
            //
            zend_throw_exception_object(zex TSRMLS_CC);
        }
        catch(const Ice::MarshalException& e)
        {
            string name = e.ice_name();
            zend_class_entry* cls = findClassScoped(name TSRMLS_CC);
            if(!cls)
            {
                throw;
            }

            zval* zex;
            MAKE_STD_ZVAL(zex);
            if(object_init_ex(zex, cls) != SUCCESS)
            {
                php_error_docref(0 TSRMLS_CC, E_ERROR, "unable to create exception %s", cls->name);
                return;
            }

            //
            // Set the reason member.
            //
            zend_update_property_string(cls, zex, "reason", sizeof("reason") - 1,
                                        const_cast<char*>(e.reason.c_str()) TSRMLS_CC);

            //
            // Throw the exception.
            //
            zend_throw_exception_object(zex TSRMLS_CC);
        }
    }
    catch(const Ice::LocalException& e)
    {
        zval* zex;
        MAKE_STD_ZVAL(zex);

        //
        // See if we have a PHP class for the exception, otherwise raise UnknownLocalException.
        //
        string name = e.ice_name();
        zend_class_entry* cls = findClassScoped(name TSRMLS_CC);
        if(cls)
        {
            if(object_init_ex(zex, cls) != SUCCESS)
            {
                php_error_docref(0 TSRMLS_CC, E_ERROR, "unable to create exception %s", cls->name);
                return;
            }
        }
        else
        {
            cls = findClass("Ice_UnknownLocalException" TSRMLS_CC);
            if(!cls)
            {
                php_error_docref(0 TSRMLS_CC, E_ERROR, "unable to find class Ice_UnknownLocalException");
                return;
            }

            if(object_init_ex(zex, cls) != SUCCESS)
            {
                php_error_docref(0 TSRMLS_CC, E_ERROR, "unable to create exception %s", cls->name);
                return;
            }

            //
            // Set the unknown member.
            //
            ostringstream ostr;
            e.ice_print(ostr);
            string str = ostr.str();
            zend_update_property_string(cls, zex, "unknown", sizeof("unknown") - 1,
                                        const_cast<char*>(str.c_str()) TSRMLS_CC);
        }

        //
        // Throw the exception.
        //
        zend_throw_exception_object(zex TSRMLS_CC);
    }
    catch(const Ice::UserException&)
    {
        assert(false);
    }
    catch(const IceUtil::Exception& e)
    {
        ostringstream ostr;
        e.ice_print(ostr);
        php_error_docref(0 TSRMLS_CC, E_ERROR, "exception: %s", ostr.str().c_str());
    }
}

zend_class_entry*
IcePHP::findClass(const string& flat TSRMLS_DC)
{
    zend_class_entry** result;
    string lower = lowerCase(flat);
    if(zend_lookup_class(const_cast<char*>(lower.c_str()), lower.length(), &result TSRMLS_CC) == FAILURE)
    {
        return 0;
    }
    return *result;
}

zend_class_entry*
IcePHP::findClassScoped(const string& scoped TSRMLS_DC)
{
    return findClass(flatten(scoped) TSRMLS_CC);
}

string
IcePHP::lowerCase(const string& s)
{
    string result(s);
    transform(result.begin(), result.end(), result.begin(), ::tolower);
    return result;
}

string
IcePHP::flatten(const string& scoped)
{
    string result = scoped;
    if(result.find("::") == 0)
    {
        result.erase(0, 2);
    }

    string::size_type pos;
    while((pos = result.find("::")) != string::npos)
    {
        result.replace(pos, 2, "_");
    }

    return fixIdent(result);
}

string
IcePHP::fixIdent(const string& ident)
{
    if(ident[0] != ':')
    {
        return lookupKwd(ident);
    }
    vector<string> ids = splitScopedName(ident);
    transform(ids.begin(), ids.end(), ids.begin(), ptr_fun(lookupKwd));
    stringstream result;
    for(vector<string>::const_iterator i = ids.begin(); i != ids.end(); ++i)
    {
        result << "::" + *i;
    }
    return result.str();
}

std::string
IcePHP::zendTypeToString(int type)
{
    string result;

    switch(type)
    {
    case IS_NULL:
        result = "null";
        break;

    case IS_LONG:
        result = "long";
        break;

    case IS_DOUBLE:
        result = "double";
        break;

    case IS_STRING:
        result = "string";
        break;

    case IS_ARRAY:
        result = "array";
        break;

    case IS_OBJECT:
        result = "object";
        break;

    case IS_BOOL:
        result = "bool";
        break;

    default:
        result = "unknown";
        break;
    }

    return result;
}

bool
IcePHP::isNativeKey(const Slice::TypePtr& type)
{
    //
    // PHP's native associative array supports only integer and string types for the key.
    // For Slice dictionaries that meet this criteria, we use the native array type.
    //
    Slice::BuiltinPtr b = Slice::BuiltinPtr::dynamicCast(type);
    if(b)
    {
        switch(b->kind())
        {
        case Slice::Builtin::KindByte:
        case Slice::Builtin::KindBool: // We allow bool even though PHP doesn't support it directly.
        case Slice::Builtin::KindShort:
        case Slice::Builtin::KindInt:
        case Slice::Builtin::KindLong:
        case Slice::Builtin::KindString:
            return true;

        case Slice::Builtin::KindFloat:
        case Slice::Builtin::KindDouble:
        case Slice::Builtin::KindObject:
        case Slice::Builtin::KindObjectProxy:
        case Slice::Builtin::KindLocalObject:
            break;
        }
    }

    return false;
}

bool
IcePHP::checkClass(zend_class_entry* ce, zend_class_entry* base)
{
    while(ce)
    {
        if(ce == base)
        {
            return true;
        }

        for(zend_uint i = 0; i < ce->num_interfaces; ++i)
        {
            if(checkClass(ce->interfaces[i], base))
            {
                return true;
            }
        }

        ce = ce->parent;
    }

    return false;
}