v8js_convert.cc 22 KB

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