v8js_convert.cc 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. /*
  2. +----------------------------------------------------------------------+
  3. | PHP Version 5 |
  4. +----------------------------------------------------------------------+
  5. | Copyright (c) 1997-2013 The PHP Group |
  6. +----------------------------------------------------------------------+
  7. | http://www.opensource.org/licenses/mit-license.php MIT License |
  8. +----------------------------------------------------------------------+
  9. | Author: Jani Taskinen <[email protected]> |
  10. | Author: Patrick Reilly <[email protected]> |
  11. +----------------------------------------------------------------------+
  12. */
  13. /* $Id$ */
  14. #ifdef HAVE_CONFIG_H
  15. #include "config.h"
  16. #endif
  17. extern "C" {
  18. #include "php.h"
  19. #include "ext/date/php_date.h"
  20. #include "zend_interfaces.h"
  21. #include "zend_closures.h"
  22. }
  23. #include "php_v8js_macros.h"
  24. #include <v8.h>
  25. #include <stdexcept>
  26. #if PHP_V8_API_VERSION < 3022000
  27. /* CopyablePersistentTraits is only part of V8 from 3.22.0 on,
  28. to be compatible with lower versions add our own (compatible) version. */
  29. namespace v8 {
  30. template<class T>
  31. struct CopyablePersistentTraits {
  32. typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
  33. static const bool kResetInDestructor = true;
  34. template<class S, class M>
  35. #if PHP_V8_API_VERSION >= 3021015
  36. static V8_INLINE void Copy(const Persistent<S, M>& source,
  37. CopyablePersistent* dest)
  38. #else
  39. V8_INLINE(static void Copy(const Persistent<S, M>& source,
  40. CopyablePersistent* dest))
  41. #endif
  42. {
  43. // do nothing, just allow copy
  44. }
  45. };
  46. }
  47. #endif
  48. typedef std::pair<struct php_v8js_ctx *, const char *> TemplateCacheKey;
  49. typedef v8::Persistent<v8::FunctionTemplate, v8::CopyablePersistentTraits<v8::FunctionTemplate> > TemplateCacheEntry;
  50. typedef std::map<TemplateCacheKey, TemplateCacheEntry> TemplateCache;
  51. /* Callback for PHP methods and functions */
  52. static void php_v8js_call_php_func(zval *value, zend_class_entry *ce, zend_function *method_ptr, v8::Isolate *isolate, const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  53. {
  54. v8::Handle<v8::Value> return_value;
  55. zend_fcall_info fci;
  56. zend_fcall_info_cache fcc;
  57. zval fname, *retval_ptr = NULL, **argv = NULL;
  58. zend_uint argc = info.Length(), min_num_args = 0, max_num_args = 0;
  59. char *error;
  60. int error_len, i, flags = V8JS_FLAG_NONE;
  61. /* Set parameter limits */
  62. min_num_args = method_ptr->common.required_num_args;
  63. max_num_args = method_ptr->common.num_args;
  64. /* Function name to call */
  65. ZVAL_STRING(&fname, method_ptr->common.function_name, 0);
  66. /* zend_fcall_info */
  67. fci.size = sizeof(fci);
  68. fci.function_table = &ce->function_table;
  69. fci.function_name = &fname;
  70. fci.symbol_table = NULL;
  71. fci.object_ptr = value;
  72. fci.retval_ptr_ptr = &retval_ptr;
  73. fci.param_count = 0;
  74. /* Check for passed vs required number of arguments */
  75. if (argc < min_num_args)
  76. {
  77. error_len = spprintf(&error, 0,
  78. "%s::%s() expects %s %d parameter%s, %d given",
  79. ce->name,
  80. method_ptr->common.function_name,
  81. min_num_args == max_num_args ? "exactly" : argc < min_num_args ? "at least" : "at most",
  82. argc < min_num_args ? min_num_args : max_num_args,
  83. (argc < min_num_args ? min_num_args : max_num_args) == 1 ? "" : "s",
  84. argc);
  85. return_value = V8JS_THROW(TypeError, error, error_len);
  86. if (ce == zend_ce_closure) {
  87. efree(const_cast<char*>(method_ptr->internal_function.function_name));
  88. efree(method_ptr);
  89. }
  90. efree(error);
  91. info.GetReturnValue().Set(return_value);
  92. return;
  93. }
  94. /* Convert parameters passed from V8 */
  95. if (argc) {
  96. flags = V8JS_GLOBAL_GET_FLAGS();
  97. fci.params = (zval ***) safe_emalloc(argc, sizeof(zval **), 0);
  98. argv = (zval **) safe_emalloc(argc, sizeof(zval *), 0);
  99. for (i = 0; i < argc; i++) {
  100. MAKE_STD_ZVAL(argv[i]);
  101. if (v8js_to_zval(info[i], argv[i], flags, isolate TSRMLS_CC) == FAILURE) {
  102. fci.param_count++;
  103. error_len = spprintf(&error, 0, "converting parameter #%d passed to %s() failed", i + 1, method_ptr->common.function_name);
  104. return_value = V8JS_THROW(Error, error, error_len);
  105. efree(error);
  106. goto failure;
  107. }
  108. fci.params[fci.param_count++] = &argv[i];
  109. }
  110. } else {
  111. fci.params = NULL;
  112. }
  113. fci.no_separation = 1;
  114. /* zend_fcall_info_cache */
  115. fcc.initialized = 1;
  116. fcc.function_handler = method_ptr;
  117. fcc.calling_scope = ce;
  118. fcc.called_scope = ce;
  119. fcc.object_ptr = value;
  120. /* Call the method */
  121. zend_call_function(&fci, &fcc TSRMLS_CC);
  122. failure:
  123. /* Cleanup */
  124. if (argc) {
  125. for (i = 0; i < fci.param_count; i++) {
  126. zval_ptr_dtor(&argv[i]);
  127. }
  128. efree(argv);
  129. efree(fci.params);
  130. }
  131. if (retval_ptr != NULL) {
  132. return_value = zval_to_v8js(retval_ptr, isolate TSRMLS_CC);
  133. zval_ptr_dtor(&retval_ptr);
  134. } else {
  135. return_value = V8JS_NULL;
  136. }
  137. info.GetReturnValue().Set(return_value);
  138. }
  139. /* }}} */
  140. /* Callback for PHP methods and functions */
  141. static void php_v8js_php_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  142. {
  143. zval *value = reinterpret_cast<zval *>(info.This()->GetAlignedPointerFromInternalField(0));
  144. v8::Isolate *isolate = reinterpret_cast<v8::Isolate *>(info.This()->GetAlignedPointerFromInternalField(1));
  145. zend_function *method_ptr;
  146. zend_class_entry *ce = Z_OBJCE_P(value);
  147. TSRMLS_FETCH();
  148. /* Set method_ptr from v8::External or fetch the closure invoker */
  149. if (!info.Data().IsEmpty() && info.Data()->IsExternal()) {
  150. method_ptr = static_cast<zend_function *>(v8::External::Cast(*info.Data())->Value());
  151. } else {
  152. method_ptr = zend_get_closure_invoke_method(value TSRMLS_CC);
  153. }
  154. return php_v8js_call_php_func(value, ce, method_ptr, isolate, info);
  155. }
  156. /* Callback for PHP constructor calls */
  157. static void php_v8js_construct_callback(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  158. {
  159. v8::Isolate *isolate = v8::Isolate::GetCurrent();
  160. info.GetReturnValue().Set(V8JS_UNDEFINED);
  161. // @todo assert constructor call
  162. v8::Handle<v8::Object> newobj = info.This();
  163. zval *value;
  164. TSRMLS_FETCH();
  165. if (!info.IsConstructCall()) {
  166. return;
  167. }
  168. if (info[0]->IsExternal()) {
  169. // Object created by v8js in php_v8js_hash_to_jsobj, PHP object passed as v8::External.
  170. value = static_cast<zval *>(v8::External::Cast(*info[0])->Value());
  171. } else {
  172. // Object created from JavaScript context. Need to create PHP object first.
  173. zend_class_entry *ce = static_cast<zend_class_entry *>(v8::External::Cast(*info.Data())->Value());
  174. zend_function *ctor_ptr = ce->constructor;
  175. // Check access on __construct function, if any
  176. if (ctor_ptr != NULL && (ctor_ptr->common.fn_flags & ZEND_ACC_PUBLIC) == 0) {
  177. info.GetReturnValue().Set(v8::ThrowException(v8::String::New("Call to protected __construct() not allowed")));
  178. return;
  179. }
  180. MAKE_STD_ZVAL(value);
  181. object_init_ex(value, ce TSRMLS_CC);
  182. // Call __construct function
  183. if (ctor_ptr != NULL) {
  184. php_v8js_call_php_func(value, ce, ctor_ptr, isolate, info);
  185. }
  186. }
  187. newobj->SetAlignedPointerInInternalField(0, value);
  188. newobj->SetAlignedPointerInInternalField(1, (void *) isolate);
  189. }
  190. /* }}} */
  191. static int _php_v8js_is_assoc_array(HashTable *myht TSRMLS_DC) /* {{{ */
  192. {
  193. int i;
  194. char *key;
  195. ulong index, idx = 0;
  196. uint key_len;
  197. HashPosition pos;
  198. zend_hash_internal_pointer_reset_ex(myht, &pos);
  199. for (;; zend_hash_move_forward_ex(myht, &pos)) {
  200. i = zend_hash_get_current_key_ex(myht, &key, &key_len, &index, 0, &pos);
  201. if (i == HASH_KEY_NON_EXISTANT)
  202. break;
  203. if (i == HASH_KEY_IS_STRING || index != idx) {
  204. return 1;
  205. }
  206. idx++;
  207. }
  208. return 0;
  209. }
  210. /* }}} */
  211. static void php_v8js_property_caller(const v8::FunctionCallbackInfo<v8::Value>& info) /* {{{ */
  212. {
  213. v8::Local<v8::Object> self = info.Holder();
  214. v8::Local<v8::String> cname = info.Callee()->GetName()->ToString();
  215. v8::Local<v8::Value> value;
  216. v8::Local<v8::String> cb_func = v8::Local<v8::String>::Cast(info.Data());
  217. value = self->GetHiddenValue(cb_func);
  218. if (!value.IsEmpty() && value->IsFunction())
  219. {
  220. int argc = info.Length(), i = 0;
  221. v8::Local<v8::Value> *argv = new v8::Local<v8::Value>[argc];
  222. v8::Local<v8::Function> cb = v8::Local<v8::Function>::Cast(value);
  223. if (cb_func->Equals(V8JS_SYM(ZEND_INVOKE_FUNC_NAME))) {
  224. for (; i < argc; ++i) {
  225. argv[i] = info[i];
  226. }
  227. value = cb->Call(self, argc, argv);
  228. }
  229. else /* __call() */
  230. {
  231. v8::Local<v8::Array> argsarr = v8::Array::New(argc);
  232. for (; i < argc; ++i) {
  233. argsarr->Set(i, info[i]);
  234. }
  235. v8::Local<v8::Value> argsv[2] = { cname, argsarr };
  236. value = cb->Call(self, 2, argsv);
  237. }
  238. }
  239. if (info.IsConstructCall()) {
  240. if (!value.IsEmpty() && !value->IsNull()) {
  241. info.GetReturnValue().Set(value);
  242. return;
  243. }
  244. info.GetReturnValue().Set(self);
  245. return;
  246. }
  247. info.GetReturnValue().Set(value);
  248. }
  249. /* }}} */
  250. static void php_v8js_property_getter(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Value> &info) /* {{{ */
  251. {
  252. v8::Local<v8::Object> self = info.Holder();
  253. v8::Local<v8::Value> value;
  254. v8::Local<v8::Function> cb;
  255. /* Check first if JS object has the named property */
  256. value = self->GetRealNamedProperty(property);
  257. if (!value.IsEmpty()) {
  258. info.GetReturnValue().Set(value);
  259. return;
  260. }
  261. /* If __get() is set for PHP object, call it */
  262. value = self->GetHiddenValue(V8JS_SYM(ZEND_GET_FUNC_NAME));
  263. if (!value.IsEmpty() && value->IsFunction()) {
  264. cb = v8::Local<v8::Function>::Cast(value);
  265. v8::Local<v8::Value> argv[1] = {property};
  266. value = cb->Call(self, 1, argv);
  267. }
  268. /* If __get() does not exist or returns NULL, create new function with callback for __call() */
  269. if ((value.IsEmpty() || value->IsNull()) && info.Data()->IsTrue()) {
  270. v8::Local<v8::FunctionTemplate> cb_t = v8::FunctionTemplate::New(php_v8js_property_caller, V8JS_SYM(ZEND_CALL_FUNC_NAME));
  271. cb = cb_t->GetFunction();
  272. cb->SetName(property);
  273. info.GetReturnValue().Set(cb);
  274. return;
  275. }
  276. info.GetReturnValue().Set(value);
  277. }
  278. /* }}} */
  279. static void php_v8js_property_query(v8::Local<v8::String> property, const v8::PropertyCallbackInfo<v8::Integer> &info) /* {{{ */
  280. {
  281. v8::Local<v8::Object> self = info.Holder();
  282. v8::Local<v8::Value> value;
  283. /* Return early if property is set in JS object */
  284. if (self->HasRealNamedProperty(property)) {
  285. info.GetReturnValue().Set(V8JS_INT(v8::ReadOnly));
  286. return;
  287. }
  288. value = self->GetHiddenValue(V8JS_SYM(ZEND_ISSET_FUNC_NAME));
  289. if (!value.IsEmpty() && value->IsFunction()) {
  290. v8::Local<v8::Function> cb = v8::Local<v8::Function>::Cast(value);
  291. v8::Local<v8::Value> argv[1] = {property};
  292. value = cb->Call(self, 1, argv);
  293. }
  294. info.GetReturnValue().Set((!value.IsEmpty() && value->IsTrue()) ? V8JS_INT(v8::ReadOnly) : v8::Local<v8::Integer>());
  295. }
  296. /* }}} */
  297. /* These are not defined by Zend */
  298. #define ZEND_WAKEUP_FUNC_NAME "__wakeup"
  299. #define ZEND_SLEEP_FUNC_NAME "__sleep"
  300. #define ZEND_SET_STATE_FUNC_NAME "__set_state"
  301. #define IS_MAGIC_FUNC(mname) \
  302. ((key_len == sizeof(mname)) && \
  303. !strncasecmp(key, mname, key_len - 1))
  304. #define PHP_V8JS_CALLBACK(mptr) \
  305. v8::FunctionTemplate::New(php_v8js_php_callback, v8::External::New(mptr))->GetFunction()
  306. static void php_v8js_weak_object_callback(v8::Isolate *isolate, v8::Persistent<v8::Object> *object, zval *value)
  307. {
  308. if (READY_TO_DESTROY(value)) {
  309. zval_dtor(value);
  310. FREE_ZVAL(value);
  311. } else {
  312. Z_DELREF_P(value);
  313. }
  314. v8::V8::AdjustAmountOfExternalAllocatedMemory(-1024);
  315. object->Dispose();
  316. }
  317. static v8::Handle<v8::Value> php_v8js_hash_to_jsobj(zval *value, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  318. {
  319. v8::Handle<v8::Object> newobj;
  320. int i;
  321. char *key = NULL;
  322. ulong index;
  323. uint key_len;
  324. HashTable *myht;
  325. HashPosition pos;
  326. zend_class_entry *ce = NULL;
  327. zend_function *method_ptr, *call_ptr = NULL, *get_ptr = NULL, *invoke_ptr = NULL, *isset_ptr = NULL;
  328. if (Z_TYPE_P(value) == IS_ARRAY) {
  329. myht = HASH_OF(value);
  330. } else {
  331. myht = Z_OBJPROP_P(value);
  332. ce = Z_OBJCE_P(value);
  333. }
  334. /* Prevent recursion */
  335. if (myht && myht->nApplyCount > 1) {
  336. return V8JS_NULL;
  337. }
  338. /* Object methods */
  339. if (ce == php_ce_v8_function) {
  340. php_v8js_object *c = (php_v8js_object *) zend_object_store_get_object(value TSRMLS_CC);
  341. v8::Local<v8::Value> v8obj = v8::Local<v8::Value>::New(isolate, c->v8obj);
  342. return v8obj;
  343. } else if (ce) {
  344. php_v8js_ctx *ctx = (php_v8js_ctx *) isolate->GetData();
  345. v8::Local<v8::FunctionTemplate> new_tpl;
  346. bool cached_tpl = true;
  347. static TemplateCache tpl_map;
  348. try {
  349. new_tpl = v8::Local<v8::FunctionTemplate>::New
  350. (isolate, tpl_map.at(std::make_pair(ctx, ce->name)));
  351. }
  352. catch (const std::out_of_range &) {
  353. cached_tpl = false;
  354. /* No cached v8::FunctionTemplate available as of yet, create one. */
  355. new_tpl = v8::FunctionTemplate::New();
  356. new_tpl->SetClassName(V8JS_STRL(ce->name, ce->name_length));
  357. new_tpl->InstanceTemplate()->SetInternalFieldCount(2);
  358. v8::Handle<v8::Value> wrapped_ce = v8::External::New(ce);
  359. new_tpl->SetCallHandler(php_v8js_construct_callback, wrapped_ce);
  360. if (ce == zend_ce_closure) {
  361. /* Got a closure, mustn't cache ... */
  362. new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(php_v8js_php_callback);
  363. } else {
  364. /* Add new v8::FunctionTemplate to tpl_map, as long as it is not a closure. */
  365. TemplateCacheEntry tce(isolate, new_tpl);
  366. tpl_map[std::make_pair(ctx, ce->name)] = tce;
  367. }
  368. }
  369. if (ce != zend_ce_closure) {
  370. /* Attach object methods to the instance template. */
  371. zend_hash_internal_pointer_reset_ex(&ce->function_table, &pos);
  372. for (;; zend_hash_move_forward_ex(&ce->function_table, &pos)) {
  373. if (zend_hash_get_current_key_ex(&ce->function_table, &key, &key_len, &index, 0, &pos) != HASH_KEY_IS_STRING ||
  374. zend_hash_get_current_data_ex(&ce->function_table, (void **) &method_ptr, &pos) == FAILURE
  375. ) {
  376. break;
  377. }
  378. if ((method_ptr->common.fn_flags & ZEND_ACC_PUBLIC) && /* Allow only public methods */
  379. (method_ptr->common.fn_flags & ZEND_ACC_CTOR) == 0 && /* ..and no __construct() */
  380. (method_ptr->common.fn_flags & ZEND_ACC_DTOR) == 0 && /* ..or __destruct() */
  381. (method_ptr->common.fn_flags & ZEND_ACC_CLONE) == 0 /* ..or __clone() functions */
  382. ) {
  383. /* Override native toString() with __tostring() if it is set in passed object */
  384. if (!cached_tpl && IS_MAGIC_FUNC(ZEND_TOSTRING_FUNC_NAME)) {
  385. new_tpl->InstanceTemplate()->Set(V8JS_SYM("toString"), PHP_V8JS_CALLBACK(method_ptr));
  386. /* TODO: __set(), __unset() disabled as JS is not allowed to modify the passed PHP object yet.
  387. * __sleep(), __wakeup(), __set_state() are always ignored */
  388. } else if (
  389. IS_MAGIC_FUNC(ZEND_CALLSTATIC_FUNC_NAME)|| /* TODO */
  390. IS_MAGIC_FUNC(ZEND_SLEEP_FUNC_NAME) ||
  391. IS_MAGIC_FUNC(ZEND_WAKEUP_FUNC_NAME) ||
  392. IS_MAGIC_FUNC(ZEND_SET_STATE_FUNC_NAME) ||
  393. IS_MAGIC_FUNC(ZEND_SET_FUNC_NAME) ||
  394. IS_MAGIC_FUNC(ZEND_UNSET_FUNC_NAME)
  395. ) {
  396. /* Register all magic function as hidden with lowercase name */
  397. } else if (IS_MAGIC_FUNC(ZEND_GET_FUNC_NAME)) {
  398. get_ptr = method_ptr;
  399. } else if (IS_MAGIC_FUNC(ZEND_CALL_FUNC_NAME)) {
  400. call_ptr = method_ptr;
  401. } else if (IS_MAGIC_FUNC(ZEND_INVOKE_FUNC_NAME)) {
  402. invoke_ptr = method_ptr;
  403. } else if (IS_MAGIC_FUNC(ZEND_ISSET_FUNC_NAME)) {
  404. isset_ptr = method_ptr;
  405. } else if (!cached_tpl) {
  406. new_tpl->InstanceTemplate()->Set(V8JS_STR(method_ptr->common.function_name), PHP_V8JS_CALLBACK(method_ptr), v8::ReadOnly);
  407. }
  408. }
  409. }
  410. if (!cached_tpl) {
  411. /* Only register getter, etc. when they're set in PHP side */
  412. if (call_ptr || get_ptr || isset_ptr)
  413. {
  414. /* Set __get() handler which acts also as __call() proxy */
  415. new_tpl->InstanceTemplate()->SetNamedPropertyHandler(
  416. php_v8js_property_getter, /* getter */
  417. 0, /* setter */
  418. isset_ptr ? php_v8js_property_query : 0, /* query */
  419. 0, /* deleter */
  420. 0, /* enumerator */
  421. V8JS_BOOL(call_ptr ? true : false)
  422. );
  423. }
  424. /* __invoke() handler */
  425. if (invoke_ptr) {
  426. new_tpl->InstanceTemplate()->SetCallAsFunctionHandler(php_v8js_property_caller, V8JS_SYM(ZEND_INVOKE_FUNC_NAME));
  427. }
  428. }
  429. }
  430. // Increase the reference count of this value because we're storing it internally for use later
  431. // See https://github.com/preillyme/v8js/issues/6
  432. Z_ADDREF_P(value);
  433. // Since we got to decrease the reference count again, in case v8 garbage collector
  434. // decides to dispose the JS object, we add a weak persistent handle and register
  435. // a callback function that removes the reference.
  436. v8::Handle<v8::Value> external = v8::External::New(value);
  437. v8::Persistent<v8::Object> persist_newobj(isolate, new_tpl->GetFunction()->NewInstance(1, &external));
  438. persist_newobj.MakeWeak(value, php_v8js_weak_object_callback);
  439. // Just tell v8 that we're allocating some external memory
  440. // (for the moment we just always tell 1k instead of trying to find out actual values)
  441. v8::V8::AdjustAmountOfExternalAllocatedMemory(1024);
  442. newobj = v8::Local<v8::Object>::New(isolate, persist_newobj);
  443. if (ce != zend_ce_closure) {
  444. // These unfortunately cannot be attached to the template, hence we have to put them
  445. // on each and every object instance manually.
  446. if (call_ptr) {
  447. newobj->SetHiddenValue(V8JS_SYM(ZEND_CALL_FUNC_NAME), PHP_V8JS_CALLBACK(call_ptr));
  448. }
  449. if (get_ptr) {
  450. newobj->SetHiddenValue(V8JS_SYM(ZEND_GET_FUNC_NAME), PHP_V8JS_CALLBACK(get_ptr));
  451. }
  452. if (invoke_ptr) {
  453. newobj->SetHiddenValue(V8JS_SYM(ZEND_INVOKE_FUNC_NAME), PHP_V8JS_CALLBACK(invoke_ptr));
  454. }
  455. if (isset_ptr) {
  456. newobj->SetHiddenValue(V8JS_SYM(ZEND_ISSET_FUNC_NAME), PHP_V8JS_CALLBACK(isset_ptr));
  457. }
  458. }
  459. } else {
  460. v8::Local<v8::FunctionTemplate> new_tpl = v8::FunctionTemplate::New(); // @todo re-use template likewise
  461. new_tpl->SetClassName(V8JS_SYM("Array"));
  462. newobj = new_tpl->InstanceTemplate()->NewInstance();
  463. }
  464. /* Object properties */
  465. i = myht ? zend_hash_num_elements(myht) : 0;
  466. if (i > 0)
  467. {
  468. zval **data;
  469. HashTable *tmp_ht;
  470. zend_hash_internal_pointer_reset_ex(myht, &pos);
  471. for (;; zend_hash_move_forward_ex(myht, &pos)) {
  472. i = zend_hash_get_current_key_ex(myht, &key, &key_len, &index, 0, &pos);
  473. if (i == HASH_KEY_NON_EXISTANT)
  474. break;
  475. if (zend_hash_get_current_data_ex(myht, (void **) &data, &pos) == SUCCESS)
  476. {
  477. tmp_ht = HASH_OF(*data);
  478. if (tmp_ht) {
  479. tmp_ht->nApplyCount++;
  480. }
  481. if (i == HASH_KEY_IS_STRING)
  482. {
  483. if (key[0] == '\0' && Z_TYPE_P(value) == IS_OBJECT) {
  484. /* Skip protected and private members. */
  485. if (tmp_ht) {
  486. tmp_ht->nApplyCount--;
  487. }
  488. continue;
  489. }
  490. newobj->Set(V8JS_STRL(key, key_len - 1), zval_to_v8js(*data, isolate TSRMLS_CC), v8::ReadOnly);
  491. } else {
  492. newobj->Set(index, zval_to_v8js(*data, isolate TSRMLS_CC));
  493. }
  494. if (tmp_ht) {
  495. tmp_ht->nApplyCount--;
  496. }
  497. }
  498. }
  499. }
  500. return newobj;
  501. }
  502. /* }}} */
  503. static v8::Handle<v8::Value> php_v8js_hash_to_jsarr(zval *value, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  504. {
  505. HashTable *myht = HASH_OF(value);
  506. int i = myht ? zend_hash_num_elements(myht) : 0;
  507. /* Return object if dealing with assoc array */
  508. if (i > 0 && _php_v8js_is_assoc_array(myht TSRMLS_CC)) {
  509. return php_v8js_hash_to_jsobj(value, isolate TSRMLS_CC);
  510. }
  511. v8::Local<v8::Array> newarr;
  512. /* Prevent recursion */
  513. if (myht && myht->nApplyCount > 1) {
  514. return V8JS_NULL;
  515. }
  516. newarr = v8::Array::New(i);
  517. if (i > 0)
  518. {
  519. zval **data;
  520. ulong index = 0;
  521. HashTable *tmp_ht;
  522. HashPosition pos;
  523. for (zend_hash_internal_pointer_reset_ex(myht, &pos);
  524. SUCCESS == zend_hash_get_current_data_ex(myht, (void **) &data, &pos);
  525. zend_hash_move_forward_ex(myht, &pos)
  526. ) {
  527. tmp_ht = HASH_OF(*data);
  528. if (tmp_ht) {
  529. tmp_ht->nApplyCount++;
  530. }
  531. newarr->Set(index++, zval_to_v8js(*data, isolate TSRMLS_CC));
  532. if (tmp_ht) {
  533. tmp_ht->nApplyCount--;
  534. }
  535. }
  536. }
  537. return newarr;
  538. }
  539. /* }}} */
  540. v8::Handle<v8::Value> zval_to_v8js(zval *value, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  541. {
  542. v8::Handle<v8::Value> jsValue;
  543. switch (Z_TYPE_P(value))
  544. {
  545. case IS_ARRAY:
  546. jsValue = php_v8js_hash_to_jsarr(value, isolate TSRMLS_CC);
  547. break;
  548. case IS_OBJECT:
  549. jsValue = php_v8js_hash_to_jsobj(value, isolate TSRMLS_CC);
  550. break;
  551. case IS_STRING:
  552. jsValue = V8JS_STRL(Z_STRVAL_P(value), Z_STRLEN_P(value));
  553. break;
  554. case IS_LONG:
  555. jsValue = V8JS_INT(Z_LVAL_P(value));
  556. break;
  557. case IS_DOUBLE:
  558. jsValue = V8JS_FLOAT(Z_DVAL_P(value));
  559. break;
  560. case IS_BOOL:
  561. jsValue = V8JS_BOOL(Z_BVAL_P(value));
  562. break;
  563. default:
  564. case IS_NULL:
  565. jsValue = V8JS_NULL;
  566. break;
  567. }
  568. return jsValue;
  569. }
  570. /* }}} */
  571. int v8js_to_zval(v8::Handle<v8::Value> jsValue, zval *return_value, int flags, v8::Isolate *isolate TSRMLS_DC) /* {{{ */
  572. {
  573. if (jsValue->IsString())
  574. {
  575. v8::String::Utf8Value str(jsValue);
  576. const char *cstr = ToCString(str);
  577. RETVAL_STRING(cstr, 1);
  578. }
  579. else if (jsValue->IsBoolean())
  580. {
  581. RETVAL_BOOL(jsValue->Uint32Value());
  582. }
  583. else if (jsValue->IsInt32() || jsValue->IsUint32())
  584. {
  585. RETVAL_LONG((long) jsValue->IntegerValue());
  586. }
  587. else if (jsValue->IsNumber())
  588. {
  589. RETVAL_DOUBLE(jsValue->NumberValue());
  590. }
  591. else if (jsValue->IsDate()) /* Return as a PHP DateTime object */
  592. {
  593. v8::String::Utf8Value str(jsValue);
  594. const char *cstr = ToCString(str);
  595. zend_class_entry *ce = php_date_get_date_ce();
  596. #if PHP_VERSION_ID < 50304
  597. zval *param;
  598. MAKE_STD_ZVAL(param);
  599. ZVAL_STRING(param, cstr, 1);
  600. object_init_ex(return_value, ce TSRMLS_CC);
  601. zend_call_method_with_1_params(&return_value, ce, &ce->constructor, "__construct", NULL, param);
  602. zval_ptr_dtor(&param);
  603. if (EG(exception)) {
  604. return FAILURE;
  605. }
  606. #else
  607. php_date_instantiate(ce, return_value TSRMLS_CC);
  608. if (!php_date_initialize((php_date_obj *) zend_object_store_get_object(return_value TSRMLS_CC), (char *) cstr, strlen(cstr), NULL, NULL, 0 TSRMLS_CC)) {
  609. return FAILURE;
  610. }
  611. #endif
  612. }
  613. else if (jsValue->IsObject())
  614. {
  615. if ((flags & V8JS_FLAG_FORCE_ARRAY) || jsValue->IsArray()) {
  616. array_init(return_value);
  617. return php_v8js_v8_get_properties_hash(jsValue, Z_ARRVAL_P(return_value), flags, isolate TSRMLS_CC);
  618. } else {
  619. php_v8js_create_v8(return_value, jsValue, flags, isolate TSRMLS_CC);
  620. return SUCCESS;
  621. }
  622. }
  623. else /* types External, RegExp, Undefined and Null are considered NULL */
  624. {
  625. RETVAL_NULL();
  626. }
  627. return SUCCESS;
  628. }
  629. /* }}} */
  630. /*
  631. * Local variables:
  632. * tab-width: 4
  633. * c-basic-offset: 4
  634. * End:
  635. * vim600: noet sw=4 ts=4 fdm=marker
  636. * vim<600: noet sw=4 ts=4
  637. */