package.xml 0000644 0001751 0000166 00001331711 15014033047 010120 0 ustar
mongodb
pecl.php.net
MongoDB driver for PHP
The purpose of this driver is to provide exceptionally thin glue between MongoDB
and PHP, implementing only fundamental and performance-critical components
necessary to build a fully-functional MongoDB driver.
Andreas Braun
alcaeus
alcaeus@php.net
yes
Jeremy Mikola
jmikola
jmikola@php.net
yes
Derick Rethans
derick
derick@php.net
no
Hannes Magnusson
bjori
bjori@php.net
no
Katherine Walker
kvwalker
kvwalker@php.net
no
2025-05-23
2.1.0
2.1.0
stable
stable
Apache License
## What's Changed
* Mention `Serializable` and `Unserializable` types in upgrade guide by @GromNaN in https://github.com/mongodb/mongo-php-driver/pull/1805
* Add CODEOWNERS for 1.21+ by @alcaeus in https://github.com/mongodb/mongo-php-driver/pull/1810
* PHPC-2537 Update to newer Ubuntu version in GitHub Actions workflows by @GromNaN in https://github.com/mongodb/mongo-php-driver/pull/1814
* Feature: Client Bulk Write by @GromNaN in https://github.com/mongodb/mongo-php-driver/pull/1818
* PHPC-2580: Bump to libmongoc 1.30.4 by @alcaeus in https://github.com/mongodb/mongo-php-driver/pull/1822
* PHPC-2510 Install evergreen tools using git submodule by @GromNaN in https://github.com/mongodb/mongo-php-driver/pull/1797
* PHPC-2555: Stop testing with MongoDB 4.0 by @alcaeus in https://github.com/mongodb/mongo-php-driver/pull/1827
* PHPLIB-1678: Use assume_role command before accessing secrets by @alcaeus in https://github.com/mongodb/mongo-php-driver/pull/1832
**Full Changelog**: https://github.com/mongodb/mongo-php-driver/compare/2.0.0...2.1.0
8.1.0
8.99.99
1.4.8
mongodb
mongodb-2.1.0/scripts/autotools/libbson/CheckHeaders.m4 0000644 0001751 0000166 00000000421 15014033047 017775 0 ustar AC_HEADER_STDBOOL
AC_SUBST(BSON_HAVE_STDBOOL_H, 0)
if test "$ac_cv_header_stdbool_h" = "yes"; then
AC_SUBST(BSON_HAVE_STDBOOL_H, 1)
fi
AC_CHECK_HEADER([strings.h],
[AC_SUBST(BSON_HAVE_STRINGS_H, 1)],
[AC_SUBST(BSON_HAVE_STRINGS_H, 0)])
mongodb-2.1.0/scripts/autotools/libbson/Endian.m4 0000644 0001751 0000166 00000000276 15014033047 016672 0 ustar AC_C_BIGENDIAN(
[AC_SUBST(BSON_BYTE_ORDER, 4321)],
[AC_SUBST(BSON_BYTE_ORDER, 1234)],
[AC_MSG_ERROR([unknown endianness])],
[AC_MSG_ERROR([universal endianness is not supported])]
)
mongodb-2.1.0/scripts/autotools/libbson/FindDependencies.m4 0000644 0001751 0000166 00000003732 15014033047 020663 0 ustar # Check for strnlen()
dnl AC_CHECK_FUNC isn't properly respecting _XOPEN_SOURCE for strnlen for unknown reason
AC_SUBST(BSON_HAVE_STRNLEN, 0)
AC_CACHE_CHECK([for strnlen],
bson_cv_have_strnlen,
[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[
#include
int strnlen () { return 0; }
]])],
[bson_cv_have_strnlen=no],
[bson_cv_have_strnlen=yes])])
if test "$bson_cv_have_strnlen" = yes; then
AC_SUBST(BSON_HAVE_STRNLEN, 1)
fi
# Check for snprintf()
AC_SUBST(BSON_HAVE_SNPRINTF, 0)
AC_CHECK_FUNC(snprintf, [AC_SUBST(BSON_HAVE_SNPRINTF, 1)])
# Check for strlcpy()
AC_SUBST(BSON_HAVE_STRLCPY, 0)
AC_CHECK_FUNC(strlcpy, [AC_SUBST(BSON_HAVE_STRLCPY, 1)])
# Check for struct timespec
AC_SUBST(BSON_HAVE_TIMESPEC, 0)
AC_CHECK_TYPE([struct timespec], [AC_SUBST(BSON_HAVE_TIMESPEC, 1)], [], [#include ])
# Check for clock_gettime and if it needs -lrt
AC_SUBST(BSON_HAVE_CLOCK_GETTIME, 0)
AC_SEARCH_LIBS([clock_gettime], [rt], [AC_SUBST(BSON_HAVE_CLOCK_GETTIME, 1)])
# Check if math functions need -lm
AC_SEARCH_LIBS([floor], [m])
# Check for gmtime_r()
AC_SUBST(BSON_HAVE_GMTIME_R, 0)
AC_CHECK_FUNC(gmtime_r, [AC_SUBST(BSON_HAVE_GMTIME_R, 1)])
# Check for rand_r()
AC_SUBST(BSON_HAVE_RAND_R, 0)
AC_CHECK_FUNC(rand_r, [AC_SUBST(BSON_HAVE_RAND_R, 1)])
# Check for pthreads. We might need to make this better to handle mingw,
# but I actually think it is okay to just check for it even though we will
# use win32 primatives.
AX_PTHREAD([
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS $PTHREAD_CFLAGS"
PHP_EVAL_LIBLINE([$PTHREAD_LIBS],[MONGODB_SHARED_LIBADD])
# PTHREAD_CFLAGS may come back as "-pthread", which should also be used when
# linking. We can trust PHP_EVAL_LIBLINE to ignore other values.
PHP_EVAL_LIBLINE([$PTHREAD_CFLAGS],[MONGODB_SHARED_LIBADD])
],[
AC_MSG_ERROR([libbson requires pthreads on non-Windows platforms.])
])
# Check for aligned_alloc()
AC_SUBST(BSON_HAVE_ALIGNED_ALLOC, 0)
AC_CHECK_FUNC(aligned_alloc, [AC_SUBST(BSON_HAVE_ALIGNED_ALLOC, 1)])
mongodb-2.1.0/scripts/autotools/libbson/Versions.m4 0000644 0001751 0000166 00000001252 15014033047 017277 0 ustar BSON_CURRENT_FILE=[]PHP_EXT_SRCDIR(mongodb)[/src/LIBMONGOC_VERSION_CURRENT]
libbson_VERSION_FULL=$(cat $BSON_CURRENT_FILE)
dnl Ensure newline for "cut" implementations that need it, e.g. HP-UX.
libbson_VERSION_MAJOR=$( (cat $BSON_CURRENT_FILE; echo) | cut -d- -f1 | cut -d. -f1 )
libbson_VERSION_MINOR=$( (cat $BSON_CURRENT_FILE; echo) | cut -d- -f1 | cut -d. -f2 )
libbson_VERSION_PATCH=$( (cat $BSON_CURRENT_FILE; echo) | cut -d- -f1 | cut -d. -f3 )
libbson_VERSION_PRERELEASE=$(cut -s -d- -f2 $BSON_CURRENT_FILE)
AC_SUBST(libbson_VERSION_FULL)
AC_SUBST(libbson_VERSION_MAJOR)
AC_SUBST(libbson_VERSION_MINOR)
AC_SUBST(libbson_VERSION_PATCH)
AC_SUBST(libbson_VERSION_PRERELEASE)
mongodb-2.1.0/scripts/autotools/libmongoc/CheckCompression.m4 0000644 0001751 0000166 00000012274 15014033047 021255 0 ustar PHP_ARG_WITH([mongodb-snappy],
[whether to enable Snappy for compression],
[AS_HELP_STRING([--with-mongodb-snappy=@<:@auto/yes/no@:>@],
[MongoDB: Enable Snappy for compression [default=auto]])],
[auto],
[no])
PHP_MONGODB_VALIDATE_ARG([PHP_MONGODB_SNAPPY], [auto yes no])
PHP_ARG_WITH([mongodb-zlib],
[whether to enable zlib for compression],
[AS_HELP_STRING([--with-mongodb-zlib=@<:@auto/system/bundled/no@:>@],
[MongoDB: Enable zlib for compression [default=auto]])],
[auto],
[no])
dnl PHP_ARG_WITH without a value assigns "yes". Treat it like "auto" since we
dnl fall back to bundled zlib if the system library isn't found
if test "$PHP_MONGODB_ZLIB" = "yes"; then
PHP_MONGODB_ZLIB="auto"
fi
PHP_MONGODB_VALIDATE_ARG([PHP_MONGODB_ZLIB], [auto system bundled no])
PHP_ARG_WITH([mongodb-zstd],
[whether to enable zstd for compression],
[AS_HELP_STRING([--with-mongodb-zstd=@<:@auto/yes/no@:>@],
[MongoDB: Enable zstd for compression [default=auto]])],
[auto],
[no])
PHP_MONGODB_VALIDATE_ARG([PHP_MONGODB_ZSTD], [auto yes no])
found_snappy="no"
found_zlib="no"
bundled_zlib="no"
found_zstd="no"
AS_IF([test "$PHP_MONGODB_SNAPPY" = "auto" -o "$PHP_MONGODB_SNAPPY" = "yes"],[
PKG_CHECK_MODULES([PHP_MONGODB_SNAPPY],[snappy],[
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS $PHP_MONGODB_SNAPPY_CFLAGS"
PHP_EVAL_LIBLINE([$PHP_MONGODB_SNAPPY_LIBS],[MONGODB_SHARED_LIBADD])
found_snappy="yes"
],[
PHP_CHECK_LIBRARY([snappy],
[snappy_uncompress],
[have_snappy_lib="yes"],
[have_snappy_lib="no"])
AC_CHECK_HEADER([snappy-c.h],
[have_snappy_headers=yes],
[have_snappy_headers=no])
if test "$have_snappy_lib" = "yes" -a "$have_snappy_headers" = "yes"; then
PHP_ADD_LIBRARY([snappy],,[MONGODB_SHARED_LIBADD])
found_snappy="yes"
fi
])
if test "$PHP_MONGODB_SNAPPY" = "yes" -a "$found_snappy" = "no"; then
AC_MSG_ERROR([Snappy libraries and development headers could not be found])
fi
])
AS_IF([test "$PHP_MONGODB_ZLIB" = "auto" -o "$PHP_MONGODB_ZLIB" = "system"],[
PKG_CHECK_MODULES([PHP_MONGODB_ZLIB],[zlib],[
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS $PHP_MONGODB_ZLIB_CFLAGS"
PHP_EVAL_LIBLINE([$PHP_MONGODB_ZLIB_LIBS],[MONGODB_SHARED_LIBADD])
found_zlib="yes"
],[
PHP_CHECK_LIBRARY([zlib],
[compress2],
[have_zlib_lib="yes"],
[have_zlib_lib="no"])
AC_CHECK_HEADER([zlib.h],
[have_zlib_headers=yes],
[have_zlib_headers=no])
if test "$have_zlib_lib" = "yes" -a "$have_zlib_headers" = "yes"; then
PHP_ADD_LIBRARY([z],,[MONGODB_SHARED_LIBADD])
found_zlib="yes"
fi
])
if test "$PHP_MONGODB_ZLIB" = "system" -a "$found_zlib" = "no"; then
AC_MSG_ERROR([zlib libraries and development headers could not be found])
fi
])
dnl Use libmongoc's bundled zlib if necessary
AS_IF([test "$found_zlib" = "no" -a \( "$PHP_MONGODB_ZLIB" = "auto" -o "$PHP_MONGODB_ZLIB" = "bundled" \)],[
AC_CHECK_HEADER([unistd.h],[PHP_MONGODB_ZLIB_CFLAGS="$PHP_MONGODB_ZLIB_CFLAGS -DHAVE_UNISTD_H"])
AC_CHECK_HEADER([stdarg.h],[PHP_MONGODB_ZLIB_CFLAGS="$PHP_MONGODB_ZLIB_CFLAGS -DHAVE_STDARG_H"])
bundled_zlib="yes"
])
AS_IF([test "$PHP_MONGODB_ZSTD" = "auto" -o "$PHP_MONGODB_ZSTD" = "yes"],[
PKG_CHECK_MODULES([PHP_MONGODB_ZSTD],[libzstd],[
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS $PHP_MONGODB_ZSTD_CFLAGS"
PHP_EVAL_LIBLINE([$PHP_MONGODB_ZSTD_LIBS],[MONGODB_SHARED_LIBADD])
found_zstd="yes"
],[
PHP_CHECK_LIBRARY([zstd],
[ZSTD_compress],
[have_zstd_lib="yes"],
[have_zstd_lib="no"])
AC_CHECK_HEADER([zstd.h],
[have_zstd_headers=yes],
[have_zstd_headers=no])
if test "$have_zstd_lib" = "yes" -a "$have_zstd_headers" = "yes"; then
PHP_ADD_LIBRARY([zstd],,[MONGODB_SHARED_LIBADD])
found_zstd="yes"
fi
])
if test "$PHP_MONGODB_ZSTD" = "yes" -a "$found_zstd" = "no"; then
AC_MSG_ERROR([zstd libraries and development headers could not be found])
fi
])
if test "$found_snappy" = "yes" -o "$found_zlib" = "yes" -o "$bundled_zlib" = "yes" -o "$found_zstd" = "yes"; then
AC_SUBST(MONGOC_ENABLE_COMPRESSION, 1)
if test "$found_snappy" = "yes"; then
AC_SUBST(MONGOC_ENABLE_COMPRESSION_SNAPPY, 1)
else
AC_SUBST(MONGOC_ENABLE_COMPRESSION_SNAPPY, 0)
fi
if test "$found_zlib" = "yes" -o "$bundled_zlib" = "yes"; then
AC_SUBST(MONGOC_ENABLE_COMPRESSION_ZLIB, 1)
else
AC_SUBST(MONGOC_ENABLE_COMPRESSION_ZLIB, 0)
fi
if test "$found_zstd" = "yes"; then
AC_SUBST(MONGOC_ENABLE_COMPRESSION_ZSTD, 1)
else
AC_SUBST(MONGOC_ENABLE_COMPRESSION_ZSTD, 0)
fi
else
AC_SUBST(MONGOC_ENABLE_COMPRESSION, 0)
AC_SUBST(MONGOC_ENABLE_COMPRESSION_SNAPPY, 0)
AC_SUBST(MONGOC_ENABLE_COMPRESSION_ZLIB, 0)
AC_SUBST(MONGOC_ENABLE_COMPRESSION_ZSTD, 0)
fi
mongodb-2.1.0/scripts/autotools/libmongoc/CheckResolv.m4 0000644 0001751 0000166 00000005621 15014033047 020224 0 ustar dnl Disable SRV until we find a library
AC_SUBST(MONGOC_ENABLE_SRV, 0)
dnl Disable Windows DNSAPI
AC_SUBST(MONGOC_HAVE_DNSAPI, 0)
found_resolv="no"
libc_has_resolv="no"
if test "$os_aix" = "yes" -o "$os_freebsd" = "yes"; then
libc_has_resolv="yes"
fi
dnl Temporarily link libresolv for detection if necessary
if test "$libc_has_resolv" = "no"; then
old_LIBS="$LIBS"
LIBS="$LIBS -lresolv"
fi
dnl Thread-safe DNS query function for _mongoc_client_get_srv.
dnl Could be a macro, not a function, so check with AC_LINK_IFELSE.
AC_MSG_CHECKING([for res_nsearch])
AC_LINK_IFELSE([AC_LANG_PROGRAM([[
#include
#include
#include
#include
]], [[
int len;
unsigned char reply[1024];
res_state statep;
len = res_nsearch(
statep, "example.com", ns_c_in, ns_t_srv, reply, sizeof(reply));
]])], [
AC_MSG_RESULT([yes])
AC_SUBST(MONGOC_HAVE_RES_SEARCH, 0)
AC_SUBST(MONGOC_HAVE_RES_NSEARCH, 1)
found_resolv="yes"
dnl We have res_nsearch. Call res_ndestroy (BSD/Mac) or res_nclose (Linux)?
AC_MSG_CHECKING([for res_ndestroy])
AC_LINK_IFELSE([AC_LANG_PROGRAM([[
#include
#include
#include
#include
]], [[
res_state statep;
res_ndestroy(statep);
]])], [
AC_MSG_RESULT([yes])
AC_SUBST(MONGOC_HAVE_RES_NDESTROY, 1)
AC_SUBST(MONGOC_HAVE_RES_NCLOSE, 0)
], [
AC_MSG_RESULT([no])
AC_SUBST(MONGOC_HAVE_RES_NDESTROY, 0)
AC_MSG_CHECKING([for res_nclose])
AC_LINK_IFELSE([AC_LANG_PROGRAM([[
#include
#include
#include
#include
]], [[
res_state statep;
res_nclose(statep);
]])], [
AC_MSG_RESULT([yes])
AC_SUBST(MONGOC_HAVE_RES_NCLOSE, 1)
], [
AC_MSG_RESULT([no])
AC_SUBST(MONGOC_HAVE_RES_NCLOSE, 0)
])
])
],[
AC_MSG_RESULT([no])
AC_SUBST(MONGOC_HAVE_RES_NSEARCH, 0)
AC_SUBST(MONGOC_HAVE_RES_NDESTROY, 0)
AC_SUBST(MONGOC_HAVE_RES_NCLOSE, 0)
dnl Thread-unsafe function.
AC_MSG_CHECKING([for res_search])
AC_LINK_IFELSE([AC_LANG_PROGRAM([[
#include
#include
#include
#include
]], [[
int len;
unsigned char reply[1024];
len = res_search("example.com", ns_c_in, ns_t_srv, reply, sizeof(reply));
]])], [
AC_MSG_RESULT([yes])
AC_SUBST(MONGOC_HAVE_RES_SEARCH, 1)
found_resolv="yes"
], [
AC_MSG_RESULT([no])
AC_SUBST(MONGOC_HAVE_RES_SEARCH, 0)
])
])
AS_IF([test "$found_resolv" = "yes"],[
AC_SUBST(MONGOC_ENABLE_SRV, 1)
])
if test "$libc_has_resolv" = "no"; then
LIBS="$old_LIBS"
AS_IF([test "$found_resolv" = "yes"],[
PHP_ADD_LIBRARY([resolv],,[MONGODB_SHARED_LIBADD])
])
fi
mongodb-2.1.0/scripts/autotools/libmongoc/CheckSSL.m4 0000644 0001751 0000166 00000020765 15014033047 017421 0 ustar PHP_ARG_WITH([mongodb-ssl],
[whether to enable crypto and TLS],
[AS_HELP_STRING([--with-mongodb-ssl=@<:@auto/openssl/libressl/darwin/no@:>@],
[MongoDB: Enable TLS connections and SCRAM-SHA-1 authentication [default=auto]])],
[auto],
[no])
if test "$PHP_MONGODB_SSL" = "auto" -o "$PHP_MONGODB_SSL" = "no"; then
crypto_required="no"
else
crypto_required="yes"
dnl PHP_ARG_WITH without a value assigns "yes". Treat it like "auto" but
dnl require a crypto library.
if test "$PHP_MONGODB_SSL" = "yes"; then
PHP_MONGODB_SSL="auto"
fi
fi
PHP_MONGODB_VALIDATE_ARG([PHP_MONGODB_SSL], [auto openssl libressl darwin no])
AS_IF([test "$PHP_MONGODB_SSL" = "openssl" -o "$PHP_MONGODB_SSL" = "auto"],[
found_openssl="no"
dnl OpenSSL 1.0.1 is required for libmongoc 1.24+ (CDRIVER-3562). This can be
dnl enforced through pkg-config but not the PHP_CHECK_LIBRARY fallback.
PKG_CHECK_MODULES([PHP_MONGODB_SSL],[openssl >= 1.0.1],[
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS $PHP_MONGODB_SSL_CFLAGS"
PHP_EVAL_LIBLINE([$PHP_MONGODB_SSL_LIBS],[MONGODB_SHARED_LIBADD])
PHP_MONGODB_SSL="openssl"
found_openssl="yes"
old_CFLAGS="$CFLAGS"
CFLAGS="$PHP_MONGODB_SSL_CFLAGS $CFLAGS"
AC_CHECK_DECLS([ASN1_STRING_get0_data],
[have_ASN1_STRING_get0_data="yes"],
[have_ASN1_STRING_get0_data="no"],
[[#include ]])
CFLAGS="$old_CFLAGS"
],[
unset OPENSSL_INCDIR
unset OPENSSL_LIBDIR
dnl Use a list of directories from PHP_SETUP_OPENSSL by default.
OPENSSL_SEARCH_PATHS="/usr/local/ssl /usr/local /usr /usr/local/openssl"
for i in $OPENSSL_SEARCH_PATHS; do
if test -r $i/include/openssl/evp.h; then
OPENSSL_INCDIR="$i/include"
fi
if test -r $i/$PHP_LIBDIR/libssl.a -o -r $i/$PHP_LIBDIR/libssl.$SHLIB_SUFFIX_NAME; then
OPENSSL_LIBDIR="$i/$PHP_LIBDIR"
fi
test -n "$OPENSSL_INCDIR" && test -n "$OPENSSL_LIBDIR" && break
done
if test -n "$OPENSSL_LIBDIR"; then
OPENSSL_LIBDIR_LDFLAG="-L$OPENSSL_LIBDIR"
fi
PHP_CHECK_LIBRARY([crypto],
[EVP_DigestInit_ex],
[have_crypto_lib="yes"],
[have_crypto_lib="no"],
[$OPENSSL_LIBDIR_LDFLAG])
dnl Check whether OpenSSL >= 1.1.0 is available
PHP_CHECK_LIBRARY([ssl],
[OPENSSL_init_ssl],
[have_ssl_lib="yes"],
[have_ssl_lib="no"],
[$OPENSSL_LIBDIR_LDFLAG -lcrypto])
dnl If necessary, check whether OpenSSL < 1.1.0 is available
if test "$have_ssl_lib" = "no"; then
PHP_CHECK_LIBRARY([ssl],
[SSL_library_init],
[have_ssl_lib="yes"],
[have_ssl_lib="no"],
[$OPENSSL_LIBDIR_LDFLAG -lcrypto])
fi
if test "$have_ssl_lib" = "yes" -a "$have_crypto_lib" = "yes"; then
PHP_ADD_LIBRARY([ssl],,[MONGODB_SHARED_LIBADD])
PHP_ADD_LIBRARY([crypto],,[MONGODB_SHARED_LIBADD])
if test -n "$OPENSSL_LIBDIR"; then
PHP_ADD_LIBPATH([$OPENSSL_LIBDIR],[MONGODB_SHARED_LIBADD])
fi
if test -n "$OPENSSL_INCDIR"; then
PHP_ADD_INCLUDE($OPENSSL_INCDIR)
fi
old_CFLAGS="$CFLAGS"
CFLAGS="-I$OPENSSL_INCDIR $CFLAGS"
AC_CHECK_DECLS([ASN1_STRING_get0_data],
[have_ASN1_STRING_get0_data="yes"],
[have_ASN1_STRING_get0_data="no"],
[[#include ]])
CFLAGS="$old_CFLAGS"
PHP_MONGODB_SSL="openssl"
found_openssl="yes"
fi
])
if test "$PHP_MONGODB_SSL" = "openssl" -a "$found_openssl" != "yes"; then
AC_MSG_ERROR([OpenSSL libraries and development headers could not be found])
fi
])
AS_IF([test "$PHP_MONGODB_SSL" = "darwin" -o \( "$PHP_MONGODB_SSL" = "auto" -a "$os_darwin" = "yes" \)],[
if test "$os_darwin" = "no"; then
AC_MSG_ERROR([Darwin SSL is only supported on macOS])
fi
dnl PHP_FRAMEWORKS is only used for SAPI builds, so use MONGODB_SHARED_LIBADD for shared builds
if test "$ext_shared" = "yes"; then
MONGODB_SHARED_LIBADD="-framework Security -framework CoreFoundation $MONGODB_SHARED_LIBADD"
else
PHP_ADD_FRAMEWORK([Security])
PHP_ADD_FRAMEWORK([CoreFoundation])
fi
PHP_MONGODB_SSL="darwin"
])
AS_IF([test "$PHP_MONGODB_SSL" = "libressl" -o "$PHP_MONGODB_SSL" = "auto"],[
found_libressl="no"
PKG_CHECK_MODULES([PHP_MONGODB_SSL],[libtls libcrypto],[
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS $PHP_MONGODB_SSL_CFLAGS"
PHP_EVAL_LIBLINE([$PHP_MONGODB_SSL_LIBS],[MONGODB_SHARED_LIBADD])
PHP_MONGODB_SSL="libressl"
found_libressl="yes"
],[
PHP_CHECK_LIBRARY([crypto],
[EVP_DigestInit_ex],
[have_crypto_lib="yes"],
[have_crypto_lib="no"])
PHP_CHECK_LIBRARY([tls],
[tls_init],
[have_ssl_lib="yes"],
[have_ssl_lib="no"],
[-lcrypto])
if test "$have_ssl_lib" = "yes" -a "$have_crypto_lib" = "yes"; then
PHP_ADD_LIBRARY([tls],,[MONGODB_SHARED_LIBADD])
PHP_ADD_LIBRARY([crypto],,[MONGODB_SHARED_LIBADD])
PHP_MONGODB_SSL="libressl"
found_libressl="yes"
fi
])
if test "$PHP_MONGODB_SSL" = "libressl" -a "$found_libressl" != "yes"; then
AC_MSG_ERROR([LibreSSL libraries and development headers could not be found])
fi
])
AS_IF([test "$PHP_MONGODB_SSL" = "auto"],[
if test "$crypto_required" = "yes"; then
AC_MSG_ERROR([crypto and TLS libraries not found])
fi
PHP_MONGODB_SSL="no"
])
AC_MSG_CHECKING([which TLS library to use])
AC_MSG_RESULT([$PHP_MONGODB_SSL])
dnl Disable Windows SSL and crypto
AC_SUBST(MONGOC_ENABLE_SSL_SECURE_CHANNEL, 0)
AC_SUBST(MONGOC_ENABLE_CRYPTO_CNG, 0)
AC_SUBST(MONGOC_HAVE_BCRYPT_PBKDF2, 0)
if test "$PHP_MONGODB_SSL" = "openssl" -o "$PHP_MONGODB_SSL" = "libressl" -o "$PHP_MONGODB_SSL" = "darwin"; then
AC_SUBST(MONGOC_ENABLE_SSL, 1)
AC_SUBST(MONGOC_ENABLE_CRYPTO, 1)
if test "$PHP_MONGODB_SSL" = "darwin"; then
AC_SUBST(MONGOC_ENABLE_SSL_OPENSSL, 0)
AC_SUBST(MONGOC_ENABLE_SSL_LIBRESSL, 0)
AC_SUBST(MONGOC_ENABLE_SSL_SECURE_TRANSPORT, 1)
AC_SUBST(MONGOC_ENABLE_CRYPTO_LIBCRYPTO, 0)
AC_SUBST(MONGOC_ENABLE_CRYPTO_COMMON_CRYPTO, 1)
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS -DKMS_MESSAGE_ENABLE_CRYPTO=1 -DKMS_MESSAGE_ENABLE_CRYPTO_COMMON_CRYPTO=1"
elif test "$PHP_MONGODB_SSL" = "openssl"; then
AC_SUBST(MONGOC_ENABLE_SSL_OPENSSL, 1)
AC_SUBST(MONGOC_ENABLE_SSL_LIBRESSL, 0)
AC_SUBST(MONGOC_ENABLE_SSL_SECURE_TRANSPORT, 0)
AC_SUBST(MONGOC_ENABLE_CRYPTO_LIBCRYPTO, 1)
AC_SUBST(MONGOC_ENABLE_CRYPTO_COMMON_CRYPTO, 0)
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS -DKMS_MESSAGE_ENABLE_CRYPTO=1 -DKMS_MESSAGE_ENABLE_CRYPTO_LIBCRYPTO=1"
elif test "$PHP_MONGODB_SSL" = "libressl"; then
AC_SUBST(MONGOC_ENABLE_SSL_OPENSSL, 0)
AC_SUBST(MONGOC_ENABLE_SSL_LIBRESSL, 1)
AC_SUBST(MONGOC_ENABLE_SSL_SECURE_TRANSPORT, 0)
AC_SUBST(MONGOC_ENABLE_CRYPTO_LIBCRYPTO, 1)
AC_SUBST(MONGOC_ENABLE_CRYPTO_COMMON_CRYPTO, 0)
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS -DKMS_MESSAGE_ENABLE_CRYPTO=1 -DKMS_MESSAGE_ENABLE_CRYPTO_LIBCRYPTO=1"
fi
else
AC_SUBST(MONGOC_ENABLE_SSL, 0)
AC_SUBST(MONGOC_ENABLE_SSL_LIBRESSL, 0)
AC_SUBST(MONGOC_ENABLE_SSL_OPENSSL, 0)
AC_SUBST(MONGOC_ENABLE_SSL_SECURE_TRANSPORT, 0)
AC_SUBST(MONGOC_ENABLE_CRYPTO, 0)
AC_SUBST(MONGOC_ENABLE_CRYPTO_LIBCRYPTO, 0)
AC_SUBST(MONGOC_ENABLE_CRYPTO_COMMON_CRYPTO, 0)
fi
if test "$have_ASN1_STRING_get0_data" = "yes"; then
AC_SUBST(MONGOC_HAVE_ASN1_STRING_GET0_DATA, 1)
else
AC_SUBST(MONGOC_HAVE_ASN1_STRING_GET0_DATA, 0)
fi
PHP_ARG_ENABLE([mongodb-crypto-system-profile],
[whether to use system crypto profile],
[AS_HELP_STRING([--enable-mongodb-crypto-system-profile],
[MongoDB: Use system crypto profile (OpenSSL only) [default=no]])],
[no],
[no])
PHP_MONGODB_VALIDATE_ARG([PHP_MONGODB_CRYPTO_SYSTEM_PROFILE], [yes no])
if test "$PHP_MONGODB_CRYPTO_SYSTEM_PROFILE" = "yes"; then
if test "$PHP_MONGODB_SSL" = "openssl"; then
AC_SUBST(MONGOC_ENABLE_CRYPTO_SYSTEM_PROFILE, 1)
else
AC_MSG_ERROR([System crypto profile is only available with OpenSSL])
fi
else
AC_SUBST(MONGOC_ENABLE_CRYPTO_SYSTEM_PROFILE, 0)
fi
mongodb-2.1.0/scripts/autotools/libmongoc/CheckSasl.m4 0000644 0001751 0000166 00000004566 15014033047 017663 0 ustar PHP_ARG_WITH([mongodb-sasl],
[whether to enable SASL for Kerberos authentication],
[AS_HELP_STRING([--with-mongodb-sasl=@<:@auto/cyrus/no@:>@],
[MongoDB: Enable SASL for Kerberos authentication [default=auto]])],
[auto],
[no])
dnl PHP_ARG_WITH without a value assigns "yes". Treat it like "cyrus" (required)
if test "$PHP_MONGODB_SASL" = "yes"; then
PHP_MONGODB_SASL="cyrus"
fi
PHP_MONGODB_VALIDATE_ARG([PHP_MONGODB_SASL], [auto cyrus no])
AS_IF([test "$PHP_MONGODB_SASL" = "auto" -o "$PHP_MONGODB_SASL" = "cyrus"],[
found_cyrus="no"
PKG_CHECK_MODULES([PHP_MONGODB_SASL],[libsasl2],[
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS $PHP_MONGODB_SASL_CFLAGS"
PHP_EVAL_LIBLINE([$PHP_MONGODB_SASL_LIBS],[MONGODB_SHARED_LIBADD])
PHP_MONGODB_SASL="cyrus"
found_cyrus="yes"
],[
PHP_CHECK_LIBRARY([sasl2],
[sasl_client_init],
[have_sasl2_lib="yes"],
[have_sasl2_lib="no"])
AC_CHECK_HEADER([sasl/sasl.h],
[have_sasl_headers=yes],
[have_sasl_headers=no])
if test "$have_sasl2_lib" = "yes" -a "$have_sasl_headers" = "yes"; then
PHP_ADD_LIBRARY([sasl2],,[MONGODB_SHARED_LIBADD])
PHP_MONGODB_SASL="cyrus"
found_cyrus="yes"
fi
])
if test "$found_cyrus" = "yes"; then
PHP_CHECK_LIBRARY([sasl2],
[sasl_client_done],
[have_sasl_client_done=yes],
[have_sasl_client_done=no],
$MONGODB_SHARED_LIBADD)
fi
if test "$PHP_MONGODB_SASL" = "cyrus" -a "$found_cyrus" != "yes"; then
AC_MSG_ERROR([Cyrus SASL libraries and development headers could not be found])
fi
])
if test "$PHP_MONGODB_SASL" = "auto"; then
PHP_MONGODB_SASL="no"
fi
AC_MSG_CHECKING([which SASL library to use])
AC_MSG_RESULT([$PHP_MONGODB_SASL])
dnl Disable Windows SSPI
AC_SUBST(MONGOC_ENABLE_SASL_SSPI, 0)
if test "$PHP_MONGODB_SASL" = "cyrus"; then
AC_SUBST(MONGOC_ENABLE_SASL, 1)
AC_SUBST(MONGOC_ENABLE_SASL_CYRUS, 1)
if test "$have_sasl_client_done" = "yes"; then
AC_SUBST(MONGOC_HAVE_SASL_CLIENT_DONE, 1)
else
AC_SUBST(MONGOC_HAVE_SASL_CLIENT_DONE, 0)
fi
else
AC_SUBST(MONGOC_ENABLE_SASL, 0)
AC_SUBST(MONGOC_ENABLE_SASL_CYRUS, 0)
AC_SUBST(MONGOC_HAVE_SASL_CLIENT_DONE, 0)
fi
mongodb-2.1.0/scripts/autotools/libmongoc/CheckUtf8Proc.m4 0000644 0001751 0000166 00000003062 15014033047 020421 0 ustar PHP_ARG_WITH([mongodb-utf8proc],
[whether to use bundled or system utf8proc for SCRAM-SHA-256 SASLprep],
[AS_HELP_STRING([--with-mongodb-utf8proc=@<:@bundled/system@:>@],
[MongoDB: Use bundled or system utf8proc for SCRAM-SHA-256 SASLprep [default=bundled]])],
[bundled],
[no])
PHP_MONGODB_VALIDATE_ARG([PHP_MONGODB_UTF8PROC], [bundled system])
found_utf8proc="no"
bundled_utf8proc="no"
AS_IF([test "$PHP_MONGODB_UTF8PROC" = "system"],[
PKG_CHECK_MODULES([PHP_MONGODB_UTF8PROC],[libutf8proc],[
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS $PHP_MONGODB_UTF8PROC_CFLAGS"
PHP_EVAL_LIBLINE([$PHP_MONGODB_UTF8PROC_LIBS],[MONGODB_SHARED_LIBADD])
found_utf8proc="yes"
],[
PHP_CHECK_LIBRARY([utf8proc],
[utf8proc_NFKC],
[have_utf8proc_lib="yes"],
[have_utf8proc_lib="no"])
AC_CHECK_HEADER([utf8proc.h],
[have_utf8proc_headers=yes],
[have_utf8proc_headers=no])
if test "$have_utf8proc_lib" = "yes" -a "$have_utf8proc_headers" = "yes"; then
PHP_ADD_LIBRARY([utf8proc],,[MONGODB_SHARED_LIBADD])
found_utf8proc="yes"
fi
])
if test "$PHP_MONGODB_UTF8PROC" = "system" -a "$found_utf8proc" = "no"; then
AC_MSG_ERROR([utf8proc library and development headers could not be found])
fi
])
AS_IF([test "$PHP_MONGODB_UTF8PROC" = "bundled"],[
PHP_MONGODB_UTF8PROC_CFLAGS="$PHP_MONGODB_UTF8PROC_CFLAGS -DUTF8PROC_STATIC"
bundled_utf8proc="yes"
])
mongodb-2.1.0/scripts/autotools/libmongoc/Endian.m4 0000644 0001751 0000166 00000000451 15014033047 017206 0 ustar AC_C_BIGENDIAN(
[PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS -DKMS_MESSAGE_BIG_ENDIAN=1"],
[PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS -DKMS_MESSAGE_LITTLE_ENDIAN=1"],
[AC_MSG_ERROR([unknown endianness])],
[AC_MSG_ERROR([universal endianness is not supported])]
)
mongodb-2.1.0/scripts/autotools/libmongoc/FindDependencies.m4 0000644 0001751 0000166 00000003057 15014033047 021204 0 ustar # Check for shm functions
AC_CHECK_FUNCS([shm_open],[],[
AC_CHECK_LIB([rt],
[shm_open],
[PHP_ADD_LIBRARY([rt],,[MONGODB_SHARED_LIBADD])],
[])
])
# Check for sched_getcpu
AC_CHECK_FUNC([sched_getcpu],
[AC_SUBST(MONGOC_HAVE_SCHED_GETCPU, 1)],
[AC_SUBST(MONGOC_HAVE_SCHED_GETCPU, 0)])
AC_CHECK_TYPE([socklen_t],
[AC_SUBST(MONGOC_HAVE_SOCKLEN, 1)],
[AC_SUBST(MONGOC_HAVE_SOCKLEN, 0)],
[#include ])
AC_CHECK_MEMBER([struct sockaddr_storage.ss_family],
[AC_SUBST(MONGOC_HAVE_SS_FAMILY, 1)],
[AC_SUBST(MONGOC_HAVE_SS_FAMILY, 0)],
[#include ])
AC_DEFINE([ACCEPT_ARG2], [], [Description])
AC_DEFINE([ACCEPT_ARG3], [], [Description])
AX_PROTOTYPE_ACCEPT
AC_SUBST(MONGOC_SOCKET_ARG2, "$ACCEPT_ARG2")
AC_SUBST(MONGOC_SOCKET_ARG3, "$ACCEPT_ARG3")
# Check for pthreads. libmongoc's original FindDependencies.m4 script did not
# require pthreads, but it does appear to be necessary on non-Windows platforms
# based on mongoc-openssl.c and mongoc-thread-private.h.
AX_PTHREAD([
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS $PTHREAD_CFLAGS"
PHP_EVAL_LIBLINE([$PTHREAD_LIBS],[MONGODB_SHARED_LIBADD])
# PTHREAD_CFLAGS may come back as "-pthread", which should also be used when
# linking. We can trust PHP_EVAL_LIBLINE to ignore other values.
PHP_EVAL_LIBLINE([$PTHREAD_CFLAGS],[MONGODB_SHARED_LIBADD])
],[
AC_MSG_ERROR([libmongoc requires pthreads on non-Windows platforms.])
])
mongodb-2.1.0/scripts/autotools/libmongoc/Versions.m4 0000644 0001751 0000166 00000001312 15014033047 017615 0 ustar MONGOC_CURRENT_FILE=[]PHP_EXT_SRCDIR(mongodb)[/src/LIBMONGOC_VERSION_CURRENT]
libmongoc_VERSION_FULL=$(cat $MONGOC_CURRENT_FILE)
dnl Ensure newline for "cut" implementations that need it, e.g. HP-UX.
libmongoc_VERSION_MAJOR=$( (cat $MONGOC_CURRENT_FILE; echo) | cut -d- -f1 | cut -d. -f1 )
libmongoc_VERSION_MINOR=$( (cat $MONGOC_CURRENT_FILE; echo) | cut -d- -f1 | cut -d. -f2 )
libmongoc_VERSION_PATCH=$( (cat $MONGOC_CURRENT_FILE; echo) | cut -d- -f1 | cut -d. -f3 )
libmongoc_VERSION_PRERELEASE=$(cut -s -d- -f2 $MONGOC_CURRENT_FILE)
AC_SUBST(libmongoc_VERSION_FULL)
AC_SUBST(libmongoc_VERSION_MAJOR)
AC_SUBST(libmongoc_VERSION_MINOR)
AC_SUBST(libmongoc_VERSION_PATCH)
AC_SUBST(libmongoc_VERSION_PRERELEASE)
mongodb-2.1.0/scripts/autotools/libmongocrypt/CheckSSL.m4 0000644 0001751 0000166 00000002167 15014033047 020334 0 ustar if test "$PHP_MONGODB_CLIENT_SIDE_ENCRYPTION" != "no"; then
AC_MSG_CHECKING([which crypto library to use for libmongocrypt])
AC_MSG_RESULT([$PHP_MONGODB_SSL])
dnl Disable Windows crypto
AC_SUBST(MONGOCRYPT_ENABLE_CRYPTO_CNG, 0)
if test "$PHP_MONGODB_SSL" = "darwin"; then
PHP_MONGODB_CLIENT_SIDE_ENCRYPTION="yes"
AC_SUBST(MONGOCRYPT_ENABLE_CRYPTO, 1)
AC_SUBST(MONGOCRYPT_ENABLE_CRYPTO_LIBCRYPTO, 0)
AC_SUBST(MONGOCRYPT_ENABLE_CRYPTO_COMMON_CRYPTO, 1)
elif test "$PHP_MONGODB_SSL" = "openssl" -o "$PHP_MONGODB_SSL" = "libressl"; then
PHP_MONGODB_CLIENT_SIDE_ENCRYPTION="yes"
AC_SUBST(MONGOCRYPT_ENABLE_CRYPTO, 1)
AC_SUBST(MONGOCRYPT_ENABLE_CRYPTO_LIBCRYPTO, 1)
AC_SUBST(MONGOCRYPT_ENABLE_CRYPTO_COMMON_CRYPTO, 0)
elif test "$PHP_MONGODB_CLIENT_SIDE_ENCRYPTION" = "auto"; then
PHP_MONGODB_CLIENT_SIDE_ENCRYPTION="no"
AC_MSG_RESULT(No SSL library found. Compiling without libmongocrypt. Please specify a library using the --with-mongodb-ssl option)
else
AC_MSG_ERROR(Need an SSL library to compile with libmongocrypt. Please specify it using the --with-mongodb-ssl option)
fi
fi
mongodb-2.1.0/scripts/autotools/libmongocrypt/Endian.m4 0000644 0001751 0000166 00000000570 15014033047 020127 0 ustar AC_C_BIGENDIAN(
[PHP_MONGODB_LIBMONGOCRYPT_CFLAGS="$PHP_MONGODB_LIBMONGOCRYPT_CFLAGS -DKMS_MESSAGE_BIG_ENDIAN=1 -DMONGOCRYPT_BIG_ENDIAN=1"],
[PHP_MONGODB_LIBMONGOCRYPT_CFLAGS="$PHP_MONGODB_LIBMONGOCRYPT_CFLAGS -DKMS_MESSAGE_LITTLE_ENDIAN=1 -DMONGOCRYPT_LITTLE_ENDIAN=1"],
[AC_MSG_ERROR([unknown endianness])],
[AC_MSG_ERROR([universal endianness is not supported])]
)
mongodb-2.1.0/scripts/autotools/libmongocrypt/Version.m4 0000644 0001751 0000166 00000000370 15014033047 020354 0 ustar if test "$PHP_MONGODB_CLIENT_SIDE_ENCRYPTION" = "yes"; then
MONGOCRYPT_CURRENT_FILE=[]PHP_EXT_SRCDIR(mongodb)[/src/LIBMONGOCRYPT_VERSION_CURRENT]
MONGOCRYPT_BUILD_VERSION=$(cat $MONGOCRYPT_CURRENT_FILE)
AC_SUBST(MONGOCRYPT_BUILD_VERSION)
fi
mongodb-2.1.0/scripts/autotools/m4/ax_check_compile_flag.m4 0000644 0001751 0000166 00000004070 15014033047 020626 0 ustar # ===========================================================================
# https://www.gnu.org/software/autoconf-archive/ax_check_compile_flag.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_CHECK_COMPILE_FLAG(FLAG, [ACTION-SUCCESS], [ACTION-FAILURE], [EXTRA-FLAGS], [INPUT])
#
# DESCRIPTION
#
# Check whether the given FLAG works with the current language's compiler
# or gives an error. (Warnings, however, are ignored)
#
# ACTION-SUCCESS/ACTION-FAILURE are shell commands to execute on
# success/failure.
#
# If EXTRA-FLAGS is defined, it is added to the current language's default
# flags (e.g. CFLAGS) when the check is done. The check is thus made with
# the flags: "CFLAGS EXTRA-FLAGS FLAG". This can for example be used to
# force the compiler to issue an error when a bad flag is given.
#
# INPUT gives an alternative input source to AC_COMPILE_IFELSE.
#
# NOTE: Implementation based on AX_CFLAGS_GCC_OPTION. Please keep this
# macro in sync with AX_CHECK_{PREPROC,LINK}_FLAG.
#
# LICENSE
#
# Copyright (c) 2008 Guido U. Draheim
# Copyright (c) 2011 Maarten Bosmans
#
# Copying and distribution of this file, with or without modification, are
# permitted in any medium without royalty provided the copyright notice
# and this notice are preserved. This file is offered as-is, without any
# warranty.
#serial 6
AC_DEFUN([AX_CHECK_COMPILE_FLAG],
[AC_PREREQ(2.64)dnl for _AC_LANG_PREFIX and AS_VAR_IF
AS_VAR_PUSHDEF([CACHEVAR],[ax_cv_check_[]_AC_LANG_ABBREV[]flags_$4_$1])dnl
AC_CACHE_CHECK([whether _AC_LANG compiler accepts $1], CACHEVAR, [
ax_check_save_flags=$[]_AC_LANG_PREFIX[]FLAGS
_AC_LANG_PREFIX[]FLAGS="$[]_AC_LANG_PREFIX[]FLAGS $4 $1"
AC_COMPILE_IFELSE([m4_default([$5],[AC_LANG_PROGRAM()])],
[AS_VAR_SET(CACHEVAR,[yes])],
[AS_VAR_SET(CACHEVAR,[no])])
_AC_LANG_PREFIX[]FLAGS=$ax_check_save_flags])
AS_VAR_IF(CACHEVAR,yes,
[m4_default([$2], :)],
[m4_default([$3], :)])
AS_VAR_POPDEF([CACHEVAR])dnl
])dnl AX_CHECK_COMPILE_FLAGS
mongodb-2.1.0/scripts/autotools/m4/ax_prototype.m4 0000644 0001751 0000166 00000020112 15014033047 017110 0 ustar # ===========================================================================
# https://www.gnu.org/software/autoconf-archive/ax_prototype.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_PROTOTYPE(function, includes, code, TAG1, values1 [, TAG2, values2 [...]])
#
# DESCRIPTION
#
# Try all the combinations of , ... to successfully compile
# . , , ... are substituted in and with
# values found in , , ... respectively. ,
# , ... contain a list of possible values for each corresponding
# tag and all combinations are tested. When AC_TRY_COMPILE(include, code)
# is successful for a given substitution, the macro stops and defines the
# following macros: FUNCTION_TAG1, FUNCTION_TAG2, ... using AC_DEFINE()
# with values set to the current values of , , ... If no
# combination is successful the configure script is aborted with a
# message.
#
# Intended purpose is to find which combination of argument types is
# acceptable for a given function . It is recommended to list
# the most specific types first. For instance ARG1, [size_t, int] instead
# of ARG1, [int, size_t].
#
# Generic usage pattern:
#
# 1) add a call in configure.ac
#
# AX_PROTOTYPE(...)
#
# 2) call autoheader to see which symbols are not covered
#
# 3) add the lines in config.h
#
# /* Type of Nth argument of function */
# #undef FUNCTION_ARGN
#
# 4) Within the code use FUNCTION_ARGN instead of an hardwired type
#
# Complete example:
#
# 1) configure.ac
#
# AX_PROTOTYPE(getpeername,
# [
# #include
# #include
# ],
# [
# int a = 0;
# ARG2 * b = 0;
# ARG3 * c = 0;
# getpeername(a, b, c);
# ],
# ARG2, [struct sockaddr, void],
# ARG3, [socklen_t, size_t, int, unsigned int, long unsigned int])
#
# 2) call autoheader
#
# autoheader: Symbol `GETPEERNAME_ARG2' is not covered by ./config.h
# autoheader: Symbol `GETPEERNAME_ARG3' is not covered by ./config.h
#
# 3) config.h
#
# /* Type of second argument of getpeername */
# #undef GETPEERNAME_ARG2
#
# /* Type of third argument of getpeername */
# #undef GETPEERNAME_ARG3
#
# 4) in the code
#
# ...
# GETPEERNAME_ARG2 name;
# GETPEERNAME_ARG3 namelen;
# ...
# ret = getpeername(socket, &name, &namelen);
# ...
#
# Implementation notes: generating all possible permutations of the
# arguments is not easily done with the usual mixture of shell and m4,
# that is why this macro is almost 100% m4 code. It generates long but
# simple to read code.
#
# LICENSE
#
# Copyright (c) 2009 Loic Dachary
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see .
#
# As a special exception, the respective Autoconf Macro's copyright owner
# gives unlimited permission to copy, distribute and modify the configure
# scripts that are the output of Autoconf when processing the Macro. You
# need not follow the terms of the GNU General Public License when using
# or distributing such scripts, even though portions of the text of the
# Macro appear in them. The GNU General Public License (GPL) does govern
# all other use of the material that constitutes the Autoconf Macro.
#
# This special exception to the GPL applies to versions of the Autoconf
# Macro released by the Autoconf Archive. When you make and distribute a
# modified version of the Autoconf Macro, you may extend this special
# exception to the GPL to apply to your modified version as well.
#serial 11
AU_ALIAS([AC_PROTOTYPE], [AX_PROTOTYPE])
AC_DEFUN([AX_PROTOTYPE],[
dnl
dnl Upper case function name
dnl
pushdef([function],translit([$1], [a-z], [A-Z]))
dnl
dnl Collect tags that will be substituted
dnl
pushdef([tags],[AX_PROTOTYPE_TAGS(builtin([shift],builtin([shift],builtin([shift],$@))))])
dnl
dnl Wrap in a 1 time loop, when a combination is found break to stop the combinatory exploration
dnl
for i in 1
do
AX_PROTOTYPE_LOOP(AX_PROTOTYPE_REVERSE($1, AX_PROTOTYPE_SUBST($2,tags),AX_PROTOTYPE_SUBST($3,tags),builtin([shift],builtin([shift],builtin([shift],$@)))))
AC_MSG_ERROR($1 unable to find a working combination)
done
popdef([tags])
popdef([function])
])
dnl
dnl AX_PROTOTYPE_REVERSE(list)
dnl
dnl Reverse the order of the
dnl
AC_DEFUN([AX_PROTOTYPE_REVERSE],[ifelse($#,0,,$#,1,[[$1]],[AX_PROTOTYPE_REVERSE(builtin([shift],$@)),[$1]])])
dnl
dnl AX_PROTOTYPE_SUBST(string, tag)
dnl
dnl Substitute all occurrence of in with _VAL.
dnl Assumes that tag_VAL is a macro containing the value associated to tag.
dnl
AC_DEFUN([AX_PROTOTYPE_SUBST],[ifelse($2,,[$1],[AX_PROTOTYPE_SUBST(patsubst([$1],[$2],[$2[]_VAL]),builtin([shift],builtin([shift],$@)))])])
dnl
dnl AX_PROTOTYPE_TAGS([tag, values, [tag, values ...]])
dnl
dnl Generate a list of by skipping .
dnl
AC_DEFUN([AX_PROTOTYPE_TAGS],[ifelse($1,,[],[$1, AX_PROTOTYPE_TAGS(builtin([shift],builtin([shift],$@)))])])
dnl
dnl AX_PROTOTYPE_DEFINES(tags)
dnl
dnl Generate a AC_DEFINE(function_tag, tag_VAL) for each tag in list
dnl Assumes that function is a macro containing the name of the function in upper case
dnl and that tag_VAL is a macro containing the value associated to tag.
dnl
AC_DEFUN([AX_PROTOTYPE_DEFINES],[ifelse($1,,[],
[AC_DEFINE(function[]_$1, $1_VAL)
AC_SUBST(function[]_$1, "$1_VAL")
AX_PROTOTYPE_DEFINES(builtin([shift],$@))])])
dnl
dnl AX_PROTOTYPE_STATUS(tags)
dnl
dnl Generates a message suitable for argument to AC_MSG_* macros. For each tag
dnl in the list the message tag => tag_VAL is generated.
dnl Assumes that tag_VAL is a macro containing the value associated to tag.
dnl
AC_DEFUN([AX_PROTOTYPE_STATUS],[ifelse($1,,[],[$1 => $1_VAL AX_PROTOTYPE_STATUS(builtin([shift],$@))])])
dnl
dnl AX_PROTOTYPE_EACH(tag, values)
dnl
dnl Call AX_PROTOTYPE_LOOP for each values and define the macro tag_VAL to
dnl the current value.
dnl
AC_DEFUN([AX_PROTOTYPE_EACH],[
ifelse($2,, [
], [
pushdef([$1_VAL], $2)
AX_PROTOTYPE_LOOP(rest)
popdef([$1_VAL])
AX_PROTOTYPE_EACH($1, builtin([shift], builtin([shift], $@)))
])
])
dnl
dnl AX_PROTOTYPE_LOOP([tag, values, [tag, values ...]], code, include, function)
dnl
dnl If there is a tag/values pair, call AX_PROTOTYPE_EACH with it.
dnl If there is no tag/values pair left, tries to compile the code and include
dnl using AC_TRY_COMPILE. If it compiles, AC_DEFINE all the tags to their
dnl current value and exit with success.
dnl
AC_DEFUN([AX_PROTOTYPE_LOOP],[
ifelse(builtin([eval], $# > 3), 1,
[
pushdef([rest],[builtin([shift],builtin([shift],$@))])
AX_PROTOTYPE_EACH($2,$1)
popdef([rest])
], [
AC_MSG_CHECKING($3 AX_PROTOTYPE_STATUS(tags))
dnl
dnl Activate fatal warnings if possible, gives better guess
dnl
ac_save_CPPFLAGS="$CPPFLAGS"
dnl ifelse(AC_LANG,CPLUSPLUS,if test "$GXX" = "yes" ; then CPPFLAGS="$CPPFLAGS -Werror" ; fi)
dnl ifelse(AC_LANG,C,if test "$GCC" = "yes" ; then CPPFLAGS="$CPPFLAGS -Werror" ; fi)
dnl
dnl Disable the 'unused-variable' warning in case e.g. -Wall was enabled,
dnl otherwise the test may always fail.
dnl
if (test "x$GCC" = "xyes" || test "x$GXX" = "xyes" ); then
CPPFLAGS="$CPPFLAGS -Werror -Wno-unused-variable" ;
fi
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([$2], [$1])],
[
CPPFLAGS="$ac_save_CPPFLAGS"
AC_MSG_RESULT(ok)
AX_PROTOTYPE_DEFINES(tags)
break;
], [
CPPFLAGS="$ac_save_CPPFLAGS"
AC_MSG_RESULT(not ok)
])
]
)
])
mongodb-2.1.0/scripts/autotools/m4/ax_prototype_accept.m4 0000644 0001751 0000166 00000004673 15014033047 020445 0 ustar # ===========================================================================
# https://www.gnu.org/software/autoconf-archive/ax_prototype_accept.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_PROTOTYPE_ACCEPT
#
# DESCRIPTION
#
# Requires the AX_PROTOTYPE macro. FIXME: Put this in the code!
#
# Find the type of argument two and three of accept. User must include the
# following in acconfig.h:
#
# /* Type of second argument of accept */
# #undef ACCEPT_ARG2
#
# /* Type of third argument of accept */
# #undef ACCEPT_ARG3
#
# LICENSE
#
# Copyright (c) 2008 Loic Dachary
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 2 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see .
#
# As a special exception, the respective Autoconf Macro's copyright owner
# gives unlimited permission to copy, distribute and modify the configure
# scripts that are the output of Autoconf when processing the Macro. You
# need not follow the terms of the GNU General Public License when using
# or distributing such scripts, even though portions of the text of the
# Macro appear in them. The GNU General Public License (GPL) does govern
# all other use of the material that constitutes the Autoconf Macro.
#
# This special exception to the GPL applies to versions of the Autoconf
# Macro released by the Autoconf Archive. When you make and distribute a
# modified version of the Autoconf Macro, you may extend this special
# exception to the GPL to apply to your modified version as well.
#serial 6
AU_ALIAS([AC_PROTOTYPE_ACCEPT], [AX_PROTOTYPE_ACCEPT])
AC_DEFUN([AX_PROTOTYPE_ACCEPT],[
AX_PROTOTYPE(accept,
[
#include
#include
],
[
int a = 0;
ARG2 * b = 0;
ARG3 * c = 0;
accept(a, b, c);
],
ARG2, [struct sockaddr, void],
ARG3, [socklen_t, size_t, int, unsigned int, long unsigned int])
])
mongodb-2.1.0/scripts/autotools/m4/ax_pthread.m4 0000644 0001751 0000166 00000054122 15014033047 016502 0 ustar # ===========================================================================
# https://www.gnu.org/software/autoconf-archive/ax_pthread.html
# ===========================================================================
#
# SYNOPSIS
#
# AX_PTHREAD([ACTION-IF-FOUND[, ACTION-IF-NOT-FOUND]])
#
# DESCRIPTION
#
# This macro figures out how to build C programs using POSIX threads. It
# sets the PTHREAD_LIBS output variable to the threads library and linker
# flags, and the PTHREAD_CFLAGS output variable to any special C compiler
# flags that are needed. (The user can also force certain compiler
# flags/libs to be tested by setting these environment variables.)
#
# Also sets PTHREAD_CC and PTHREAD_CXX to any special C compiler that is
# needed for multi-threaded programs (defaults to the value of CC
# respectively CXX otherwise). (This is necessary on e.g. AIX to use the
# special cc_r/CC_r compiler alias.)
#
# NOTE: You are assumed to not only compile your program with these flags,
# but also to link with them as well. For example, you might link with
# $PTHREAD_CC $CFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS $LIBS
# $PTHREAD_CXX $CXXFLAGS $PTHREAD_CFLAGS $LDFLAGS ... $PTHREAD_LIBS $LIBS
#
# If you are only building threaded programs, you may wish to use these
# variables in your default LIBS, CFLAGS, and CC:
#
# LIBS="$PTHREAD_LIBS $LIBS"
# CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
# CXXFLAGS="$CXXFLAGS $PTHREAD_CFLAGS"
# CC="$PTHREAD_CC"
# CXX="$PTHREAD_CXX"
#
# In addition, if the PTHREAD_CREATE_JOINABLE thread-attribute constant
# has a nonstandard name, this macro defines PTHREAD_CREATE_JOINABLE to
# that name (e.g. PTHREAD_CREATE_UNDETACHED on AIX).
#
# Also HAVE_PTHREAD_PRIO_INHERIT is defined if pthread is found and the
# PTHREAD_PRIO_INHERIT symbol is defined when compiling with
# PTHREAD_CFLAGS.
#
# ACTION-IF-FOUND is a list of shell commands to run if a threads library
# is found, and ACTION-IF-NOT-FOUND is a list of commands to run it if it
# is not found. If ACTION-IF-FOUND is not specified, the default action
# will define HAVE_PTHREAD.
#
# Please let the authors know if this macro fails on any platform, or if
# you have any other suggestions or comments. This macro was based on work
# by SGJ on autoconf scripts for FFTW (http://www.fftw.org/) (with help
# from M. Frigo), as well as ac_pthread and hb_pthread macros posted by
# Alejandro Forero Cuervo to the autoconf macro repository. We are also
# grateful for the helpful feedback of numerous users.
#
# Updated for Autoconf 2.68 by Daniel Richard G.
#
# LICENSE
#
# Copyright (c) 2008 Steven G. Johnson
# Copyright (c) 2011 Daniel Richard G.
# Copyright (c) 2019 Marc Stevens
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see .
#
# As a special exception, the respective Autoconf Macro's copyright owner
# gives unlimited permission to copy, distribute and modify the configure
# scripts that are the output of Autoconf when processing the Macro. You
# need not follow the terms of the GNU General Public License when using
# or distributing such scripts, even though portions of the text of the
# Macro appear in them. The GNU General Public License (GPL) does govern
# all other use of the material that constitutes the Autoconf Macro.
#
# This special exception to the GPL applies to versions of the Autoconf
# Macro released by the Autoconf Archive. When you make and distribute a
# modified version of the Autoconf Macro, you may extend this special
# exception to the GPL to apply to your modified version as well.
#serial 31
AU_ALIAS([ACX_PTHREAD], [AX_PTHREAD])
AC_DEFUN([AX_PTHREAD], [
AC_REQUIRE([AC_CANONICAL_HOST])
AC_REQUIRE([AC_PROG_CC])
AC_REQUIRE([AC_PROG_SED])
AC_LANG_PUSH([C])
ax_pthread_ok=no
# We used to check for pthread.h first, but this fails if pthread.h
# requires special compiler flags (e.g. on Tru64 or Sequent).
# It gets checked for in the link test anyway.
# First of all, check if the user has set any of the PTHREAD_LIBS,
# etcetera environment variables, and if threads linking works using
# them:
if test "x$PTHREAD_CFLAGS$PTHREAD_LIBS" != "x"; then
ax_pthread_save_CC="$CC"
ax_pthread_save_CFLAGS="$CFLAGS"
ax_pthread_save_LIBS="$LIBS"
AS_IF([test "x$PTHREAD_CC" != "x"], [CC="$PTHREAD_CC"])
AS_IF([test "x$PTHREAD_CXX" != "x"], [CXX="$PTHREAD_CXX"])
CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
LIBS="$PTHREAD_LIBS $LIBS"
AC_MSG_CHECKING([for pthread_join using $CC $PTHREAD_CFLAGS $PTHREAD_LIBS])
AC_LINK_IFELSE([AC_LANG_CALL([], [pthread_join])], [ax_pthread_ok=yes])
AC_MSG_RESULT([$ax_pthread_ok])
if test "x$ax_pthread_ok" = "xno"; then
PTHREAD_LIBS=""
PTHREAD_CFLAGS=""
fi
CC="$ax_pthread_save_CC"
CFLAGS="$ax_pthread_save_CFLAGS"
LIBS="$ax_pthread_save_LIBS"
fi
# We must check for the threads library under a number of different
# names; the ordering is very important because some systems
# (e.g. DEC) have both -lpthread and -lpthreads, where one of the
# libraries is broken (non-POSIX).
# Create a list of thread flags to try. Items with a "," contain both
# C compiler flags (before ",") and linker flags (after ","). Other items
# starting with a "-" are C compiler flags, and remaining items are
# library names, except for "none" which indicates that we try without
# any flags at all, and "pthread-config" which is a program returning
# the flags for the Pth emulation library.
ax_pthread_flags="pthreads none -Kthread -pthread -pthreads -mthreads pthread --thread-safe -mt pthread-config"
# The ordering *is* (sometimes) important. Some notes on the
# individual items follow:
# pthreads: AIX (must check this before -lpthread)
# none: in case threads are in libc; should be tried before -Kthread and
# other compiler flags to prevent continual compiler warnings
# -Kthread: Sequent (threads in libc, but -Kthread needed for pthread.h)
# -pthread: Linux/gcc (kernel threads), BSD/gcc (userland threads), Tru64
# (Note: HP C rejects this with "bad form for `-t' option")
# -pthreads: Solaris/gcc (Note: HP C also rejects)
# -mt: Sun Workshop C (may only link SunOS threads [-lthread], but it
# doesn't hurt to check since this sometimes defines pthreads and
# -D_REENTRANT too), HP C (must be checked before -lpthread, which
# is present but should not be used directly; and before -mthreads,
# because the compiler interprets this as "-mt" + "-hreads")
# -mthreads: Mingw32/gcc, Lynx/gcc
# pthread: Linux, etcetera
# --thread-safe: KAI C++
# pthread-config: use pthread-config program (for GNU Pth library)
case $host_os in
freebsd*)
# -kthread: FreeBSD kernel threads (preferred to -pthread since SMP-able)
# lthread: LinuxThreads port on FreeBSD (also preferred to -pthread)
ax_pthread_flags="-kthread lthread $ax_pthread_flags"
;;
hpux*)
# From the cc(1) man page: "[-mt] Sets various -D flags to enable
# multi-threading and also sets -lpthread."
ax_pthread_flags="-mt -pthread pthread $ax_pthread_flags"
;;
openedition*)
# IBM z/OS requires a feature-test macro to be defined in order to
# enable POSIX threads at all, so give the user a hint if this is
# not set. (We don't define these ourselves, as they can affect
# other portions of the system API in unpredictable ways.)
AC_EGREP_CPP([AX_PTHREAD_ZOS_MISSING],
[
# if !defined(_OPEN_THREADS) && !defined(_UNIX03_THREADS)
AX_PTHREAD_ZOS_MISSING
# endif
],
[AC_MSG_WARN([IBM z/OS requires -D_OPEN_THREADS or -D_UNIX03_THREADS to enable pthreads support.])])
;;
solaris*)
# On Solaris (at least, for some versions), libc contains stubbed
# (non-functional) versions of the pthreads routines, so link-based
# tests will erroneously succeed. (N.B.: The stubs are missing
# pthread_cleanup_push, or rather a function called by this macro,
# so we could check for that, but who knows whether they'll stub
# that too in a future libc.) So we'll check first for the
# standard Solaris way of linking pthreads (-mt -lpthread).
ax_pthread_flags="-mt,-lpthread pthread $ax_pthread_flags"
;;
esac
# Are we compiling with Clang?
AC_CACHE_CHECK([whether $CC is Clang],
[ax_cv_PTHREAD_CLANG],
[ax_cv_PTHREAD_CLANG=no
# Note that Autoconf sets GCC=yes for Clang as well as GCC
if test "x$GCC" = "xyes"; then
AC_EGREP_CPP([AX_PTHREAD_CC_IS_CLANG],
[/* Note: Clang 2.7 lacks __clang_[a-z]+__ */
# if defined(__clang__) && defined(__llvm__)
AX_PTHREAD_CC_IS_CLANG
# endif
],
[ax_cv_PTHREAD_CLANG=yes])
fi
])
ax_pthread_clang="$ax_cv_PTHREAD_CLANG"
# GCC generally uses -pthread, or -pthreads on some platforms (e.g. SPARC)
# Note that for GCC and Clang -pthread generally implies -lpthread,
# except when -nostdlib is passed.
# This is problematic using libtool to build C++ shared libraries with pthread:
# [1] https://gcc.gnu.org/bugzilla/show_bug.cgi?id=25460
# [2] https://bugzilla.redhat.com/show_bug.cgi?id=661333
# [3] https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=468555
# To solve this, first try -pthread together with -lpthread for GCC
AS_IF([test "x$GCC" = "xyes"],
[ax_pthread_flags="-pthread,-lpthread -pthread -pthreads $ax_pthread_flags"])
# Clang takes -pthread (never supported any other flag), but we'll try with -lpthread first
AS_IF([test "x$ax_pthread_clang" = "xyes"],
[ax_pthread_flags="-pthread,-lpthread -pthread"])
# The presence of a feature test macro requesting re-entrant function
# definitions is, on some systems, a strong hint that pthreads support is
# correctly enabled
case $host_os in
darwin* | hpux* | linux* | osf* | solaris*)
ax_pthread_check_macro="_REENTRANT"
;;
aix*)
ax_pthread_check_macro="_THREAD_SAFE"
;;
*)
ax_pthread_check_macro="--"
;;
esac
AS_IF([test "x$ax_pthread_check_macro" = "x--"],
[ax_pthread_check_cond=0],
[ax_pthread_check_cond="!defined($ax_pthread_check_macro)"])
if test "x$ax_pthread_ok" = "xno"; then
for ax_pthread_try_flag in $ax_pthread_flags; do
case $ax_pthread_try_flag in
none)
AC_MSG_CHECKING([whether pthreads work without any flags])
;;
*,*)
PTHREAD_CFLAGS=`echo $ax_pthread_try_flag | sed "s/^\(.*\),\(.*\)$/\1/"`
PTHREAD_LIBS=`echo $ax_pthread_try_flag | sed "s/^\(.*\),\(.*\)$/\2/"`
AC_MSG_CHECKING([whether pthreads work with "$PTHREAD_CFLAGS" and "$PTHREAD_LIBS"])
;;
-*)
AC_MSG_CHECKING([whether pthreads work with $ax_pthread_try_flag])
PTHREAD_CFLAGS="$ax_pthread_try_flag"
;;
pthread-config)
AC_CHECK_PROG([ax_pthread_config], [pthread-config], [yes], [no])
AS_IF([test "x$ax_pthread_config" = "xno"], [continue])
PTHREAD_CFLAGS="`pthread-config --cflags`"
PTHREAD_LIBS="`pthread-config --ldflags` `pthread-config --libs`"
;;
*)
AC_MSG_CHECKING([for the pthreads library -l$ax_pthread_try_flag])
PTHREAD_LIBS="-l$ax_pthread_try_flag"
;;
esac
ax_pthread_save_CFLAGS="$CFLAGS"
ax_pthread_save_LIBS="$LIBS"
CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
LIBS="$PTHREAD_LIBS $LIBS"
# Check for various functions. We must include pthread.h,
# since some functions may be macros. (On the Sequent, we
# need a special flag -Kthread to make this header compile.)
# We check for pthread_join because it is in -lpthread on IRIX
# while pthread_create is in libc. We check for pthread_attr_init
# due to DEC craziness with -lpthreads. We check for
# pthread_cleanup_push because it is one of the few pthread
# functions on Solaris that doesn't have a non-functional libc stub.
# We try pthread_create on general principles.
AC_LINK_IFELSE([AC_LANG_PROGRAM([#include
# if $ax_pthread_check_cond
# error "$ax_pthread_check_macro must be defined"
# endif
static void *some_global = NULL;
static void routine(void *a)
{
/* To avoid any unused-parameter or
unused-but-set-parameter warning. */
some_global = a;
}
static void *start_routine(void *a) { return a; }],
[pthread_t th; pthread_attr_t attr;
pthread_create(&th, 0, start_routine, 0);
pthread_join(th, 0);
pthread_attr_init(&attr);
pthread_cleanup_push(routine, 0);
pthread_cleanup_pop(0) /* ; */])],
[ax_pthread_ok=yes],
[])
CFLAGS="$ax_pthread_save_CFLAGS"
LIBS="$ax_pthread_save_LIBS"
AC_MSG_RESULT([$ax_pthread_ok])
AS_IF([test "x$ax_pthread_ok" = "xyes"], [break])
PTHREAD_LIBS=""
PTHREAD_CFLAGS=""
done
fi
# Clang needs special handling, because older versions handle the -pthread
# option in a rather... idiosyncratic way
if test "x$ax_pthread_clang" = "xyes"; then
# Clang takes -pthread; it has never supported any other flag
# (Note 1: This will need to be revisited if a system that Clang
# supports has POSIX threads in a separate library. This tends not
# to be the way of modern systems, but it's conceivable.)
# (Note 2: On some systems, notably Darwin, -pthread is not needed
# to get POSIX threads support; the API is always present and
# active. We could reasonably leave PTHREAD_CFLAGS empty. But
# -pthread does define _REENTRANT, and while the Darwin headers
# ignore this macro, third-party headers might not.)
# However, older versions of Clang make a point of warning the user
# that, in an invocation where only linking and no compilation is
# taking place, the -pthread option has no effect ("argument unused
# during compilation"). They expect -pthread to be passed in only
# when source code is being compiled.
#
# Problem is, this is at odds with the way Automake and most other
# C build frameworks function, which is that the same flags used in
# compilation (CFLAGS) are also used in linking. Many systems
# supported by AX_PTHREAD require exactly this for POSIX threads
# support, and in fact it is often not straightforward to specify a
# flag that is used only in the compilation phase and not in
# linking. Such a scenario is extremely rare in practice.
#
# Even though use of the -pthread flag in linking would only print
# a warning, this can be a nuisance for well-run software projects
# that build with -Werror. So if the active version of Clang has
# this misfeature, we search for an option to squash it.
AC_CACHE_CHECK([whether Clang needs flag to prevent "argument unused" warning when linking with -pthread],
[ax_cv_PTHREAD_CLANG_NO_WARN_FLAG],
[ax_cv_PTHREAD_CLANG_NO_WARN_FLAG=unknown
# Create an alternate version of $ac_link that compiles and
# links in two steps (.c -> .o, .o -> exe) instead of one
# (.c -> exe), because the warning occurs only in the second
# step
ax_pthread_save_ac_link="$ac_link"
ax_pthread_sed='s/conftest\.\$ac_ext/conftest.$ac_objext/g'
ax_pthread_link_step=`AS_ECHO(["$ac_link"]) | sed "$ax_pthread_sed"`
ax_pthread_2step_ac_link="($ac_compile) && (echo ==== >&5) && ($ax_pthread_link_step)"
ax_pthread_save_CFLAGS="$CFLAGS"
for ax_pthread_try in '' -Qunused-arguments -Wno-unused-command-line-argument unknown; do
AS_IF([test "x$ax_pthread_try" = "xunknown"], [break])
CFLAGS="-Werror -Wunknown-warning-option $ax_pthread_try -pthread $ax_pthread_save_CFLAGS"
ac_link="$ax_pthread_save_ac_link"
AC_LINK_IFELSE([AC_LANG_SOURCE([[int main(void){return 0;}]])],
[ac_link="$ax_pthread_2step_ac_link"
AC_LINK_IFELSE([AC_LANG_SOURCE([[int main(void){return 0;}]])],
[break])
])
done
ac_link="$ax_pthread_save_ac_link"
CFLAGS="$ax_pthread_save_CFLAGS"
AS_IF([test "x$ax_pthread_try" = "x"], [ax_pthread_try=no])
ax_cv_PTHREAD_CLANG_NO_WARN_FLAG="$ax_pthread_try"
])
case "$ax_cv_PTHREAD_CLANG_NO_WARN_FLAG" in
no | unknown) ;;
*) PTHREAD_CFLAGS="$ax_cv_PTHREAD_CLANG_NO_WARN_FLAG $PTHREAD_CFLAGS" ;;
esac
fi # $ax_pthread_clang = yes
# Various other checks:
if test "x$ax_pthread_ok" = "xyes"; then
ax_pthread_save_CFLAGS="$CFLAGS"
ax_pthread_save_LIBS="$LIBS"
CFLAGS="$CFLAGS $PTHREAD_CFLAGS"
LIBS="$PTHREAD_LIBS $LIBS"
# Detect AIX lossage: JOINABLE attribute is called UNDETACHED.
AC_CACHE_CHECK([for joinable pthread attribute],
[ax_cv_PTHREAD_JOINABLE_ATTR],
[ax_cv_PTHREAD_JOINABLE_ATTR=unknown
for ax_pthread_attr in PTHREAD_CREATE_JOINABLE PTHREAD_CREATE_UNDETACHED; do
AC_LINK_IFELSE([AC_LANG_PROGRAM([#include ],
[int attr = $ax_pthread_attr; return attr /* ; */])],
[ax_cv_PTHREAD_JOINABLE_ATTR=$ax_pthread_attr; break],
[])
done
])
AS_IF([test "x$ax_cv_PTHREAD_JOINABLE_ATTR" != "xunknown" && \
test "x$ax_cv_PTHREAD_JOINABLE_ATTR" != "xPTHREAD_CREATE_JOINABLE" && \
test "x$ax_pthread_joinable_attr_defined" != "xyes"],
[AC_DEFINE_UNQUOTED([PTHREAD_CREATE_JOINABLE],
[$ax_cv_PTHREAD_JOINABLE_ATTR],
[Define to necessary symbol if this constant
uses a non-standard name on your system.])
ax_pthread_joinable_attr_defined=yes
])
AC_CACHE_CHECK([whether more special flags are required for pthreads],
[ax_cv_PTHREAD_SPECIAL_FLAGS],
[ax_cv_PTHREAD_SPECIAL_FLAGS=no
case $host_os in
solaris*)
ax_cv_PTHREAD_SPECIAL_FLAGS="-D_POSIX_PTHREAD_SEMANTICS"
;;
esac
])
AS_IF([test "x$ax_cv_PTHREAD_SPECIAL_FLAGS" != "xno" && \
test "x$ax_pthread_special_flags_added" != "xyes"],
[PTHREAD_CFLAGS="$ax_cv_PTHREAD_SPECIAL_FLAGS $PTHREAD_CFLAGS"
ax_pthread_special_flags_added=yes])
AC_CACHE_CHECK([for PTHREAD_PRIO_INHERIT],
[ax_cv_PTHREAD_PRIO_INHERIT],
[AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include ]],
[[int i = PTHREAD_PRIO_INHERIT;
return i;]])],
[ax_cv_PTHREAD_PRIO_INHERIT=yes],
[ax_cv_PTHREAD_PRIO_INHERIT=no])
])
AS_IF([test "x$ax_cv_PTHREAD_PRIO_INHERIT" = "xyes" && \
test "x$ax_pthread_prio_inherit_defined" != "xyes"],
[AC_DEFINE([HAVE_PTHREAD_PRIO_INHERIT], [1], [Have PTHREAD_PRIO_INHERIT.])
ax_pthread_prio_inherit_defined=yes
])
CFLAGS="$ax_pthread_save_CFLAGS"
LIBS="$ax_pthread_save_LIBS"
# More AIX lossage: compile with *_r variant
if test "x$GCC" != "xyes"; then
case $host_os in
aix*)
AS_CASE(["x/$CC"],
[x*/c89|x*/c89_128|x*/c99|x*/c99_128|x*/cc|x*/cc128|x*/xlc|x*/xlc_v6|x*/xlc128|x*/xlc128_v6],
[#handle absolute path differently from PATH based program lookup
AS_CASE(["x$CC"],
[x/*],
[
AS_IF([AS_EXECUTABLE_P([${CC}_r])],[PTHREAD_CC="${CC}_r"])
AS_IF([test "x${CXX}" != "x"], [AS_IF([AS_EXECUTABLE_P([${CXX}_r])],[PTHREAD_CXX="${CXX}_r"])])
],
[
AC_CHECK_PROGS([PTHREAD_CC],[${CC}_r],[$CC])
AS_IF([test "x${CXX}" != "x"], [AC_CHECK_PROGS([PTHREAD_CXX],[${CXX}_r],[$CXX])])
]
)
])
;;
esac
fi
fi
test -n "$PTHREAD_CC" || PTHREAD_CC="$CC"
test -n "$PTHREAD_CXX" || PTHREAD_CXX="$CXX"
AC_SUBST([PTHREAD_LIBS])
AC_SUBST([PTHREAD_CFLAGS])
AC_SUBST([PTHREAD_CC])
AC_SUBST([PTHREAD_CXX])
# Finally, execute ACTION-IF-FOUND/ACTION-IF-NOT-FOUND:
if test "x$ax_pthread_ok" = "xyes"; then
ifelse([$1],,[AC_DEFINE([HAVE_PTHREAD],[1],[Define if you have POSIX threads libraries and header files.])],[$1])
:
else
ax_pthread_ok=no
$2
fi
AC_LANG_POP
])dnl AX_PTHREAD
mongodb-2.1.0/scripts/autotools/m4/php_mongodb.m4 0000644 0001751 0000166 00000003574 15014033047 016664 0 ustar dnl
dnl PHP_MONGODB_ADD_SOURCES(source-path, sources [, special-flags])
dnl
dnl Adds sources which are located relative to source-path. source-path should
dnl be relative to the extension directory (i.e. PHP_EXT_DIR). special-flags
dnl will be passed to the compiler.
dnl
dnl This macro will call PHP_ADD_SOURCES or PHP_ADD_SOURCES_X depending on
dnl whether the extension is being built statically or as a shared module.
dnl
AC_DEFUN([PHP_MONGODB_ADD_SOURCES],[
_src_path=PHP_EXT_DIR(mongodb)
dnl Join extension directory and source path
case $_src_path in
""[)] _src_path="$1" ;;
*/[)] _src_path="$_src_path$1" ;;
*[)] _src_path="$_src_path/$1" ;;
esac
dnl Trim trailing slash from source path
case $_src_path in
*/[)] _src_path=${_src_path%?}
esac
if test "$ext_shared" = "no"; then
PHP_ADD_SOURCES($_src_path, [$2], [$3])
else
PHP_ADD_SOURCES_X($_src_path, [$2], [$3], shared_objects_mongodb, yes)
fi
])
dnl
dnl PHP_MONGODB_ADD_INCLUDE(path)
dnl
dnl Adds an include path relative to the extension source directory (i.e.
dnl PHP_EXT_SRCDIR).
dnl
AC_DEFUN([PHP_MONGODB_ADD_INCLUDE],[
PHP_ADD_INCLUDE(PHP_EXT_SRCDIR(mongodb)[/][$1])
])
dnl
dnl PHP_MONGODB_ADD_BUILD_DIR(path)
dnl
dnl Adds a build directory relative to the extension build directory (i.e.
dnl PHP_EXT_BUILDDIR).
dnl
AC_DEFUN([PHP_MONGODB_ADD_BUILD_DIR],[
PHP_ADD_BUILD_DIR(PHP_EXT_BUILDDIR(mongodb)[/][$1])
])
dnl
dnl PHP_MONGODB_VALIDATE_ARG(arg-name, valid-values)
dnl
dnl Checks that value of arg-name is in the space-delimited list of valid-values
dnl and raises an error if not.
dnl
AC_DEFUN([PHP_MONGODB_VALIDATE_ARG], [
ac_php_mongodb_valid_arg="no"
for value in $2; do
if test "$value" = "$$1"; then
ac_php_mongodb_valid_arg="yes"
break
fi
done
if test "$ac_php_mongodb_valid_arg" = "no"; then
AC_MSG_ERROR([Expected $1 to be one of "$2", "$$1" given])
fi
])
mongodb-2.1.0/scripts/autotools/m4/pkg.m4 0000644 0001751 0000166 00000024250 15014033047 015143 0 ustar # https://gitlab.freedesktop.org/pkg-config/pkg-config/-/blob/pkg-config-0.29.2/pkg.m4.in
# pkg.m4 - Macros to locate and utilise pkg-config. -*- Autoconf -*-
# serial 12 (pkg-config-0.29)
dnl Copyright © 2004 Scott James Remnant .
dnl Copyright © 2012-2015 Dan Nicholson
dnl
dnl This program is free software; you can redistribute it and/or modify
dnl it under the terms of the GNU General Public License as published by
dnl the Free Software Foundation; either version 2 of the License, or
dnl (at your option) any later version.
dnl
dnl This program is distributed in the hope that it will be useful, but
dnl WITHOUT ANY WARRANTY; without even the implied warranty of
dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
dnl General Public License for more details.
dnl
dnl You should have received a copy of the GNU General Public License
dnl along with this program; if not, write to the Free Software
dnl Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
dnl 02111-1307, USA.
dnl
dnl As a special exception to the GNU General Public License, if you
dnl distribute this file as part of a program that contains a
dnl configuration script generated by Autoconf, you may include it under
dnl the same distribution terms that you use for the rest of that
dnl program.
dnl PKG_PREREQ(MIN-VERSION)
dnl -----------------------
dnl Since: 0.29
dnl
dnl Verify that the version of the pkg-config macros are at least
dnl MIN-VERSION. Unlike PKG_PROG_PKG_CONFIG, which checks the user's
dnl installed version of pkg-config, this checks the developer's version
dnl of pkg.m4 when generating configure.
dnl
dnl To ensure that this macro is defined, also add:
dnl m4_ifndef([PKG_PREREQ],
dnl [m4_fatal([must install pkg-config 0.29 or later before running autoconf/autogen])])
dnl
dnl See the "Since" comment for each macro you use to see what version
dnl of the macros you require.
m4_defun([PKG_PREREQ],
[m4_define([PKG_MACROS_VERSION], [0.29])
m4_if(m4_version_compare(PKG_MACROS_VERSION, [$1]), -1,
[m4_fatal([pkg.m4 version $1 or higher is required but ]PKG_MACROS_VERSION[ found])])
])dnl PKG_PREREQ
dnl PKG_PROG_PKG_CONFIG([MIN-VERSION])
dnl ----------------------------------
dnl Since: 0.16
dnl
dnl Search for the pkg-config tool and set the PKG_CONFIG variable to
dnl first found in the path. Checks that the version of pkg-config found
dnl is at least MIN-VERSION. If MIN-VERSION is not specified, 0.9.0 is
dnl used since that's the first version where most current features of
dnl pkg-config existed.
AC_DEFUN([PKG_PROG_PKG_CONFIG],
[m4_pattern_forbid([^_?PKG_[A-Z_]+$])
m4_pattern_allow([^PKG_CONFIG(_(PATH|LIBDIR|SYSROOT_DIR|ALLOW_SYSTEM_(CFLAGS|LIBS)))?$])
m4_pattern_allow([^PKG_CONFIG_(DISABLE_UNINSTALLED|TOP_BUILD_DIR|DEBUG_SPEW)$])
AC_ARG_VAR([PKG_CONFIG], [path to pkg-config utility])
AC_ARG_VAR([PKG_CONFIG_PATH], [directories to add to pkg-config's search path])
AC_ARG_VAR([PKG_CONFIG_LIBDIR], [path overriding pkg-config's built-in search path])
if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then
AC_PATH_TOOL([PKG_CONFIG], [pkg-config])
fi
if test -n "$PKG_CONFIG"; then
_pkg_min_version=m4_default([$1], [0.9.0])
AC_MSG_CHECKING([pkg-config is at least version $_pkg_min_version])
if $PKG_CONFIG --atleast-pkgconfig-version $_pkg_min_version; then
AC_MSG_RESULT([yes])
else
AC_MSG_RESULT([no])
PKG_CONFIG=""
fi
fi[]dnl
])dnl PKG_PROG_PKG_CONFIG
dnl PKG_CHECK_EXISTS(MODULES, [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
dnl -------------------------------------------------------------------
dnl Since: 0.18
dnl
dnl Check to see whether a particular set of modules exists. Similar to
dnl PKG_CHECK_MODULES(), but does not set variables or print errors.
dnl
dnl Please remember that m4 expands AC_REQUIRE([PKG_PROG_PKG_CONFIG])
dnl only at the first occurence in configure.ac, so if the first place
dnl it's called might be skipped (such as if it is within an "if", you
dnl have to call PKG_CHECK_EXISTS manually
AC_DEFUN([PKG_CHECK_EXISTS],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
if test -n "$PKG_CONFIG" && \
AC_RUN_LOG([$PKG_CONFIG --exists --print-errors "$1"]); then
m4_default([$2], [:])
m4_ifvaln([$3], [else
$3])dnl
fi])
dnl _PKG_CONFIG([VARIABLE], [COMMAND], [MODULES])
dnl ---------------------------------------------
dnl Internal wrapper calling pkg-config via PKG_CONFIG and setting
dnl pkg_failed based on the result.
m4_define([_PKG_CONFIG],
[if test -n "$$1"; then
pkg_cv_[]$1="$$1"
elif test -n "$PKG_CONFIG"; then
PKG_CHECK_EXISTS([$3],
[pkg_cv_[]$1=`$PKG_CONFIG --[]$2 "$3" 2>/dev/null`
test "x$?" != "x0" && pkg_failed=yes ],
[pkg_failed=yes])
else
pkg_failed=untried
fi[]dnl
])dnl _PKG_CONFIG
dnl _PKG_SHORT_ERRORS_SUPPORTED
dnl ---------------------------
dnl Internal check to see if pkg-config supports short errors.
AC_DEFUN([_PKG_SHORT_ERRORS_SUPPORTED],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])
if $PKG_CONFIG --atleast-pkgconfig-version 0.20; then
_pkg_short_errors_supported=yes
else
_pkg_short_errors_supported=no
fi[]dnl
])dnl _PKG_SHORT_ERRORS_SUPPORTED
dnl PKG_CHECK_MODULES(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
dnl [ACTION-IF-NOT-FOUND])
dnl --------------------------------------------------------------
dnl Since: 0.4.0
dnl
dnl Note that if there is a possibility the first call to
dnl PKG_CHECK_MODULES might not happen, you should be sure to include an
dnl explicit call to PKG_PROG_PKG_CONFIG in your configure.ac
AC_DEFUN([PKG_CHECK_MODULES],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
AC_ARG_VAR([$1][_CFLAGS], [C compiler flags for $1, overriding pkg-config])dnl
AC_ARG_VAR([$1][_LIBS], [linker flags for $1, overriding pkg-config])dnl
pkg_failed=no
AC_MSG_CHECKING([for $2])
_PKG_CONFIG([$1][_CFLAGS], [cflags], [$2])
_PKG_CONFIG([$1][_LIBS], [libs], [$2])
m4_define([_PKG_TEXT], [Alternatively, you may set the environment variables $1[]_CFLAGS
and $1[]_LIBS to avoid the need to call pkg-config.
See the pkg-config man page for more details.])
if test $pkg_failed = yes; then
AC_MSG_RESULT([no])
_PKG_SHORT_ERRORS_SUPPORTED
if test $_pkg_short_errors_supported = yes; then
$1[]_PKG_ERRORS=`$PKG_CONFIG --short-errors --print-errors --cflags --libs "$2" 2>&1`
else
$1[]_PKG_ERRORS=`$PKG_CONFIG --print-errors --cflags --libs "$2" 2>&1`
fi
# Put the nasty error message in config.log where it belongs
echo "$$1[]_PKG_ERRORS" >&AS_MESSAGE_LOG_FD
m4_default([$4], [AC_MSG_ERROR(
[Package requirements ($2) were not met:
$$1_PKG_ERRORS
Consider adjusting the PKG_CONFIG_PATH environment variable if you
installed software in a non-standard prefix.
_PKG_TEXT])[]dnl
])
elif test $pkg_failed = untried; then
AC_MSG_RESULT([no])
m4_default([$4], [AC_MSG_FAILURE(
[The pkg-config script could not be found or is too old. Make sure it
is in your PATH or set the PKG_CONFIG environment variable to the full
path to pkg-config.
_PKG_TEXT
To get pkg-config, see .])[]dnl
])
else
$1[]_CFLAGS=$pkg_cv_[]$1[]_CFLAGS
$1[]_LIBS=$pkg_cv_[]$1[]_LIBS
AC_MSG_RESULT([yes])
$3
fi[]dnl
])dnl PKG_CHECK_MODULES
dnl PKG_CHECK_MODULES_STATIC(VARIABLE-PREFIX, MODULES, [ACTION-IF-FOUND],
dnl [ACTION-IF-NOT-FOUND])
dnl ---------------------------------------------------------------------
dnl Since: 0.29
dnl
dnl Checks for existence of MODULES and gathers its build flags with
dnl static libraries enabled. Sets VARIABLE-PREFIX_CFLAGS from --cflags
dnl and VARIABLE-PREFIX_LIBS from --libs.
dnl
dnl Note that if there is a possibility the first call to
dnl PKG_CHECK_MODULES_STATIC might not happen, you should be sure to
dnl include an explicit call to PKG_PROG_PKG_CONFIG in your
dnl configure.ac.
AC_DEFUN([PKG_CHECK_MODULES_STATIC],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
_save_PKG_CONFIG=$PKG_CONFIG
PKG_CONFIG="$PKG_CONFIG --static"
PKG_CHECK_MODULES($@)
PKG_CONFIG=$_save_PKG_CONFIG[]dnl
])dnl PKG_CHECK_MODULES_STATIC
dnl PKG_INSTALLDIR([DIRECTORY])
dnl -------------------------
dnl Since: 0.27
dnl
dnl Substitutes the variable pkgconfigdir as the location where a module
dnl should install pkg-config .pc files. By default the directory is
dnl $libdir/pkgconfig, but the default can be changed by passing
dnl DIRECTORY. The user can override through the --with-pkgconfigdir
dnl parameter.
AC_DEFUN([PKG_INSTALLDIR],
[m4_pushdef([pkg_default], [m4_default([$1], ['${libdir}/pkgconfig'])])
m4_pushdef([pkg_description],
[pkg-config installation directory @<:@]pkg_default[@:>@])
AC_ARG_WITH([pkgconfigdir],
[AS_HELP_STRING([--with-pkgconfigdir], pkg_description)],,
[with_pkgconfigdir=]pkg_default)
AC_SUBST([pkgconfigdir], [$with_pkgconfigdir])
m4_popdef([pkg_default])
m4_popdef([pkg_description])
])dnl PKG_INSTALLDIR
dnl PKG_NOARCH_INSTALLDIR([DIRECTORY])
dnl --------------------------------
dnl Since: 0.27
dnl
dnl Substitutes the variable noarch_pkgconfigdir as the location where a
dnl module should install arch-independent pkg-config .pc files. By
dnl default the directory is $datadir/pkgconfig, but the default can be
dnl changed by passing DIRECTORY. The user can override through the
dnl --with-noarch-pkgconfigdir parameter.
AC_DEFUN([PKG_NOARCH_INSTALLDIR],
[m4_pushdef([pkg_default], [m4_default([$1], ['${datadir}/pkgconfig'])])
m4_pushdef([pkg_description],
[pkg-config arch-independent installation directory @<:@]pkg_default[@:>@])
AC_ARG_WITH([noarch-pkgconfigdir],
[AS_HELP_STRING([--with-noarch-pkgconfigdir], pkg_description)],,
[with_noarch_pkgconfigdir=]pkg_default)
AC_SUBST([noarch_pkgconfigdir], [$with_noarch_pkgconfigdir])
m4_popdef([pkg_default])
m4_popdef([pkg_description])
])dnl PKG_NOARCH_INSTALLDIR
dnl PKG_CHECK_VAR(VARIABLE, MODULE, CONFIG-VARIABLE,
dnl [ACTION-IF-FOUND], [ACTION-IF-NOT-FOUND])
dnl -------------------------------------------
dnl Since: 0.28
dnl
dnl Retrieves the value of the pkg-config variable for the given module.
AC_DEFUN([PKG_CHECK_VAR],
[AC_REQUIRE([PKG_PROG_PKG_CONFIG])dnl
AC_ARG_VAR([$1], [value of $3 for $2, overriding pkg-config])dnl
_PKG_CONFIG([$1], [variable="][$3]["], [$2])
AS_VAR_COPY([$1], [pkg_cv_][$1])
AS_VAR_IF([$1], [""], [$5], [$4])dnl
])dnl PKG_CHECK_VAR
mongodb-2.1.0/scripts/autotools/CheckCompiler.m4 0000644 0001751 0000166 00000003270 15014033047 016551 0 ustar # If CFLAGS and CXXFLAGS are unset, default to empty.
# This is to tell automake not to include '-g' if C{XX,}FLAGS is not set.
# For more info - http://www.gnu.org/software/automake/manual/autoconf.html#C_002b_002b-Compiler
if test -z "$CXXFLAGS"; then
CXXFLAGS=""
fi
if test -z "$CFLAGS"; then
CFLAGS=""
fi
AC_PROG_CC
AC_PROG_CXX
dnl AC_PROG_CC_C99 is previously called in config.m4, but AC_PROG_CC resets CC
dnl so call it once more to ensure C99 remains enabled
m4_version_prereq([2.70],,[AC_PROG_CC_C99])
# Check that an appropriate C compiler is available.
# Note: BEGIN_IGNORE_DEPRECATIONS macro requires GCC 4.6+.
c_compiler="unknown"
AC_LANG_PUSH([C])
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([
#if !(defined(__GNUC__) && !defined(__clang__) && !defined(__INTEL_COMPILER))
#error Not a supported GCC compiler
#endif
#if defined(__GNUC__)
#define GCC_VERSION (__GNUC__ * 10000 \
+ __GNUC_MINOR__ * 100 \
+ __GNUC_PATCHLEVEL__)
#if GCC_VERSION < 40600
#error Not a supported GCC compiler
#endif
#endif
])], [c_compiler="gcc"], [])
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([
#if defined(__clang__)
#define CLANG_VERSION (__clang_major__ * 10000 \
+ __clang_minor__ * 100 \
+ __clang_patchlevel__)
#if CLANG_VERSION < 30300
#error Not a supported Clang compiler
#endif
#endif
])], [c_compiler="clang"], [])
AC_COMPILE_IFELSE([AC_LANG_PROGRAM([
#if !(defined(__SUNPRO_C))
#error Not a supported Sun compiler
#endif
])], [c_compiler="sun"], [])
AC_LANG_POP([C])
if test "$c_compiler" = "unknown"; then
AC_MSG_ERROR([Compiler GCC >= 4.6 or Clang >= 3.3 is required for C compilation])
fi
AC_C_CONST
AC_C_INLINE
AC_C_TYPEOF
mongodb-2.1.0/scripts/autotools/CheckHost.m4 0000644 0001751 0000166 00000001774 15014033047 015723 0 ustar AC_CANONICAL_HOST
os_win32=no
os_netbsd=no
os_freebsd=no
os_openbsd=no
os_hpux=no
os_linux=no
os_solaris=no
os_darwin=no
os_gnu=no
os_aix=no
case "$host" in
*-mingw*|*-*-cygwin*)
os_win32=yes
TARGET_OS=windows
;;
*-*-*netbsd*)
os_netbsd=yes
TARGET_OS=unix
;;
*-*-*freebsd*)
os_freebsd=yes
TARGET_OS=unix
;;
*-*-*openbsd*)
os_openbsd=yes
TARGET_OS=unix
;;
*-*-hpux*)
os_hpux=yes
TARGET_OS=unix
;;
*-*-linux*)
os_linux=yes
os_gnu=yes
TARGET_OS=unix
;;
*-*-solaris*)
os_solaris=yes
TARGET_OS=unix
;;
*-*-darwin*)
os_darwin=yes
TARGET_OS=unix
;;
*-*-aix*|*-*-os400*)
os_aix=yes
TARGET_OS=unix
;;
gnu*|k*bsd*-gnu*)
os_gnu=yes
TARGET_OS=unix
;;
*)
AC_MSG_WARN([*** Please add $host to configure.ac checks!])
;;
esac
mongodb-2.1.0/scripts/autotools/PlatformFlags.m4 0000644 0001751 0000166 00000002313 15014033047 016577 0 ustar dnl Enable POSIX features up to POSIX.1-2008 plus the XSI extension and BSD-derived definitions.
dnl Both _BSD_SOURCE and _DEFAULT_SOURCE are defined for backwards-compatibility with glibc 2.19 and earlier.
dnl _BSD_SOURCE and _DEFAULT_SOURCE are required by `getpagesize`, `h_errno`, etc.
dnl _XOPEN_SOURCE=700 is required by `strnlen`, `strerror_l`, etc.
dnl https://man7.org/linux/man-pages/man7/feature_test_macros.7.html
dnl https://pubs.opengroup.org/onlinepubs/7908799/xsh/compilation.html
CPPFLAGS="$CPPFLAGS -D_XOPEN_SOURCE=700 -D_BSD_SOURCE -D_DEFAULT_SOURCE"
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS -D_XOPEN_SOURCE=700 -D_BSD_SOURCE -D_DEFAULT_SOURCE"
dnl Enable non-standard features on FreeBSD with __BSD_VISIBLE=1
if test "$os_freebsd" = "yes"; then
CPPFLAGS="$CPPFLAGS -D__BSD_VISIBLE=1"
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS -D__BSD_VISIBLE=1"
fi
AS_IF([test "$os_darwin" = "yes"],[
dnl Non-POSIX extensions are required by `_SC_NPROCESSORS_ONLN`.
dnl https://opensource.apple.com/source/Libc/Libc-1439.40.11/gen/compat.5.auto.html
CPPFLAGS="$CPPFLAGS -D_DARWIN_C_SOURCE"
PHP_MONGODB_BUNDLED_CFLAGS="$PHP_MONGODB_BUNDLED_CFLAGS -D_DARWIN_C_SOURCE"
])
mongodb-2.1.0/scripts/clang-format.sh 0000755 0001751 0000166 00000002366 15014033047 014464 0 ustar #!/bin/sh
CLANG_ARGS="-Werror"
if test x"$1" = xchanged; then
FILES1=`git ls-files | grep -v "src/contrib" | grep -v "_arginfo.h" | grep '\.[ch]$'`
FILES2=`git ls-files --others --exclude-standard | grep -v "src/contrib" | grep -v "_arginfo.h" | grep '\.[ch]$'`
FILES="$FILES1 $FILES2"
else
FILES1=`git ls-files | grep -v "src/contrib" | grep -v "_arginfo.h" | grep '\.[ch]$'`
FILES2=`git ls-files --others --exclude-standard | grep -v "src/contrib" | grep -v "_arginfo.h" | grep '\.[ch]$'`
FILES="$FILES1 $FILES2"
fi
if test x"$1" = xcheck; then
CLANG_ARGS="$CLANG_ARGS -n"
fi
# Find clang-format, we prefer -6.0, but also allow binaries without -suffix as
# long as they're >= 6.0.0
CLANG_FORMAT=`which clang-format-6.0`
if [ -z "$CLANG_FORMAT" ]; then
CLANG_FORMAT=`which clang-format`
fi
if [ -z "$CLANG_FORMAT" ]; then
echo "Couldn't find clang-format"
exit
fi
VERSION=`$CLANG_FORMAT -version | grep -oE '[0-9]+\.[0-9]+\.[0-9]+'`
VERSION_MAJOR=`echo $VERSION | cut -d "." -f 1`
if [ $VERSION_MAJOR -lt 6 ]; then
echo "Found clang-format $VERSION but we need >= 6.0.0"
exit
fi
FAILURE=""
# Run formatter
for i in $FILES; do
$CLANG_FORMAT $CLANG_ARGS -i $i
[ $? -eq 0 ] || FAILURE="yes"
done
if [ -z "$FAILURE" ]; then
exit 0
fi
exit 1
mongodb-2.1.0/scripts/convert-bson-corpus-tests.php 0000644 0001751 0000166 00000027713 15014033047 017357 0 ustar 'Embedded null in code string is not supported in libbson (CDRIVER-1879)',
'Javascript Code with Scope: Unicode and embedded null in code string, empty scope' => 'Embedded null in code string is not supported in libbson (CDRIVER-1879)',
'Top-level document validity: Bad $date (number, not string or hash)' => 'Legacy extended JSON $date syntax uses numbers (CDRIVER-2223)',
];
$for64bitOnly = [
/* Note: Although 64-bit integers be represented by the Int64 class, these
* tests fail on 32-bit platforms due to json_canonicalize() roundtripping
* values through PHP, which converts large integers to floats. */
'Int64 type: MinValue' => "Can't represent 64-bit ints on a 32-bit platform",
'Int64 type: MaxValue' => "Can't represent 64-bit ints on a 32-bit platform",
];
$outputPath = realpath(__DIR__ . '/../tests') . '/bson-corpus/';
if ( ! is_dir($outputPath) && ! mkdir($outputPath, 0755, true)) {
printf("Error creating output path: %s\n", $outputPath);
}
foreach (array_slice($argv, 1) as $inputFile) {
if ( ! is_readable($inputFile) || ! is_file($inputFile)) {
printf("Error reading %s\n", $inputFile);
continue;
}
$test = json_decode(file_get_contents($inputFile), true);
if (json_last_error() !== JSON_ERROR_NONE) {
printf("Error decoding %s: %s\n", $inputFile, json_last_error_msg());
continue;
}
if ( ! isset($test['description'])) {
printf("Skipping test file without \"description\" field: %s\n", $inputFile);
continue;
}
if ( ! empty($test['valid'])) {
foreach ($test['valid'] as $i => $case) {
$outputFile = sprintf('%s-valid-%03d.phpt', pathinfo($inputFile, PATHINFO_FILENAME), $i + 1);
try {
$output = renderPhpt(getParamsForValid($test, $case), $expectedFailures, $for64bitOnly);
} catch (Exception $e) {
printf("Error processing valid[%d] in %s: %s\n", $i, $inputFile, $e->getMessage());
continue;
}
if (false === file_put_contents($outputPath . '/' . $outputFile, $output)) {
printf("Error writing valid[%d] in %s\n", $i, $inputFile);
continue;
}
}
}
if ( ! empty($test['decodeErrors'])) {
foreach ($test['decodeErrors'] as $i => $case) {
$outputFile = sprintf('%s-decodeError-%03d.phpt', pathinfo($inputFile, PATHINFO_FILENAME), $i + 1);
try {
$output = renderPhpt(getParamsForDecodeError($test, $case), $expectedFailures, $for64bitOnly);
} catch (Exception $e) {
printf("Error processing decodeErrors[%d] in %s: %s\n", $i, $inputFile, $e->getMessage());
continue;
}
if (false === file_put_contents($outputPath . '/' . $outputFile, $output)) {
printf("Error writing decodeErrors[%d] in %s\n", $i, $inputFile);
continue;
}
}
}
if ( ! empty($test['parseErrors'])) {
foreach ($test['parseErrors'] as $i => $case) {
$outputFile = sprintf('%s-parseError-%03d.phpt', pathinfo($inputFile, PATHINFO_FILENAME), $i + 1);
try {
$output = renderPhpt(getParamsForParseError($test, $case), $expectedFailures, $for64bitOnly);
} catch (Exception $e) {
printf("Error processing parseErrors[%d] in %s: %s\n", $i, $inputFile, $e->getMessage());
continue;
}
if (false === file_put_contents($outputPath . '/' . $outputFile, $output)) {
printf("Error writing parseErrors[%d] in %s\n", $i, $inputFile);
continue;
}
}
}
}
function getParamsForValid(array $test, array $case)
{
foreach (['description', 'canonical_bson', 'canonical_extjson'] as $field) {
if (!isset($case[$field])) {
throw new InvalidArgumentException(sprintf('Missing "%s" field', $field));
}
}
$code = '';
$expect = '';
$lossy = isset($case['lossy']) ? (boolean) $case['lossy'] : false;
$canonicalBson = $case['canonical_bson'];
$expectedCanonicalBson = strtolower($canonicalBson);
$code .= sprintf('$canonicalBson = hex2bin(%s);', var_export($canonicalBson, true)) . "\n";
if (isset($case['degenerate_bson'])) {
$degenerateBson = $case['degenerate_bson'];
$expectedDegenerateBson = strtolower($degenerateBson);
$code .= sprintf('$degenerateBson = hex2bin(%s);', var_export($degenerateBson, true)) . "\n";
}
if (isset($case['converted_bson'])) {
$convertedBson = $case['converted_bson'];
$expectedConvertedBson = strtolower($convertedBson);
$code .= sprintf('$convertedBson = hex2bin(%s);', var_export($convertedBson, true)) . "\n";
}
$canonicalExtJson = $case['canonical_extjson'];
$expectedCanonicalExtJson = json_canonicalize($canonicalExtJson);
$code .= sprintf('$canonicalExtJson = %s;', var_export($canonicalExtJson, true)) . "\n";
if (isset($case['relaxed_extjson'])) {
$relaxedExtJson = $case['relaxed_extjson'];
$expectedRelaxedExtJson = json_canonicalize($relaxedExtJson);
$code .= sprintf('$relaxedExtJson = %s;', var_export($relaxedExtJson, true)) . "\n";
}
if (isset($case['degenerate_extjson'])) {
$degenerateExtJson = $case['degenerate_extjson'];
$expectedDegenerateExtJson = json_canonicalize($degenerateExtJson);
$code .= sprintf('$degenerateExtJson = %s;', var_export($degenerateExtJson, true)) . "\n";
}
if (isset($case['converted_extjson'])) {
$convertedExtJson = $case['converted_extjson'];
$expectedConvertedExtJson = json_canonicalize($convertedExtJson);
$code .= sprintf('$convertedExtJson = %s;', var_export($convertedExtJson, true)) . "\n";
}
$code .= "\n// Canonical BSON -> BSON object -> Canonical BSON\n";
$code .= 'echo bin2hex((string) MongoDB\BSON\Document::fromBSON($canonicalBson)), "\n";' . "\n";
$expect .= $expectedCanonicalBson . "\n";
$code .= "\n// Canonical BSON -> BSON object -> Canonical extJSON\n";
$code .= 'echo json_canonicalize(MongoDB\BSON\Document::fromBSON($canonicalBson)->toCanonicalExtendedJSON()), "\n";' . "\n";
$expect .= $expectedCanonicalExtJson . "\n";
if (isset($relaxedExtJson)) {
$code .= "\n// Canonical BSON -> BSON object -> Relaxed extJSON\n";
$code .= 'echo json_canonicalize(MongoDB\BSON\Document::fromBSON($canonicalBson)->toRelaxedExtendedJSON()), "\n";' . "\n";
$expect .= $expectedRelaxedExtJson . "\n";
}
if (!$lossy) {
$code .= "\n// Canonical extJSON -> BSON object -> Canonical BSON\n";
$code .= 'echo bin2hex((string) MongoDB\BSON\Document::fromJSON($canonicalExtJson)), "\n";' . "\n";
$expect .= $expectedCanonicalBson . "\n";
}
if (isset($degenerateBson)) {
$code .= "\n// Degenerate BSON -> BSON object -> Canonical BSON\n";
$code .= 'echo bin2hex((string) MongoDB\BSON\Document::fromPHP(MongoDB\BSON\Document::fromBSON($degenerateBson)->toPHP())), "\n";' . "\n";
$expect .= $expectedCanonicalBson . "\n";
$code .= "\n// Degenerate BSON -> BSON object -> Canonical extJSON\n";
$code .= 'echo json_canonicalize(MongoDB\BSON\Document::fromBSON($degenerateBson)->toCanonicalExtendedJSON()), "\n";' . "\n";
$expect .= $expectedCanonicalExtJson . "\n";
if (isset($relaxedExtJson)) {
$code .= "\n// Degenerate BSON -> BSON object -> Relaxed extJSON\n";
$code .= 'echo json_canonicalize(MongoDB\BSON\Document::fromBSON($degenerateBson)->toRelaxedExtendedJSON()), "\n";' . "\n";
$expect .= $expectedRelaxedExtJson . "\n";
}
}
if (isset($degenerateExtJson) && !$lossy) {
$code .= "\n// Degenerate extJSON -> BSON object -> Canonical BSON\n";
$code .= 'echo bin2hex((string) MongoDB\BSON\Document::fromJSON($degenerateExtJson)), "\n";' . "\n";
$expect .= $expectedCanonicalBson . "\n";
}
if (isset($relaxedExtJson)) {
$code .= "\n// Relaxed extJSON -> BSON object -> Relaxed extJSON\n";
$code .= 'echo json_canonicalize(MongoDB\BSON\Document::fromJSON($relaxedExtJson)->toRelaxedExtendedJSON()), "\n";' . "\n";
$expect .= $expectedRelaxedExtJson . "\n";
}
return [
'%NAME%' => sprintf('%s: %s', trim($test['description']), trim($case['description'])),
'%CODE%' => trim($code),
'%EXPECT%' => trim($expect),
];
}
function getParamsForDecodeError(array $test, array $case)
{
foreach (['description', 'bson'] as $field) {
if (!isset($case[$field])) {
throw new InvalidArgumentException(sprintf('Missing "%s" field', $field));
}
}
$code = sprintf('$bson = hex2bin(%s);', var_export($case['bson'], true)) . "\n\n";
$code .= "throws(function() use (\$bson) {\n";
$code .= " MongoDB\\BSON\\Document::fromBSON(\$bson)->toPHP();\n";
$code .= "}, 'MongoDB\Driver\Exception\UnexpectedValueException');";
/* We do not test for the exception message, since that may differ based on
* the nature of the decoding error. */
$expect = "OK: Got MongoDB\Driver\Exception\UnexpectedValueException";
return [
'%NAME%' => sprintf('%s: %s', trim($test['description']), trim($case['description'])),
'%CODE%' => trim($code),
'%EXPECT%' => trim($expect),
];
}
function getParamsForParseError(array $test, array $case)
{
foreach (['description', 'string'] as $field) {
if (!isset($case[$field])) {
throw new InvalidArgumentException(sprintf('Missing "%s" field', $field));
}
}
$code = '';
$expect = '';
switch ($test['bson_type']) {
case '0x00': // Top-level document
case '0x05': // Binary
$code = "throws(function() {\n";
$code .= sprintf(" MongoDB\\BSON\\Document::fromJSON(%s);\n", var_export($case['string'], true));
$code .= "}, 'MongoDB\Driver\Exception\UnexpectedValueException');";
/* We do not test for the exception message, since that may differ
* based on the nature of the parse error. */
$expect = "OK: Got MongoDB\Driver\Exception\UnexpectedValueException";
break;
case '0x13': // Decimal128
$code = "throws(function() {\n";
$code .= sprintf(" new MongoDB\BSON\Decimal128(%s);\n", var_export($case['string'], true));
$code .= "}, 'MongoDB\Driver\Exception\InvalidArgumentException');";
/* We do not test for the exception message, since that may differ
* based on the nature of the parse error. */
$expect = "OK: Got MongoDB\Driver\Exception\InvalidArgumentException";
break;
default:
throw new UnexpectedValueException(sprintf("Parse errors not supported for BSON type: %s", $test['bson_type']));
}
return [
'%NAME%' => sprintf('%s: %s', trim($test['description']), trim($case['description'])),
'%CODE%' => trim($code),
'%EXPECT%' => trim($expect),
];
}
function renderPhpt(array $params, array $expectedFailures, array $for64bitOnly)
{
$params['%XFAIL%'] = isset($expectedFailures[$params['%NAME%']])
? "--XFAIL--\n" . $expectedFailures[$params['%NAME%']] . "\n"
: '';
$params['%SKIPIF%'] = isset($for64bitOnly[$params['%NAME%']])
? "--SKIPIF--\n" . "" . "\n"
: '';
$template = <<< 'TEMPLATE'
--TEST--
%NAME%
%XFAIL%%SKIPIF%--DESCRIPTION--
Generated by scripts/convert-bson-corpus-tests.php
DO NOT EDIT THIS FILE
--FILE--
===DONE===
--EXPECT--
%EXPECT%
===DONE===
TEMPLATE;
return str_replace(array_keys($params), array_values($params), $template);
}
mongodb-2.1.0/scripts/generate-functionmap.php 0000644 0001751 0000166 00000010542 15014033047 016372 0 ustar createFunctionMap($filename);
printf("Created call map in %s\n", $filename);
class FunctionMapGenerator
{
public function createFunctionMap(string $filename): void
{
$this->writeFunctionMap($filename, $this->getFunctionMap());
}
private function getFunctionMap(): array
{
$classes = array_filter(get_declared_classes(), $this->filterItems(...));
$interfaces = array_filter(get_declared_interfaces(), $this->filterItems(...));
$functions = array_filter(get_defined_functions()['internal'], $this->filterItems(...));
$functionMap = [];
// Generate call map for functions
foreach ($functions as $functionName) {
$reflectionFunction = new ReflectionFunction($functionName);
$functionMap[$reflectionFunction->getName()] = $this->getFunctionMapEntry($reflectionFunction);
}
// Generate call map for classes and interfaces
$members = array_merge($classes, $interfaces);
sort($members);
$skippedMethods = ['__set_state', '__wakeup', '__serialize', '__unserialize'];
foreach ($members as $member) {
$reflectionClass = new ReflectionClass($member);
foreach ($reflectionClass->getMethods(ReflectionMethod::IS_PUBLIC) as $method) {
if ($method->getDeclaringClass() != $reflectionClass && $method->getName() != '__toString') {
continue;
}
if (in_array($method->getName(), $skippedMethods, true)) {
continue;
}
$methodKey = $reflectionClass->getName() . '::' . $method->getName();
$functionMap[$methodKey] = $this->getFunctionMapEntry($method);
}
}
return $functionMap;
}
private function writeFunctionMap(string $filename, array $functionMap): void
{
$lines = [];
foreach ($functionMap as $methodName => $typeInfo) {
$generatedTypeInfo = implode(
', ',
array_map(
function (string|int $key, string $value): string {
if (is_int($key)) {
return $this->removeDoubleBackslash(var_export($value, true));
}
return sprintf('%s => %s', var_export($key, true), $this->removeDoubleBackslash(var_export($value, true)));
},
array_keys($typeInfo),
array_values($typeInfo)
)
);
$lines[] = sprintf(
' %s => [%s],',
$this->removeDoubleBackslash(var_export($methodName, true)),
$generatedTypeInfo
);
}
$fileTemplate = <<<'PHP'
hasReturnType() => (string) $function->getReturnType(),
$function->hasTentativeReturnType() => (string) $function->getTentativeReturnType(),
default => 'void',
};
$functionMapEntry = [$returnType];
foreach ($function->getParameters() as $parameter) {
$parameterKey = $parameter->getName();
if ($parameter->isOptional()) {
$parameterKey .= '=';
}
$functionMapEntry[$parameterKey] = (string) $parameter->getType();
}
return $functionMapEntry;
}
private function removeDoubleBackslash(string $string): string
{
return str_replace('\\\\', '\\', $string);
}
}
mongodb-2.1.0/scripts/update-sbom.sh 0000755 0001751 0000166 00000001467 15014033047 014333 0 ustar #!/usr/bin/env bash
SCRIPT_DIR=$(dirname ${BASH_SOURCE[0]})
ROOT_DIR=$(realpath "${SCRIPT_DIR}/../")
PURLS_FILE="${ROOT_DIR}/purls.txt"
LIBMONGOC_VERSION=$(cat ${ROOT_DIR}/src/LIBMONGOC_VERSION_CURRENT | tr -d '[:space:]')
LIBMONGOCRYPT_VERSION=$(cat ${ROOT_DIR}/src/LIBMONGOCRYPT_VERSION_CURRENT | tr -d '[:space:]')
# Generate purls file from stored versions
echo "pkg:github/mongodb/mongo-c-driver@${LIBMONGOC_VERSION}" > $PURLS_FILE
echo "pkg:github/mongodb/libmongocrypt@${LIBMONGOCRYPT_VERSION}" >> $PURLS_FILE
# Use silkbomb to update the sbom.json file
docker run --platform="linux/amd64" -it --rm -v ${ROOT_DIR}:/pwd \
artifactory.corp.mongodb.com/release-tools-container-registry-public-local/silkbomb:1.0 \
update --sbom-in /pwd/sbom.json --purls /pwd/purls.txt --sbom-out /pwd/sbom.json
rm $PURLS_FILE
mongodb-2.1.0/scripts/update-submodule-sources.php 0000644 0001751 0000166 00000004666 15014033047 017231 0 ustar 'src/libmongoc/src/common/src',
'PHP_MONGODB_KMS_MESSAGE_SOURCES' => 'src/libmongoc/src/kms-message/src',
'PHP_MONGODB_BSON_SOURCES' => 'src/libmongoc/src/libbson/src/bson',
'PHP_MONGODB_JSONSL_SOURCES' => 'src/libmongoc/src/libbson/src/jsonsl',
'PHP_MONGODB_MONGOC_SOURCES' => 'src/libmongoc/src/libmongoc/src/mongoc',
'PHP_MONGODB_UTF8PROC_SOURCES' => 'src/libmongoc/src/utf8proc-2.8.0',
'PHP_MONGODB_ZLIB_SOURCES' => 'src/libmongoc/src/zlib-1.3.1',
'PHP_MONGODB_MONGOCRYPT_SOURCES' => 'src/libmongocrypt/src',
'PHP_MONGODB_MONGOCRYPT_CRYPTO_SOURCES' => 'src/libmongocrypt/src/crypto',
'PHP_MONGODB_MONGOCRYPT_OS_POSIX_SOURCES' => 'src/libmongocrypt/src/os_posix',
'PHP_MONGODB_MONGOCRYPT_OS_WIN_SOURCES' => 'src/libmongocrypt/src/os_win',
'PHP_MONGODB_MONGOCRYPT_KMS_MESSAGE_SOURCES' => 'src/libmongocrypt/kms-message/src',
// Note: src/libmongocrypt/src/mlib does not contain source files (as of libmongocrypt 1.3.2)
];
$patterns = [];
$replacements = [];
// Paths are relative to the project root directory
chdir(__DIR__ . '/..');
foreach ($vars as $var => $path) {
$cutNth = 2 + substr_count($path, '/');
$files = trim(shell_exec(sprintf($cmd, $path, $cutNth)));
// Note: utf8proc_data.c is included from utf8proc.c and should not be compiled directly
if ($var === 'PHP_MONGODB_UTF8PROC_SOURCES') {
$files = trim(str_replace('utf8proc_data.c', '', $files));
}
$patterns[] = sprintf('/(%s=")([^"]*)(";?)/', $var);
$replacements[] = '$1' . $files . '$3';
}
$files = [
realpath(__DIR__ . '/../config.m4') => count($patterns),
// config.w32 does not use PHP_MONGODB_ZLIB_SOURCES (PHPC-1111)
realpath(__DIR__ . '/../config.w32') => count($patterns) - 1,
];
foreach ($files as $file => $expectedCount) {
$replaced = preg_replace($patterns, $replacements, file_get_contents($file), 1, $count);
if ($count !== $expectedCount) {
fprintf(STDERR, "Skipping %s: Expected %d replacements but only matched %d\n", basename($file), $expectedCount, $count);
continue;
}
printf("Updated %s\n", basename($file));
file_put_contents($file, $replaced);
}
mongodb-2.1.0/src/BSON/Binary.c 0000644 0001751 0000166 00000021272 15014033047 013001 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "Binary_arginfo.h"
#define PHONGO_BINARY_UUID_SIZE 16
zend_class_entry* php_phongo_binary_ce;
/* Initialize the object and return whether it was successful. An exception will
* be thrown on error. */
static bool php_phongo_binary_init(php_phongo_binary_t* intern, const char* data, size_t data_len, zend_long type)
{
if (type < 0 || type > UINT8_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected type to be an unsigned 8-bit integer, %" PHONGO_LONG_FORMAT " given", type);
return false;
}
if ((type == BSON_SUBTYPE_UUID_DEPRECATED || type == BSON_SUBTYPE_UUID) && data_len != PHONGO_BINARY_UUID_SIZE) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected UUID length to be %d bytes, %d given", PHONGO_BINARY_UUID_SIZE, data_len);
return false;
}
intern->data = estrndup(data, data_len);
intern->data_len = data_len;
intern->type = (uint8_t) type;
return true;
}
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_binary_init_from_hash(php_phongo_binary_t* intern, HashTable* props)
{
zval *data, *type;
if ((data = zend_hash_str_find(props, "data", sizeof("data") - 1)) && Z_TYPE_P(data) == IS_STRING &&
(type = zend_hash_str_find(props, "type", sizeof("type") - 1)) && Z_TYPE_P(type) == IS_LONG) {
return php_phongo_binary_init(intern, Z_STRVAL_P(data), Z_STRLEN_P(data), Z_LVAL_P(type));
}
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"data\" string and \"type\" integer fields", ZSTR_VAL(php_phongo_binary_ce->name));
return false;
}
static HashTable* php_phongo_binary_get_properties_hash(zend_object* object, bool is_temp)
{
php_phongo_binary_t* intern;
HashTable* props;
intern = Z_OBJ_BINARY(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_temp, intern, props, 2);
if (!intern->data) {
return props;
}
{
zval data, type;
ZVAL_STRINGL(&data, intern->data, intern->data_len);
zend_hash_str_update(props, "data", sizeof("data") - 1, &data);
ZVAL_LONG(&type, intern->type);
zend_hash_str_update(props, "type", sizeof("type") - 1, &type);
}
return props;
}
/* Construct a new BSON binary type */
static PHP_METHOD(MongoDB_BSON_Binary, __construct)
{
php_phongo_binary_t* intern;
char* data;
size_t data_len;
zend_long type = BSON_SUBTYPE_BINARY;
intern = Z_BINARY_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_STRING(data, data_len)
Z_PARAM_OPTIONAL
Z_PARAM_LONG(type)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_binary_init(intern, data, data_len, type);
}
static PHP_METHOD(MongoDB_BSON_Binary, __set_state)
{
php_phongo_binary_t* intern;
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
object_init_ex(return_value, php_phongo_binary_ce);
intern = Z_BINARY_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_binary_init_from_hash(intern, props);
}
/* Return the Binary's data string. */
static PHP_METHOD(MongoDB_BSON_Binary, __toString)
{
php_phongo_binary_t* intern;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_BINARY_OBJ_P(getThis());
RETURN_STRINGL(intern->data, intern->data_len);
}
static PHP_METHOD(MongoDB_BSON_Binary, getData)
{
php_phongo_binary_t* intern;
intern = Z_BINARY_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_STRINGL(intern->data, intern->data_len);
}
static PHP_METHOD(MongoDB_BSON_Binary, getType)
{
php_phongo_binary_t* intern;
intern = Z_BINARY_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_LONG(intern->type);
}
static PHP_METHOD(MongoDB_BSON_Binary, jsonSerialize)
{
php_phongo_binary_t* intern;
char type[3];
int type_len;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_BINARY_OBJ_P(getThis());
array_init_size(return_value, 2);
{
zend_string* data = php_base64_encode((unsigned char*) intern->data, intern->data_len);
ADD_ASSOC_STRINGL(return_value, "$binary", ZSTR_VAL(data), ZSTR_LEN(data));
zend_string_free(data);
}
type_len = snprintf(type, sizeof(type), "%02x", intern->type);
ADD_ASSOC_STRINGL(return_value, "$type", type, type_len);
}
static PHP_METHOD(MongoDB_BSON_Binary, __serialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_ARR(php_phongo_binary_get_properties_hash(Z_OBJ_P(getThis()), true));
}
static PHP_METHOD(MongoDB_BSON_Binary, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_binary_init_from_hash(Z_BINARY_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\Binary object handlers */
static zend_object_handlers php_phongo_handler_binary;
static void php_phongo_binary_free_object(zend_object* object)
{
php_phongo_binary_t* intern = Z_OBJ_BINARY(object);
zend_object_std_dtor(&intern->std);
if (intern->data) {
efree(intern->data);
}
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
}
static zend_object* php_phongo_binary_create_object(zend_class_entry* class_type)
{
php_phongo_binary_t* intern = zend_object_alloc(sizeof(php_phongo_binary_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_binary;
return &intern->std;
}
static zend_object* php_phongo_binary_clone_object(zend_object* object)
{
php_phongo_binary_t* intern;
php_phongo_binary_t* new_intern;
zend_object* new_object;
intern = Z_OBJ_BINARY(object);
new_object = php_phongo_binary_create_object(object->ce);
new_intern = Z_OBJ_BINARY(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
php_phongo_binary_init(new_intern, intern->data, intern->data_len, intern->type);
return new_object;
}
static int php_phongo_binary_compare_objects(zval* o1, zval* o2)
{
php_phongo_binary_t *intern1, *intern2;
ZEND_COMPARE_OBJECTS_FALLBACK(o1, o2);
intern1 = Z_BINARY_OBJ_P(o1);
intern2 = Z_BINARY_OBJ_P(o2);
/* MongoDB compares binary types first by the data length, then by the type
* byte, and finally by the binary data itself. */
if (intern1->data_len != intern2->data_len) {
return intern1->data_len < intern2->data_len ? -1 : 1;
}
if (intern1->type != intern2->type) {
return intern1->type < intern2->type ? -1 : 1;
}
return zend_binary_strcmp(intern1->data, intern1->data_len, intern2->data, intern2->data_len);
}
static HashTable* php_phongo_binary_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return php_phongo_binary_get_properties_hash(object, true);
}
static HashTable* php_phongo_binary_get_properties(zend_object* object)
{
return php_phongo_binary_get_properties_hash(object, false);
}
void php_phongo_binary_init_ce(INIT_FUNC_ARGS)
{
php_phongo_binary_ce = register_class_MongoDB_BSON_Binary(php_phongo_binary_interface_ce, php_phongo_json_serializable_ce, php_phongo_type_ce, zend_ce_stringable);
php_phongo_binary_ce->create_object = php_phongo_binary_create_object;
memcpy(&php_phongo_handler_binary, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_binary.compare = php_phongo_binary_compare_objects;
php_phongo_handler_binary.clone_obj = php_phongo_binary_clone_object;
php_phongo_handler_binary.get_debug_info = php_phongo_binary_get_debug_info;
php_phongo_handler_binary.get_properties = php_phongo_binary_get_properties;
php_phongo_handler_binary.free_obj = php_phongo_binary_free_object;
php_phongo_handler_binary.offset = XtOffsetOf(php_phongo_binary_t, std);
}
bool phongo_binary_new(zval* object, const char* data, size_t data_len, bson_subtype_t type)
{
php_phongo_binary_t* intern;
object_init_ex(object, php_phongo_binary_ce);
intern = Z_BINARY_OBJ_P(object);
intern->data = estrndup(data, data_len);
intern->data_len = data_len;
intern->type = (uint8_t) type;
return true;
}
mongodb-2.1.0/src/BSON/Binary.h 0000644 0001751 0000166 00000001474 15014033047 013010 0 ustar /*
* Copyright 2022-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_BSON_BINARY_H
#define PHONGO_BSON_BINARY_H
#define PHONGO_BINARY_UUID_SIZE 16
bool phongo_binary_new(zval* object, const char* data, size_t data_len, bson_subtype_t type);
#endif /* PHONGO_BSON_BINARY_H */
mongodb-2.1.0/src/BSON/BinaryInterface.c 0000644 0001751 0000166 00000001555 15014033047 014624 0 ustar /*
* Copyright 2017-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "BinaryInterface_arginfo.h"
zend_class_entry* php_phongo_binary_interface_ce;
void php_phongo_binary_interface_init_ce(INIT_FUNC_ARGS)
{
php_phongo_binary_interface_ce = register_class_MongoDB_BSON_BinaryInterface();
}
mongodb-2.1.0/src/BSON/BinaryInterface_arginfo.h 0000644 0001751 0000166 00000002532 15014033047 016332 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 48817588d8bad80ae873bb654842960e058e81a2 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_BinaryInterface_getData, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_BinaryInterface_getType, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_BSON_BinaryInterface___toString arginfo_class_MongoDB_BSON_BinaryInterface_getData
static const zend_function_entry class_MongoDB_BSON_BinaryInterface_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_BSON_BinaryInterface, getData, arginfo_class_MongoDB_BSON_BinaryInterface_getData, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_BSON_BinaryInterface, getType, arginfo_class_MongoDB_BSON_BinaryInterface_getType, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_BSON_BinaryInterface, __toString, arginfo_class_MongoDB_BSON_BinaryInterface___toString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_BinaryInterface(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "BinaryInterface", class_MongoDB_BSON_BinaryInterface_methods);
class_entry = zend_register_internal_interface(&ce);
return class_entry;
}
mongodb-2.1.0/src/BSON/Binary_arginfo.h 0000644 0001751 0000166 00000016225 15014033047 014515 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: a08dec3b63e23fbde350360b32fa0323e47069da */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_BSON_Binary___construct, 0, 0, 1)
ZEND_ARG_TYPE_INFO(0, data, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, type, IS_LONG, 0, "MongoDB\\BSON\\Binary::TYPE_GENERIC")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Binary_getData, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Binary_getType, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_Binary___set_state, 0, 1, MongoDB\\BSON\\Binary, 0)
ZEND_ARG_TYPE_INFO(0, properties, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_BSON_Binary___toString arginfo_class_MongoDB_BSON_Binary_getData
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Binary___unserialize, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Binary___serialize, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Binary_jsonSerialize, 0, 0, IS_MIXED, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_BSON_Binary, __construct);
static ZEND_METHOD(MongoDB_BSON_Binary, getData);
static ZEND_METHOD(MongoDB_BSON_Binary, getType);
static ZEND_METHOD(MongoDB_BSON_Binary, __set_state);
static ZEND_METHOD(MongoDB_BSON_Binary, __toString);
static ZEND_METHOD(MongoDB_BSON_Binary, __unserialize);
static ZEND_METHOD(MongoDB_BSON_Binary, __serialize);
static ZEND_METHOD(MongoDB_BSON_Binary, jsonSerialize);
static const zend_function_entry class_MongoDB_BSON_Binary_methods[] = {
ZEND_ME(MongoDB_BSON_Binary, __construct, arginfo_class_MongoDB_BSON_Binary___construct, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Binary, getData, arginfo_class_MongoDB_BSON_Binary_getData, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Binary, getType, arginfo_class_MongoDB_BSON_Binary_getType, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Binary, __set_state, arginfo_class_MongoDB_BSON_Binary___set_state, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Binary, __toString, arginfo_class_MongoDB_BSON_Binary___toString, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Binary, __unserialize, arginfo_class_MongoDB_BSON_Binary___unserialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Binary, __serialize, arginfo_class_MongoDB_BSON_Binary___serialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Binary, jsonSerialize, arginfo_class_MongoDB_BSON_Binary_jsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_Binary(zend_class_entry *class_entry_MongoDB_BSON_BinaryInterface, zend_class_entry *class_entry_JsonSerializable, zend_class_entry *class_entry_MongoDB_BSON_Type, zend_class_entry *class_entry_Stringable)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Binary", class_MongoDB_BSON_Binary_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
zend_class_implements(class_entry, 4, class_entry_MongoDB_BSON_BinaryInterface, class_entry_JsonSerializable, class_entry_MongoDB_BSON_Type, class_entry_Stringable);
zval const_TYPE_GENERIC_value;
ZVAL_LONG(&const_TYPE_GENERIC_value, BSON_SUBTYPE_BINARY);
zend_string *const_TYPE_GENERIC_name = zend_string_init_interned("TYPE_GENERIC", sizeof("TYPE_GENERIC") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_GENERIC_name, &const_TYPE_GENERIC_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_GENERIC_name);
zval const_TYPE_FUNCTION_value;
ZVAL_LONG(&const_TYPE_FUNCTION_value, BSON_SUBTYPE_FUNCTION);
zend_string *const_TYPE_FUNCTION_name = zend_string_init_interned("TYPE_FUNCTION", sizeof("TYPE_FUNCTION") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_FUNCTION_name, &const_TYPE_FUNCTION_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_FUNCTION_name);
zval const_TYPE_OLD_BINARY_value;
ZVAL_LONG(&const_TYPE_OLD_BINARY_value, BSON_SUBTYPE_BINARY_DEPRECATED);
zend_string *const_TYPE_OLD_BINARY_name = zend_string_init_interned("TYPE_OLD_BINARY", sizeof("TYPE_OLD_BINARY") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_OLD_BINARY_name, &const_TYPE_OLD_BINARY_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_OLD_BINARY_name);
zval const_TYPE_OLD_UUID_value;
ZVAL_LONG(&const_TYPE_OLD_UUID_value, BSON_SUBTYPE_UUID_DEPRECATED);
zend_string *const_TYPE_OLD_UUID_name = zend_string_init_interned("TYPE_OLD_UUID", sizeof("TYPE_OLD_UUID") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_OLD_UUID_name, &const_TYPE_OLD_UUID_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_OLD_UUID_name);
zval const_TYPE_UUID_value;
ZVAL_LONG(&const_TYPE_UUID_value, BSON_SUBTYPE_UUID);
zend_string *const_TYPE_UUID_name = zend_string_init_interned("TYPE_UUID", sizeof("TYPE_UUID") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_UUID_name, &const_TYPE_UUID_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_UUID_name);
zval const_TYPE_MD5_value;
ZVAL_LONG(&const_TYPE_MD5_value, BSON_SUBTYPE_MD5);
zend_string *const_TYPE_MD5_name = zend_string_init_interned("TYPE_MD5", sizeof("TYPE_MD5") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_MD5_name, &const_TYPE_MD5_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_MD5_name);
zval const_TYPE_ENCRYPTED_value;
ZVAL_LONG(&const_TYPE_ENCRYPTED_value, BSON_SUBTYPE_ENCRYPTED);
zend_string *const_TYPE_ENCRYPTED_name = zend_string_init_interned("TYPE_ENCRYPTED", sizeof("TYPE_ENCRYPTED") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_ENCRYPTED_name, &const_TYPE_ENCRYPTED_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_ENCRYPTED_name);
zval const_TYPE_COLUMN_value;
ZVAL_LONG(&const_TYPE_COLUMN_value, BSON_SUBTYPE_COLUMN);
zend_string *const_TYPE_COLUMN_name = zend_string_init_interned("TYPE_COLUMN", sizeof("TYPE_COLUMN") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_COLUMN_name, &const_TYPE_COLUMN_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_COLUMN_name);
zval const_TYPE_SENSITIVE_value;
ZVAL_LONG(&const_TYPE_SENSITIVE_value, BSON_SUBTYPE_SENSITIVE);
zend_string *const_TYPE_SENSITIVE_name = zend_string_init_interned("TYPE_SENSITIVE", sizeof("TYPE_SENSITIVE") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_SENSITIVE_name, &const_TYPE_SENSITIVE_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_SENSITIVE_name);
zval const_TYPE_USER_DEFINED_value;
ZVAL_LONG(&const_TYPE_USER_DEFINED_value, BSON_SUBTYPE_USER);
zend_string *const_TYPE_USER_DEFINED_name = zend_string_init_interned("TYPE_USER_DEFINED", sizeof("TYPE_USER_DEFINED") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_USER_DEFINED_name, &const_TYPE_USER_DEFINED_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_USER_DEFINED_name);
return class_entry;
}
mongodb-2.1.0/src/BSON/DBPointer.c 0000644 0001751 0000166 00000017405 15014033047 013406 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bson/bson.h"
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "DBPointer_arginfo.h"
zend_class_entry* php_phongo_dbpointer_ce;
/* Initialize the object and return whether it was successful. An exception will
* be thrown on error. */
static bool php_phongo_dbpointer_init(php_phongo_dbpointer_t* intern, const char* ref, size_t ref_len, const char* id, size_t id_len)
{
if (strlen(ref) != (size_t) ref_len) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Ref cannot contain null bytes");
return false;
}
if (!bson_oid_is_valid(id, id_len)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Error parsing ObjectId string: %s", id);
return false;
}
intern->ref = estrndup(ref, ref_len);
intern->ref_len = ref_len;
memset(intern->id, 0, sizeof(intern->id));
strncpy(intern->id, id, sizeof(intern->id) - 1);
return true;
}
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_dbpointer_init_from_hash(php_phongo_dbpointer_t* intern, HashTable* props)
{
zval *ref, *id;
if ((ref = zend_hash_str_find(props, "ref", sizeof("ref") - 1)) && Z_TYPE_P(ref) == IS_STRING &&
(id = zend_hash_str_find(props, "id", sizeof("id") - 1)) && Z_TYPE_P(id) == IS_STRING) {
return php_phongo_dbpointer_init(intern, Z_STRVAL_P(ref), Z_STRLEN_P(ref), Z_STRVAL_P(id), Z_STRLEN_P(id));
}
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"ref\" and \"id\" string fields", ZSTR_VAL(php_phongo_dbpointer_ce->name));
return false;
}
HashTable* php_phongo_dbpointer_get_properties_hash(zend_object* object, bool is_temp)
{
php_phongo_dbpointer_t* intern;
HashTable* props;
intern = Z_OBJ_DBPOINTER(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_temp, intern, props, 2);
if (!intern->ref) {
return props;
}
{
zval ref, id;
ZVAL_STRING(&ref, intern->ref);
ZVAL_STRING(&id, intern->id);
zend_hash_str_update(props, "ref", sizeof("ref") - 1, &ref);
zend_hash_str_update(props, "id", sizeof("id") - 1, &id);
}
return props;
}
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_BSON_DBPointer)
/* Return the DBPointer's namespace string and ObjectId. */
static PHP_METHOD(MongoDB_BSON_DBPointer, __toString)
{
php_phongo_dbpointer_t* intern;
char* retval;
int retval_len;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_DBPOINTER_OBJ_P(getThis());
retval_len = spprintf(&retval, 0, "[%s/%s]", intern->ref, intern->id);
RETVAL_STRINGL(retval, retval_len);
efree(retval);
}
static PHP_METHOD(MongoDB_BSON_DBPointer, __set_state)
{
php_phongo_dbpointer_t* intern;
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
object_init_ex(return_value, php_phongo_dbpointer_ce);
intern = Z_DBPOINTER_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_dbpointer_init_from_hash(intern, props);
}
static PHP_METHOD(MongoDB_BSON_DBPointer, jsonSerialize)
{
php_phongo_dbpointer_t* intern;
zval zdb_pointer;
zval zoid;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_DBPOINTER_OBJ_P(getThis());
array_init_size(&zdb_pointer, 2);
array_init_size(&zoid, 1);
ADD_ASSOC_STRINGL(&zdb_pointer, "$ref", intern->ref, intern->ref_len);
ADD_ASSOC_STRING(&zoid, "$oid", intern->id);
ADD_ASSOC_ZVAL(&zdb_pointer, "$id", &zoid);
array_init_size(return_value, 1);
ADD_ASSOC_ZVAL(return_value, "$dbPointer", &zdb_pointer);
}
static PHP_METHOD(MongoDB_BSON_DBPointer, __serialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_ARR(php_phongo_dbpointer_get_properties_hash(Z_OBJ_P(getThis()), true));
}
static PHP_METHOD(MongoDB_BSON_DBPointer, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_dbpointer_init_from_hash(Z_DBPOINTER_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\DBPointer object handlers */
static zend_object_handlers php_phongo_handler_dbpointer;
static void php_phongo_dbpointer_free_object(zend_object* object)
{
php_phongo_dbpointer_t* intern = Z_OBJ_DBPOINTER(object);
zend_object_std_dtor(&intern->std);
if (intern->ref) {
efree(intern->ref);
}
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
}
zend_object* php_phongo_dbpointer_create_object(zend_class_entry* class_type)
{
php_phongo_dbpointer_t* intern = zend_object_alloc(sizeof(php_phongo_dbpointer_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_dbpointer;
return &intern->std;
}
static zend_object* php_phongo_dbpointer_clone_object(zend_object* object)
{
php_phongo_dbpointer_t* intern;
php_phongo_dbpointer_t* new_intern;
zend_object* new_object;
intern = Z_OBJ_DBPOINTER(object);
new_object = php_phongo_dbpointer_create_object(object->ce);
new_intern = Z_OBJ_DBPOINTER(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
php_phongo_dbpointer_init(new_intern, intern->ref, intern->ref_len, intern->id, 24);
return new_object;
}
static int php_phongo_dbpointer_compare_objects(zval* o1, zval* o2)
{
php_phongo_dbpointer_t *intern1, *intern2;
int retval;
ZEND_COMPARE_OBJECTS_FALLBACK(o1, o2);
intern1 = Z_DBPOINTER_OBJ_P(o1);
intern2 = Z_DBPOINTER_OBJ_P(o2);
retval = strcmp(intern1->ref, intern2->ref);
if (retval != 0) {
return retval;
}
return strcmp(intern1->id, intern2->id);
}
static HashTable* php_phongo_dbpointer_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return php_phongo_dbpointer_get_properties_hash(object, true);
}
static HashTable* php_phongo_dbpointer_get_properties(zend_object* object)
{
return php_phongo_dbpointer_get_properties_hash(object, false);
}
void php_phongo_dbpointer_init_ce(INIT_FUNC_ARGS)
{
php_phongo_dbpointer_ce = register_class_MongoDB_BSON_DBPointer(php_phongo_json_serializable_ce, php_phongo_type_ce, zend_ce_stringable);
php_phongo_dbpointer_ce->create_object = php_phongo_dbpointer_create_object;
memcpy(&php_phongo_handler_dbpointer, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_dbpointer.compare = php_phongo_dbpointer_compare_objects;
php_phongo_handler_dbpointer.clone_obj = php_phongo_dbpointer_clone_object;
php_phongo_handler_dbpointer.get_debug_info = php_phongo_dbpointer_get_debug_info;
php_phongo_handler_dbpointer.get_properties = php_phongo_dbpointer_get_properties;
php_phongo_handler_dbpointer.free_obj = php_phongo_dbpointer_free_object;
php_phongo_handler_dbpointer.offset = XtOffsetOf(php_phongo_dbpointer_t, std);
}
bool phongo_dbpointer_new(zval* object, const char* ref, size_t ref_len, const bson_oid_t* oid)
{
php_phongo_dbpointer_t* intern;
object_init_ex(object, php_phongo_dbpointer_ce);
intern = Z_DBPOINTER_OBJ_P(object);
intern->ref = estrndup(ref, ref_len);
intern->ref_len = ref_len;
bson_oid_to_string(oid, intern->id);
return true;
}
mongodb-2.1.0/src/BSON/DBPointer.h 0000644 0001751 0000166 00000001444 15014033047 013407 0 ustar /*
* Copyright 2023-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_BSON_DBPOINTER_H
#define PHONGO_BSON_DBPOINTER_H
bool phongo_dbpointer_new(zval* object, const char* ref, size_t ref_len, const bson_oid_t* oid);
#endif /* PHONGO_BSON_DBPOINTER_H */
mongodb-2.1.0/src/BSON/DBPointer_arginfo.h 0000644 0001751 0000166 00000005357 15014033047 015123 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 3462cf9349062679b50671a9c388a2a1b2930070 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_BSON_DBPointer___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_DBPointer___set_state, 0, 1, MongoDB\\BSON\\DBPointer, 0)
ZEND_ARG_TYPE_INFO(0, properties, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_DBPointer___toString, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_DBPointer___unserialize, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_DBPointer___serialize, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_DBPointer_jsonSerialize, 0, 0, IS_MIXED, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_BSON_DBPointer, __construct);
static ZEND_METHOD(MongoDB_BSON_DBPointer, __set_state);
static ZEND_METHOD(MongoDB_BSON_DBPointer, __toString);
static ZEND_METHOD(MongoDB_BSON_DBPointer, __unserialize);
static ZEND_METHOD(MongoDB_BSON_DBPointer, __serialize);
static ZEND_METHOD(MongoDB_BSON_DBPointer, jsonSerialize);
static const zend_function_entry class_MongoDB_BSON_DBPointer_methods[] = {
ZEND_ME(MongoDB_BSON_DBPointer, __construct, arginfo_class_MongoDB_BSON_DBPointer___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_DBPointer, __set_state, arginfo_class_MongoDB_BSON_DBPointer___set_state, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_DBPointer, __toString, arginfo_class_MongoDB_BSON_DBPointer___toString, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_DBPointer, __unserialize, arginfo_class_MongoDB_BSON_DBPointer___unserialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_DBPointer, __serialize, arginfo_class_MongoDB_BSON_DBPointer___serialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_DBPointer, jsonSerialize, arginfo_class_MongoDB_BSON_DBPointer_jsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_DBPointer(zend_class_entry *class_entry_JsonSerializable, zend_class_entry *class_entry_MongoDB_BSON_Type, zend_class_entry *class_entry_Stringable)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "DBPointer", class_MongoDB_BSON_DBPointer_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
zend_class_implements(class_entry, 3, class_entry_JsonSerializable, class_entry_MongoDB_BSON_Type, class_entry_Stringable);
return class_entry;
}
mongodb-2.1.0/src/BSON/Decimal128.c 0000644 0001751 0000166 00000016037 15014033047 013351 0 ustar /*
* Copyright 2015-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bson/bson.h"
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "Decimal128_arginfo.h"
zend_class_entry* php_phongo_decimal128_ce;
/* Initialize the object and return whether it was successful. An exception will
* be thrown on error. */
static bool php_phongo_decimal128_init(php_phongo_decimal128_t* intern, const char* value)
{
if (!bson_decimal128_from_string(value, &intern->decimal)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Error parsing Decimal128 string: %s", value);
return false;
}
intern->initialized = true;
return true;
}
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_decimal128_init_from_hash(php_phongo_decimal128_t* intern, HashTable* props)
{
zval* dec;
if ((dec = zend_hash_str_find(props, "dec", sizeof("dec") - 1)) && Z_TYPE_P(dec) == IS_STRING) {
return php_phongo_decimal128_init(intern, Z_STRVAL_P(dec));
}
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"dec\" string field", ZSTR_VAL(php_phongo_decimal128_ce->name));
return false;
}
static HashTable* php_phongo_decimal128_get_properties_hash(zend_object* object, bool is_temp)
{
php_phongo_decimal128_t* intern;
HashTable* props;
char outbuf[BSON_DECIMAL128_STRING] = "";
intern = Z_OBJ_DECIMAL128(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_temp, intern, props, 1);
if (!intern->initialized) {
return props;
}
bson_decimal128_to_string(&intern->decimal, outbuf);
{
zval dec;
ZVAL_STRING(&dec, outbuf);
zend_hash_str_update(props, "dec", sizeof("dec") - 1, &dec);
}
return props;
}
/* Construct a new BSON Decimal128 type */
static PHP_METHOD(MongoDB_BSON_Decimal128, __construct)
{
php_phongo_decimal128_t* intern;
char* value;
size_t value_len;
intern = Z_DECIMAL128_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STRING(value, value_len)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_decimal128_init(intern, value);
}
static PHP_METHOD(MongoDB_BSON_Decimal128, __set_state)
{
php_phongo_decimal128_t* intern;
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
object_init_ex(return_value, php_phongo_decimal128_ce);
intern = Z_DECIMAL128_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_decimal128_init_from_hash(intern, props);
}
static PHP_METHOD(MongoDB_BSON_Decimal128, __toString)
{
php_phongo_decimal128_t* intern;
char outbuf[BSON_DECIMAL128_STRING];
intern = Z_DECIMAL128_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
bson_decimal128_to_string(&intern->decimal, outbuf);
RETURN_STRING(outbuf);
}
static PHP_METHOD(MongoDB_BSON_Decimal128, jsonSerialize)
{
php_phongo_decimal128_t* intern;
char outbuf[BSON_DECIMAL128_STRING] = "";
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_DECIMAL128_OBJ_P(getThis());
array_init_size(return_value, 1);
bson_decimal128_to_string(&intern->decimal, outbuf);
ADD_ASSOC_STRING(return_value, "$numberDecimal", outbuf);
}
static PHP_METHOD(MongoDB_BSON_Decimal128, __serialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_ARR(php_phongo_decimal128_get_properties_hash(Z_OBJ_P(getThis()), true));
}
static PHP_METHOD(MongoDB_BSON_Decimal128, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_decimal128_init_from_hash(Z_DECIMAL128_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\Decimal128 object handlers */
static zend_object_handlers php_phongo_handler_decimal128;
static void php_phongo_decimal128_free_object(zend_object* object)
{
php_phongo_decimal128_t* intern = Z_OBJ_DECIMAL128(object);
zend_object_std_dtor(&intern->std);
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
}
static zend_object* php_phongo_decimal128_create_object(zend_class_entry* class_type)
{
php_phongo_decimal128_t* intern = zend_object_alloc(sizeof(php_phongo_decimal128_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_decimal128;
return &intern->std;
}
static zend_object* php_phongo_decimal128_clone_object(zend_object* object)
{
php_phongo_decimal128_t* intern;
php_phongo_decimal128_t* new_intern;
zend_object* new_object;
intern = Z_OBJ_DECIMAL128(object);
new_object = php_phongo_decimal128_create_object(object->ce);
new_intern = Z_OBJ_DECIMAL128(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
// Use memcpy to copy bson value to avoid converting to string and back
memcpy(&new_intern->decimal, &intern->decimal, sizeof(bson_decimal128_t));
new_intern->initialized = true;
return new_object;
}
static HashTable* php_phongo_decimal128_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return php_phongo_decimal128_get_properties_hash(object, true);
}
static HashTable* php_phongo_decimal128_get_properties(zend_object* object)
{
return php_phongo_decimal128_get_properties_hash(object, false);
}
void php_phongo_decimal128_init_ce(INIT_FUNC_ARGS)
{
php_phongo_decimal128_ce = register_class_MongoDB_BSON_Decimal128(php_phongo_decimal128_interface_ce, php_phongo_json_serializable_ce, php_phongo_type_ce, zend_ce_stringable);
php_phongo_decimal128_ce->create_object = php_phongo_decimal128_create_object;
memcpy(&php_phongo_handler_decimal128, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_decimal128.clone_obj = php_phongo_decimal128_clone_object;
php_phongo_handler_decimal128.get_debug_info = php_phongo_decimal128_get_debug_info;
php_phongo_handler_decimal128.get_properties = php_phongo_decimal128_get_properties;
php_phongo_handler_decimal128.free_obj = php_phongo_decimal128_free_object;
php_phongo_handler_decimal128.offset = XtOffsetOf(php_phongo_decimal128_t, std);
}
bool phongo_decimal128_new(zval* object, const bson_decimal128_t* decimal)
{
php_phongo_decimal128_t* intern;
object_init_ex(object, php_phongo_decimal128_ce);
intern = Z_DECIMAL128_OBJ_P(object);
memcpy(&intern->decimal, decimal, sizeof(bson_decimal128_t));
intern->initialized = true;
return true;
}
mongodb-2.1.0/src/BSON/Decimal128.h 0000644 0001751 0000166 00000001422 15014033047 013346 0 ustar /*
* Copyright 2023-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_BSON_DECIMAL128_H
#define PHONGO_BSON_DECIMAL128_H
bool phongo_decimal128_new(zval* object, const bson_decimal128_t* decimal);
#endif /* PHONGO_BSON_DECIMAL128_H */
mongodb-2.1.0/src/BSON/Decimal128Interface.c 0000644 0001751 0000166 00000001601 15014033047 015161 0 ustar /*
* Copyright 2017-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "Decimal128Interface_arginfo.h"
zend_class_entry* php_phongo_decimal128_interface_ce;
void php_phongo_decimal128_interface_init_ce(INIT_FUNC_ARGS)
{
php_phongo_decimal128_interface_ce = register_class_MongoDB_BSON_Decimal128Interface();
}
mongodb-2.1.0/src/BSON/Decimal128Interface_arginfo.h 0000644 0001751 0000166 00000001516 15014033047 016700 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 629d35b8a42f119cefc5563eb015a1e0403b6ac7 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Decimal128Interface___toString, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
static const zend_function_entry class_MongoDB_BSON_Decimal128Interface_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_BSON_Decimal128Interface, __toString, arginfo_class_MongoDB_BSON_Decimal128Interface___toString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_Decimal128Interface(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Decimal128Interface", class_MongoDB_BSON_Decimal128Interface_methods);
class_entry = zend_register_internal_interface(&ce);
return class_entry;
}
mongodb-2.1.0/src/BSON/Decimal128_arginfo.h 0000644 0001751 0000166 00000005645 15014033047 015066 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 93e233be4ba07472af49fe8b8d3278ec30c570a9 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_BSON_Decimal128___construct, 0, 0, 1)
ZEND_ARG_TYPE_INFO(0, value, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Decimal128___toString, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_Decimal128___set_state, 0, 1, MongoDB\\BSON\\Decimal128, 0)
ZEND_ARG_TYPE_INFO(0, properties, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Decimal128___unserialize, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Decimal128___serialize, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Decimal128_jsonSerialize, 0, 0, IS_MIXED, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_BSON_Decimal128, __construct);
static ZEND_METHOD(MongoDB_BSON_Decimal128, __toString);
static ZEND_METHOD(MongoDB_BSON_Decimal128, __set_state);
static ZEND_METHOD(MongoDB_BSON_Decimal128, __unserialize);
static ZEND_METHOD(MongoDB_BSON_Decimal128, __serialize);
static ZEND_METHOD(MongoDB_BSON_Decimal128, jsonSerialize);
static const zend_function_entry class_MongoDB_BSON_Decimal128_methods[] = {
ZEND_ME(MongoDB_BSON_Decimal128, __construct, arginfo_class_MongoDB_BSON_Decimal128___construct, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Decimal128, __toString, arginfo_class_MongoDB_BSON_Decimal128___toString, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Decimal128, __set_state, arginfo_class_MongoDB_BSON_Decimal128___set_state, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Decimal128, __unserialize, arginfo_class_MongoDB_BSON_Decimal128___unserialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Decimal128, __serialize, arginfo_class_MongoDB_BSON_Decimal128___serialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Decimal128, jsonSerialize, arginfo_class_MongoDB_BSON_Decimal128_jsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_Decimal128(zend_class_entry *class_entry_MongoDB_BSON_Decimal128Interface, zend_class_entry *class_entry_JsonSerializable, zend_class_entry *class_entry_MongoDB_BSON_Type, zend_class_entry *class_entry_Stringable)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Decimal128", class_MongoDB_BSON_Decimal128_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
zend_class_implements(class_entry, 4, class_entry_MongoDB_BSON_Decimal128Interface, class_entry_JsonSerializable, class_entry_MongoDB_BSON_Type, class_entry_Stringable);
return class_entry;
}
mongodb-2.1.0/src/BSON/Document.c 0000644 0001751 0000166 00000042404 15014033047 013333 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php_phongo.h"
#include "phongo_error.h"
#include "phongo_bson_encode.h"
#include "BSON/Document_arginfo.h"
#include "BSON/Iterator.h"
zend_class_entry* php_phongo_document_ce;
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_document_init_from_hash(php_phongo_document_t* intern, HashTable* props)
{
zval* data;
if ((data = zend_hash_str_find(props, "data", sizeof("data") - 1)) && Z_TYPE_P(data) == IS_STRING) {
zend_string* decoded = php_base64_decode_str(Z_STR_P(data));
intern->bson = bson_new_from_data((const uint8_t*) ZSTR_VAL(decoded), ZSTR_LEN(decoded));
zend_string_free(decoded);
if (intern->bson == NULL) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires valid BSON", ZSTR_VAL(php_phongo_document_ce->name));
return false;
}
return true;
}
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"data\" string field", ZSTR_VAL(php_phongo_document_ce->name));
return false;
}
static HashTable* php_phongo_document_get_properties_hash(zend_object* object, bool is_temp, int size)
{
php_phongo_document_t* intern;
HashTable* props;
intern = Z_OBJ_DOCUMENT(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_temp, intern, props, size);
if (!intern->bson) {
return props;
}
{
zval data;
ZVAL_STR(&data, php_base64_encode((const unsigned char*) bson_get_data(intern->bson), intern->bson->len));
zend_hash_str_update(props, "data", sizeof("data") - 1, &data);
}
return props;
}
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_BSON_Document)
static PHP_METHOD(MongoDB_BSON_Document, fromBSON)
{
zval zv;
php_phongo_document_t* intern = NULL;
zend_string* bson_string;
const bson_t* bson;
bson_reader_t* reader;
bool eof = false;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STR(bson_string)
PHONGO_PARSE_PARAMETERS_END();
reader = bson_reader_new_from_data((const uint8_t*) ZSTR_VAL(bson_string), ZSTR_LEN(bson_string));
if (!(bson = bson_reader_read(reader, NULL))) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "Could not read document from BSON reader");
goto cleanup;
}
object_init_ex(&zv, php_phongo_document_ce);
intern = Z_DOCUMENT_OBJ_P(&zv);
intern->bson = bson_copy(bson);
if (bson_reader_read(reader, &eof) || !eof) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "Reading document did not exhaust input buffer");
zval_ptr_dtor(&zv);
goto cleanup;
}
RETVAL_ZVAL(&zv, 1, 1);
cleanup:
if (reader) {
bson_reader_destroy(reader);
}
}
static PHP_METHOD(MongoDB_BSON_Document, fromJSON)
{
zval zv;
php_phongo_document_t* intern;
zend_string* json;
bson_t* bson;
bson_error_t error;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STR(json)
PHONGO_PARSE_PARAMETERS_END();
bson = bson_new_from_json((const uint8_t*) ZSTR_VAL(json), ZSTR_LEN(json), &error);
if (!bson) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "%s", error.domain == BSON_ERROR_JSON ? error.message : "Error parsing JSON");
return;
}
object_init_ex(&zv, php_phongo_document_ce);
intern = Z_DOCUMENT_OBJ_P(&zv);
intern->bson = bson;
RETURN_ZVAL(&zv, 1, 1);
}
static PHP_METHOD(MongoDB_BSON_Document, fromPHP)
{
zval zv;
php_phongo_document_t* intern;
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY_OR_OBJECT(data)
PHONGO_PARSE_PARAMETERS_END();
object_init_ex(&zv, php_phongo_document_ce);
intern = Z_DOCUMENT_OBJ_P(&zv);
intern->bson = bson_new();
// Explicitly allow constructing a Document from a PackedArray
php_phongo_zval_to_bson(data, PHONGO_BSON_ALLOW_ROOT_ARRAY, intern->bson, NULL);
RETURN_ZVAL(&zv, 1, 1);
}
static bool php_phongo_document_get(php_phongo_document_t* intern, char* key, size_t key_len, zval* return_value, bool null_if_missing)
{
bson_iter_t iter;
if (!bson_iter_init(&iter, intern->bson)) {
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Could not initialize BSON iterator");
return false;
}
if (!bson_iter_find_w_len(&iter, key, key_len)) {
if (null_if_missing) {
ZVAL_NULL(return_value);
return true;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Could not find key \"%s\" in BSON document", key);
return false;
}
phongo_bson_value_to_zval(bson_iter_value(&iter), return_value);
return true;
}
static bool php_phongo_document_get_by_zval(php_phongo_document_t* intern, zval* key, zval* return_value, bool null_if_missing)
{
if (Z_TYPE_P(key) != IS_STRING && Z_TYPE_P(key) != IS_LONG) {
if (null_if_missing) {
ZVAL_NULL(return_value);
return true;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Could not find key of type \"%s\" in BSON document", zend_zval_type_name(key));
return false;
}
zend_string* tmp_str;
zend_string* str = zval_try_get_tmp_string(key, &tmp_str);
if (!str) {
// Exception already thrown
return false;
}
if (!php_phongo_document_get(intern, ZSTR_VAL(str), ZSTR_LEN(str), return_value, null_if_missing)) {
// Exception already thrown
zend_tmp_string_release(tmp_str);
return false;
}
zend_tmp_string_release(tmp_str);
return true;
}
static PHP_METHOD(MongoDB_BSON_Document, get)
{
php_phongo_document_t* intern;
char* key;
size_t key_len;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STRING(key, key_len)
PHONGO_PARSE_PARAMETERS_END();
intern = Z_DOCUMENT_OBJ_P(getThis());
// May throw, in which case we do nothing
php_phongo_document_get(intern, key, key_len, return_value, false);
}
static PHP_METHOD(MongoDB_BSON_Document, getIterator)
{
PHONGO_PARSE_PARAMETERS_NONE();
phongo_iterator_init(return_value, getThis());
}
static bool php_phongo_document_has(php_phongo_document_t* intern, char* key, size_t key_len)
{
bson_iter_t iter;
if (!bson_iter_init(&iter, intern->bson)) {
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Could not initialize BSON iterator");
return false;
}
return bson_iter_find_w_len(&iter, key, key_len);
}
static bool php_phongo_document_has_by_zval(php_phongo_document_t* intern, zval* key)
{
if (Z_TYPE_P(key) != IS_STRING && Z_TYPE_P(key) != IS_LONG) {
return false;
}
zend_string* tmp_str;
zend_string* str = zval_try_get_tmp_string(key, &tmp_str);
if (!str) {
// Exception already thrown
return false;
}
if (!php_phongo_document_has(intern, ZSTR_VAL(str), ZSTR_LEN(str))) {
// Exception may be thrown if BSON iterator could not be initialized
zend_tmp_string_release(tmp_str);
return false;
}
zend_tmp_string_release(tmp_str);
return true;
}
static PHP_METHOD(MongoDB_BSON_Document, has)
{
php_phongo_document_t* intern;
char* key;
size_t key_len;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STRING(key, key_len)
PHONGO_PARSE_PARAMETERS_END();
intern = Z_DOCUMENT_OBJ_P(getThis());
RETURN_BOOL(php_phongo_document_has(intern, key, key_len));
}
static PHP_METHOD(MongoDB_BSON_Document, toCanonicalExtendedJSON)
{
php_phongo_document_t* intern;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_DOCUMENT_OBJ_P(getThis());
php_phongo_bson_to_json(return_value, intern->bson, PHONGO_JSON_MODE_CANONICAL);
}
static PHP_METHOD(MongoDB_BSON_Document, toRelaxedExtendedJSON)
{
php_phongo_document_t* intern;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_DOCUMENT_OBJ_P(getThis());
php_phongo_bson_to_json(return_value, intern->bson, PHONGO_JSON_MODE_RELAXED);
}
static PHP_METHOD(MongoDB_BSON_Document, toPHP)
{
php_phongo_document_t* intern;
zval* typemap = NULL;
php_phongo_bson_state state;
PHONGO_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY(typemap)
PHONGO_PARSE_PARAMETERS_END();
PHONGO_BSON_INIT_STATE(state);
if (!php_phongo_bson_typemap_to_state(typemap, &state.map)) {
return;
}
intern = Z_DOCUMENT_OBJ_P(getThis());
state.map.int64_as_object = true;
if (!php_phongo_bson_to_zval_ex(intern->bson, &state)) {
zval_ptr_dtor(&state.zchild);
php_phongo_bson_typemap_dtor(&state.map);
RETURN_NULL();
}
php_phongo_bson_typemap_dtor(&state.map);
RETURN_ZVAL(&state.zchild, 0, 1);
}
static PHP_METHOD(MongoDB_BSON_Document, offsetExists)
{
php_phongo_document_t* intern;
zval* offset;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ZVAL(offset)
PHONGO_PARSE_PARAMETERS_END();
intern = Z_DOCUMENT_OBJ_P(getThis());
RETURN_BOOL(php_phongo_document_has_by_zval(intern, offset));
}
static PHP_METHOD(MongoDB_BSON_Document, offsetGet)
{
php_phongo_document_t* intern;
zval* offset;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ZVAL(offset)
PHONGO_PARSE_PARAMETERS_END();
intern = Z_DOCUMENT_OBJ_P(getThis());
// May throw, in which case we do nothing
php_phongo_document_get_by_zval(intern, offset, return_value, false);
}
static PHP_METHOD(MongoDB_BSON_Document, offsetSet)
{
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Cannot write to %s property", ZSTR_VAL(php_phongo_document_ce->name));
}
static PHP_METHOD(MongoDB_BSON_Document, offsetUnset)
{
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Cannot unset %s property", ZSTR_VAL(php_phongo_document_ce->name));
}
static PHP_METHOD(MongoDB_BSON_Document, __toString)
{
php_phongo_document_t* intern;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_DOCUMENT_OBJ_P(getThis());
RETVAL_STRINGL((const char*) bson_get_data(intern->bson), intern->bson->len);
}
static PHP_METHOD(MongoDB_BSON_Document, __set_state)
{
php_phongo_document_t* intern;
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
object_init_ex(return_value, php_phongo_document_ce);
intern = Z_DOCUMENT_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_document_init_from_hash(intern, props);
}
static PHP_METHOD(MongoDB_BSON_Document, __serialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_ARR(php_phongo_document_get_properties_hash(Z_OBJ_P(getThis()), true, 1));
}
static PHP_METHOD(MongoDB_BSON_Document, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_document_init_from_hash(Z_DOCUMENT_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\BSON object handlers */
static zend_object_handlers php_phongo_handler_document;
static void php_phongo_document_free_object(zend_object* object)
{
php_phongo_document_t* intern = Z_OBJ_DOCUMENT(object);
zend_object_std_dtor(&intern->std);
if (intern->bson) {
bson_destroy(intern->bson);
}
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
}
static zend_object* php_phongo_document_create_object(zend_class_entry* class_type)
{
php_phongo_document_t* intern = zend_object_alloc(sizeof(php_phongo_document_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_document;
return &intern->std;
}
static zend_object* php_phongo_document_clone_object(zend_object* object)
{
php_phongo_document_t* intern;
php_phongo_document_t* new_intern;
zend_object* new_object;
intern = Z_OBJ_DOCUMENT(object);
new_object = php_phongo_document_create_object(object->ce);
new_intern = Z_OBJ_DOCUMENT(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
new_intern->bson = bson_copy(intern->bson);
return new_object;
}
static int php_phongo_document_compare_objects(zval* o1, zval* o2)
{
php_phongo_document_t *intern1, *intern2;
ZEND_COMPARE_OBJECTS_FALLBACK(o1, o2);
intern1 = Z_DOCUMENT_OBJ_P(o1);
intern2 = Z_DOCUMENT_OBJ_P(o2);
return bson_compare(intern1->bson, intern2->bson);
}
static HashTable* php_phongo_document_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_document_t* intern;
HashTable* props;
*is_temp = 1;
intern = Z_OBJ_DOCUMENT(object);
/* This get_debug_info handler reports an additional property. This does not
* conflict with other uses of php_phongo_document_get_properties_hash since
* we always allocated a new HashTable with is_temp=true. */
props = php_phongo_document_get_properties_hash(object, true, 2);
{
php_phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
state.map.array.type = PHONGO_TYPEMAP_BSON;
state.map.document.type = PHONGO_TYPEMAP_BSON;
if (!php_phongo_bson_to_zval_ex(intern->bson, &state)) {
zval_ptr_dtor(&state.zchild);
goto failure;
}
zend_hash_str_update(props, "value", sizeof("value") - 1, &state.zchild);
}
return props;
failure:
PHONGO_GET_PROPERTY_HASH_FREE_PROPS(is_temp, props);
return NULL;
}
static HashTable* php_phongo_document_get_properties(zend_object* object)
{
return php_phongo_document_get_properties_hash(object, false, 1);
}
zval* php_phongo_document_read_property(zend_object* object, zend_string* member, int type, void** cache_slot, zval* rv)
{
php_phongo_document_t* intern = Z_OBJ_DOCUMENT(object);
if (!php_phongo_document_get(intern, ZSTR_VAL(member), ZSTR_LEN(member), rv, type == BP_VAR_IS)) {
// Exception already thrown
return &EG(uninitialized_zval);
}
return rv;
}
zval* php_phongo_document_write_property(zend_object* object, zend_string* member, zval* value, void** cache_slot)
{
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Cannot write to %s property", ZSTR_VAL(php_phongo_document_ce->name));
return value;
}
int php_phongo_document_has_property(zend_object* object, zend_string* member, int has_set_exists, void** cache_slot)
{
php_phongo_document_t* intern = Z_OBJ_DOCUMENT(object);
return php_phongo_document_has(intern, ZSTR_VAL(member), ZSTR_LEN(member));
}
void php_phongo_document_unset_property(zend_object* object, zend_string* member, void** cache_slot)
{
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Cannot unset %s property", ZSTR_VAL(php_phongo_document_ce->name));
}
zval* php_phongo_document_read_dimension(zend_object* object, zval* offset, int type, zval* rv)
{
php_phongo_document_t* intern = Z_OBJ_DOCUMENT(object);
if (!php_phongo_document_get_by_zval(intern, offset, rv, type == BP_VAR_IS)) {
// Exception already thrown
return &EG(uninitialized_zval);
}
return rv;
}
void php_phongo_document_write_dimension(zend_object* object, zval* offset, zval* value)
{
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Cannot write to %s property", ZSTR_VAL(php_phongo_document_ce->name));
}
int php_phongo_document_has_dimension(zend_object* object, zval* member, int check_empty)
{
php_phongo_document_t* intern = Z_OBJ_DOCUMENT(object);
return php_phongo_document_has_by_zval(intern, member);
}
void php_phongo_document_unset_dimension(zend_object* object, zval* offset)
{
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Cannot unset %s property", ZSTR_VAL(php_phongo_document_ce->name));
}
void php_phongo_document_init_ce(INIT_FUNC_ARGS)
{
php_phongo_document_ce = register_class_MongoDB_BSON_Document(zend_ce_aggregate, zend_ce_arrayaccess, php_phongo_type_ce, zend_ce_stringable);
php_phongo_document_ce->create_object = php_phongo_document_create_object;
memcpy(&php_phongo_handler_document, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_document.compare = php_phongo_document_compare_objects;
php_phongo_handler_document.clone_obj = php_phongo_document_clone_object;
php_phongo_handler_document.get_debug_info = php_phongo_document_get_debug_info;
php_phongo_handler_document.get_properties = php_phongo_document_get_properties;
php_phongo_handler_document.free_obj = php_phongo_document_free_object;
php_phongo_handler_document.read_property = php_phongo_document_read_property;
php_phongo_handler_document.write_property = php_phongo_document_write_property;
php_phongo_handler_document.has_property = php_phongo_document_has_property;
php_phongo_handler_document.unset_property = php_phongo_document_unset_property;
php_phongo_handler_document.read_dimension = php_phongo_document_read_dimension;
php_phongo_handler_document.write_dimension = php_phongo_document_write_dimension;
php_phongo_handler_document.has_dimension = php_phongo_document_has_dimension;
php_phongo_handler_document.unset_dimension = php_phongo_document_unset_dimension;
php_phongo_handler_document.offset = XtOffsetOf(php_phongo_document_t, std);
}
bool phongo_document_new(zval* object, bson_t* bson, bool copy)
{
php_phongo_document_t* intern;
object_init_ex(object, php_phongo_document_ce);
intern = Z_DOCUMENT_OBJ_P(object);
intern->bson = copy ? bson_copy(bson) : bson;
return true;
}
mongodb-2.1.0/src/BSON/Document.h 0000644 0001751 0000166 00000001401 15014033047 013330 0 ustar /*
* Copyright 2023-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_BSON_DOCUMENT_H
#define PHONGO_BSON_DOCUMENT_H
bool phongo_document_new(zval* object, bson_t* bson, bool copy);
#endif /* PHONGO_BSON_DOCUMENT_H */
mongodb-2.1.0/src/BSON/Document_arginfo.h 0000644 0001751 0000166 00000015617 15014033047 015053 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 13d114590a7c0bc86da4dbb1383d17c296edcb40 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_BSON_Document___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_Document_fromBSON, 0, 1, MongoDB\\BSON\\Document, 0)
ZEND_ARG_TYPE_INFO(0, bson, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_Document_fromJSON, 0, 1, MongoDB\\BSON\\Document, 0)
ZEND_ARG_TYPE_INFO(0, json, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_Document_fromPHP, 0, 1, MongoDB\\BSON\\Document, 0)
ZEND_ARG_TYPE_MASK(0, value, MAY_BE_ARRAY|MAY_BE_OBJECT, NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Document_get, 0, 1, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO(0, key, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_Document_getIterator, 0, 0, MongoDB\\BSON\\Iterator, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Document_has, 0, 1, _IS_BOOL, 0)
ZEND_ARG_TYPE_INFO(0, key, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_class_MongoDB_BSON_Document_toPHP, 0, 0, MAY_BE_ARRAY|MAY_BE_OBJECT)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, typeMap, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Document_toCanonicalExtendedJSON, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_BSON_Document_toRelaxedExtendedJSON arginfo_class_MongoDB_BSON_Document_toCanonicalExtendedJSON
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Document_offsetExists, 0, 1, _IS_BOOL, 0)
ZEND_ARG_TYPE_INFO(0, offset, IS_MIXED, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Document_offsetGet, 0, 1, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO(0, offset, IS_MIXED, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Document_offsetSet, 0, 2, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, offset, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO(0, value, IS_MIXED, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Document_offsetUnset, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, offset, IS_MIXED, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_BSON_Document___toString arginfo_class_MongoDB_BSON_Document_toCanonicalExtendedJSON
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_Document___set_state, 0, 1, MongoDB\\BSON\\Document, 0)
ZEND_ARG_TYPE_INFO(0, properties, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Document___unserialize, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Document___serialize, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_BSON_Document, __construct);
static ZEND_METHOD(MongoDB_BSON_Document, fromBSON);
static ZEND_METHOD(MongoDB_BSON_Document, fromJSON);
static ZEND_METHOD(MongoDB_BSON_Document, fromPHP);
static ZEND_METHOD(MongoDB_BSON_Document, get);
static ZEND_METHOD(MongoDB_BSON_Document, getIterator);
static ZEND_METHOD(MongoDB_BSON_Document, has);
static ZEND_METHOD(MongoDB_BSON_Document, toPHP);
static ZEND_METHOD(MongoDB_BSON_Document, toCanonicalExtendedJSON);
static ZEND_METHOD(MongoDB_BSON_Document, toRelaxedExtendedJSON);
static ZEND_METHOD(MongoDB_BSON_Document, offsetExists);
static ZEND_METHOD(MongoDB_BSON_Document, offsetGet);
static ZEND_METHOD(MongoDB_BSON_Document, offsetSet);
static ZEND_METHOD(MongoDB_BSON_Document, offsetUnset);
static ZEND_METHOD(MongoDB_BSON_Document, __toString);
static ZEND_METHOD(MongoDB_BSON_Document, __set_state);
static ZEND_METHOD(MongoDB_BSON_Document, __unserialize);
static ZEND_METHOD(MongoDB_BSON_Document, __serialize);
static const zend_function_entry class_MongoDB_BSON_Document_methods[] = {
ZEND_ME(MongoDB_BSON_Document, __construct, arginfo_class_MongoDB_BSON_Document___construct, ZEND_ACC_PRIVATE)
ZEND_ME(MongoDB_BSON_Document, fromBSON, arginfo_class_MongoDB_BSON_Document_fromBSON, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Document, fromJSON, arginfo_class_MongoDB_BSON_Document_fromJSON, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Document, fromPHP, arginfo_class_MongoDB_BSON_Document_fromPHP, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Document, get, arginfo_class_MongoDB_BSON_Document_get, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Document, getIterator, arginfo_class_MongoDB_BSON_Document_getIterator, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Document, has, arginfo_class_MongoDB_BSON_Document_has, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Document, toPHP, arginfo_class_MongoDB_BSON_Document_toPHP, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Document, toCanonicalExtendedJSON, arginfo_class_MongoDB_BSON_Document_toCanonicalExtendedJSON, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Document, toRelaxedExtendedJSON, arginfo_class_MongoDB_BSON_Document_toRelaxedExtendedJSON, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Document, offsetExists, arginfo_class_MongoDB_BSON_Document_offsetExists, ZEND_ACC_PUBLIC)
ZEND_ME(MongoDB_BSON_Document, offsetGet, arginfo_class_MongoDB_BSON_Document_offsetGet, ZEND_ACC_PUBLIC)
ZEND_ME(MongoDB_BSON_Document, offsetSet, arginfo_class_MongoDB_BSON_Document_offsetSet, ZEND_ACC_PUBLIC)
ZEND_ME(MongoDB_BSON_Document, offsetUnset, arginfo_class_MongoDB_BSON_Document_offsetUnset, ZEND_ACC_PUBLIC)
ZEND_ME(MongoDB_BSON_Document, __toString, arginfo_class_MongoDB_BSON_Document___toString, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Document, __set_state, arginfo_class_MongoDB_BSON_Document___set_state, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Document, __unserialize, arginfo_class_MongoDB_BSON_Document___unserialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Document, __serialize, arginfo_class_MongoDB_BSON_Document___serialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_Document(zend_class_entry *class_entry_IteratorAggregate, zend_class_entry *class_entry_ArrayAccess, zend_class_entry *class_entry_MongoDB_BSON_Type, zend_class_entry *class_entry_Stringable)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Document", class_MongoDB_BSON_Document_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
zend_class_implements(class_entry, 4, class_entry_IteratorAggregate, class_entry_ArrayAccess, class_entry_MongoDB_BSON_Type, class_entry_Stringable);
return class_entry;
}
mongodb-2.1.0/src/BSON/Int64.c 0000644 0001751 0000166 00000040722 15014033047 012462 0 ustar /*
* Copyright 2018-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "phongo_util.h"
#include "Int64_arginfo.h"
zend_class_entry* php_phongo_int64_ce;
/* Initialize the object and return whether it was successful. */
static bool php_phongo_int64_init(php_phongo_int64_t* intern, int64_t integer)
{
intern->integer = integer;
intern->initialized = true;
return true;
}
/* Initialize the object from a numeric string and return whether it was
* successful. An exception will be thrown on error. */
static bool php_phongo_int64_init_from_string(php_phongo_int64_t* intern, const char* s_integer, size_t s_integer_len)
{
int64_t integer;
if (!php_phongo_parse_int64(&integer, s_integer, s_integer_len)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Error parsing \"%s\" as 64-bit integer for %s initialization", s_integer, ZSTR_VAL(php_phongo_int64_ce->name));
return false;
}
return php_phongo_int64_init(intern, integer);
}
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_int64_init_from_hash(php_phongo_int64_t* intern, HashTable* props)
{
zval* value;
if ((value = zend_hash_str_find(props, "integer", sizeof("integer") - 1)) && Z_TYPE_P(value) == IS_STRING) {
return php_phongo_int64_init_from_string(intern, Z_STRVAL_P(value), Z_STRLEN_P(value));
}
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"integer\" string field", ZSTR_VAL(php_phongo_int64_ce->name));
return false;
}
HashTable* php_phongo_int64_get_properties_hash(zend_object* object, bool is_temp)
{
php_phongo_int64_t* intern;
HashTable* props;
intern = Z_OBJ_INT64(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_temp, intern, props, 2);
if (!intern->initialized) {
return props;
}
{
zval value;
ZVAL_INT64_STRING(&value, intern->integer);
zend_hash_str_update(props, "integer", sizeof("integer") - 1, &value);
}
return props;
}
static PHP_METHOD(MongoDB_BSON_Int64, __construct)
{
php_phongo_int64_t* intern;
zval* value;
intern = Z_INT64_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ZVAL(value);
PHONGO_PARSE_PARAMETERS_END();
if (Z_TYPE_P(value) == IS_STRING) {
php_phongo_int64_init_from_string(intern, Z_STRVAL_P(value), Z_STRLEN_P(value));
} else if (Z_TYPE_P(value) == IS_LONG) {
php_phongo_int64_init(intern, Z_LVAL_P(value));
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected value to be integer or string, %s given", zend_zval_type_name(value));
}
}
/* Return the Int64's value as a string. */
static PHP_METHOD(MongoDB_BSON_Int64, __toString)
{
php_phongo_int64_t* intern;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_INT64_OBJ_P(getThis());
ZVAL_INT64_STRING(return_value, intern->integer);
}
static PHP_METHOD(MongoDB_BSON_Int64, __set_state)
{
php_phongo_int64_t* intern;
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
object_init_ex(return_value, php_phongo_int64_ce);
intern = Z_INT64_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_int64_init_from_hash(intern, props);
}
static PHP_METHOD(MongoDB_BSON_Int64, jsonSerialize)
{
php_phongo_int64_t* intern;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_INT64_OBJ_P(getThis());
array_init_size(return_value, 1);
ADD_ASSOC_INT64_AS_STRING(return_value, "$numberLong", intern->integer);
}
static PHP_METHOD(MongoDB_BSON_Int64, __serialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_ARR(php_phongo_int64_get_properties_hash(Z_OBJ_P(getThis()), true));
}
static PHP_METHOD(MongoDB_BSON_Int64, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_int64_init_from_hash(Z_INT64_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\Int64 object handlers */
static zend_object_handlers php_phongo_handler_int64;
static void php_phongo_int64_free_object(zend_object* object)
{
php_phongo_int64_t* intern = Z_OBJ_INT64(object);
zend_object_std_dtor(&intern->std);
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
}
zend_object* php_phongo_int64_create_object(zend_class_entry* class_type)
{
php_phongo_int64_t* intern = zend_object_alloc(sizeof(php_phongo_int64_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_int64;
return &intern->std;
}
static zend_object* php_phongo_int64_clone_object(zend_object* object)
{
php_phongo_int64_t* intern;
php_phongo_int64_t* new_intern;
zend_object* new_object;
intern = Z_OBJ_INT64(object);
new_object = php_phongo_int64_create_object(object->ce);
new_intern = Z_OBJ_INT64(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
php_phongo_int64_init(new_intern, intern->integer);
return new_object;
}
static bool php_phongo_int64_is_int64_object(zval* object)
{
if (Z_TYPE_P(object) != IS_OBJECT) {
return false;
}
return Z_OBJ_P(object)->ce == php_phongo_int64_ce;
}
static bool php_phongo_int64_is_long_or_double(zval* value)
{
return Z_TYPE_P(value) == IS_LONG || Z_TYPE_P(value) == IS_DOUBLE;
}
static int php_phongo_int64_compare_int64_objects(zval* o1, zval* o2)
{
php_phongo_int64_t *intern1, *intern2;
intern1 = Z_INT64_OBJ_P(o1);
intern2 = Z_INT64_OBJ_P(o2);
if (intern1->integer != intern2->integer) {
return intern1->integer < intern2->integer ? -1 : 1;
}
return 0;
}
static int php_phongo_int64_compare_with_long_or_float(zval* object, zval* value)
{
php_phongo_int64_t* intern;
int64_t long_value;
double double_value;
intern = Z_INT64_OBJ_P(object);
assert(php_phongo_int64_is_long_or_double(value));
switch (Z_TYPE_P(value)) {
case IS_LONG:
long_value = Z_LVAL_P(value);
if (intern->integer != long_value) {
return intern->integer < long_value ? -1 : 1;
}
break;
case IS_DOUBLE:
double_value = Z_DVAL_P(value);
if (intern->integer != double_value) {
return intern->integer < double_value ? -1 : 1;
}
break;
default:
return 0;
}
return 0;
}
static int php_phongo_int64_compare_objects(zval* o1, zval* o2)
{
if (php_phongo_int64_is_int64_object(o1) && php_phongo_int64_is_int64_object(o2)) {
return php_phongo_int64_compare_int64_objects(o1, o2);
}
if (php_phongo_int64_is_int64_object(o1) && php_phongo_int64_is_long_or_double(o2)) {
return php_phongo_int64_compare_with_long_or_float(o1, o2);
}
if (php_phongo_int64_is_long_or_double(o1) && php_phongo_int64_is_int64_object(o2)) {
// Invert the result as we're flipping the values used for comparison
return -1 * php_phongo_int64_compare_with_long_or_float(o2, o1);
}
ZEND_COMPARE_OBJECTS_FALLBACK(o1, o2);
return 0;
}
static zend_result php_phongo_int64_cast_object(zend_object* readobj, zval* retval, int type)
{
php_phongo_int64_t* intern;
intern = Z_OBJ_INT64(readobj);
switch (type) {
case IS_DOUBLE:
ZVAL_DOUBLE(retval, (double) intern->integer);
return SUCCESS;
case IS_LONG:
case _IS_NUMBER:
#if SIZEOF_ZEND_LONG == 4
if (intern->integer > INT32_MAX || intern->integer < INT32_MIN) {
zend_error(E_WARNING, "Truncating 64-bit integer value %" PRId64 " to 32 bits", intern->integer);
}
#endif
ZVAL_LONG(retval, intern->integer);
return SUCCESS;
case _IS_BOOL:
ZVAL_BOOL(retval, intern->integer != 0);
return SUCCESS;
default:
return zend_std_cast_object_tostring(readobj, retval, type);
}
}
/* Computes the power of two int64_t values by using the exponentiation by
* squaring algorithm. This is necessary because in case the result exceeds
* the range of a int64_t, we want PHP to return a float as it would when
* using 64-bit values directly. We can't use anything involving zend_long
* here as this would limit us to 32 bits on a 32-bit platform. This also
* prohibits us from falling back to PHP's default functions after unwrapping
* the int64_t from the php_phongo_int64_t instance. */
static int64_t phongo_pow_int64(int64_t base, int64_t exp)
{
if (exp == 0) {
return 1;
}
if (exp % 2) {
return base * phongo_pow_int64(base * base, (exp - 1) / 2);
}
return phongo_pow_int64(base * base, exp / 2);
}
#define OPERATION_RESULT_INT64(value) phongo_int64_new(result, (value));
#define PHONGO_GET_INT64(int64, zval) \
if (Z_TYPE_P((zval)) == IS_LONG) { \
(int64) = Z_LVAL_P((zval)); \
} else if (Z_TYPE_P((zval)) == IS_OBJECT && Z_OBJCE_P((zval)) == php_phongo_int64_ce) { \
(int64) = Z_INT64_OBJ_P((zval))->integer; \
} else { \
return FAILURE; \
}
#define INT64_SIGN_MASK INT64_MIN
/* Overload arithmetic operators for computation on int64_t values.
* This ensures that any computation involving at least one php_phongo_int64_t
* results in a php_phongo_int64_t value, regardless of whether the result
* would fit in an int32_t or not. Results that exceed the 64-bit integer
* range are returned as float as PHP would do when using 64-bit integers.
* Note that ZEND_(PRE|POST)_(INC|DEC) are not handled here: when checking for
* a do_operation handler for inc/dec, PHP calls the handler with a ZEND_ADD
* or ZEND_SUB opcode and the same pointer for result and op1, and a ZVAL_LONG
* of 1 for op2. */
static zend_result php_phongo_int64_do_operation_ex(zend_uchar opcode, zval* result, zval* op1, zval* op2)
{
int64_t value1, value2, lresult;
PHONGO_GET_INT64(value1, op1);
switch (opcode) {
case ZEND_ADD:
PHONGO_GET_INT64(value2, op2);
lresult = value1 + value2;
/* The following is based on the logic in fast_long_add_function() in PHP.
* If the result sign differs from the first operand sign, we have an overflow if:
* - adding a positive to a positive yields a negative, or
* - adding a negative to a negative (i.e. subtraction) yields a positive */
if ((value1 & INT64_SIGN_MASK) != (lresult & INT64_SIGN_MASK) && (value1 & INT64_SIGN_MASK) == (value2 & INT64_SIGN_MASK)) {
ZVAL_DOUBLE(result, (double) value1 + (double) value2);
} else {
OPERATION_RESULT_INT64(lresult);
}
return SUCCESS;
case ZEND_SUB:
PHONGO_GET_INT64(value2, op2);
lresult = value1 - value2;
/* The following is based on the logic in fast_long_sub_function() in PHP.
* If the result sign differs from the first operand sign, we have an overflow if:
* - subtracting a positive from a negative yields a positive, or
* - subtracting a negative from a positive (i.e. addition) yields a negative */
if ((value1 & INT64_SIGN_MASK) != (lresult & INT64_SIGN_MASK) && (value1 & INT64_SIGN_MASK) != (value2 & INT64_SIGN_MASK)) {
ZVAL_DOUBLE(result, (double) value1 - (double) value2);
} else {
OPERATION_RESULT_INT64(lresult);
}
return SUCCESS;
case ZEND_MUL:
PHONGO_GET_INT64(value2, op2);
/* The following is based on the C-native implementation of
* ZEND_SIGNED_MULTIPLY_LONG() in PHP if no other methods (e.g. ASM
* or _builtin_smull_overflow) can be used. */
{
int64_t lres = value1 * value2;
long double dres = (long double) value1 * (long double) value2;
long double delta = (long double) lres - dres;
if ((dres + delta) != dres) {
ZVAL_DOUBLE(result, dres);
} else {
OPERATION_RESULT_INT64(lres);
}
}
return SUCCESS;
case ZEND_DIV:
PHONGO_GET_INT64(value2, op2);
if (value2 == 0) {
zend_throw_exception(zend_ce_division_by_zero_error, "Division by zero", 0);
return FAILURE;
}
/* The following is based on div_function_base() in PHP.
* - INT64_MIN / 1 exceeds the int64 range -> return double
* - if division has a remainder, return double as result can't be
* an int */
if ((value1 == INT64_MIN && value2 == -1) || (value1 % value2 != 0)) {
ZVAL_DOUBLE(result, (double) value1 / value2);
} else {
OPERATION_RESULT_INT64(value1 / value2);
}
return SUCCESS;
case ZEND_MOD:
PHONGO_GET_INT64(value2, op2);
if (value2 == 0) {
zend_throw_exception(zend_ce_division_by_zero_error, "Division by zero", 0);
return FAILURE;
}
OPERATION_RESULT_INT64(value1 % value2);
return SUCCESS;
case ZEND_SL:
PHONGO_GET_INT64(value2, op2);
OPERATION_RESULT_INT64(value1 << value2);
return SUCCESS;
case ZEND_SR:
PHONGO_GET_INT64(value2, op2);
OPERATION_RESULT_INT64(value1 >> value2);
return SUCCESS;
case ZEND_POW:
PHONGO_GET_INT64(value2, op2);
// Negative exponents always yield floats, leave them for PHP to handle
if (value2 < 0) {
return FAILURE;
}
// Handle 0 separately to distinguish between base 0 and
// phongo_pow_int64 overflowing
if (value1 == 0) {
OPERATION_RESULT_INT64(0);
return SUCCESS;
}
{
int64_t pow_result = phongo_pow_int64(value1, value2);
// If the result would overflow an int64_t, we let PHP fall back
// to its default pow() implementation which returns a float.
if (pow_result == 0) {
return FAILURE;
}
OPERATION_RESULT_INT64(pow_result);
}
return SUCCESS;
case ZEND_BW_AND:
PHONGO_GET_INT64(value2, op2);
OPERATION_RESULT_INT64(value1 & value2);
return SUCCESS;
case ZEND_BW_OR:
PHONGO_GET_INT64(value2, op2);
OPERATION_RESULT_INT64(value1 | value2);
return SUCCESS;
case ZEND_BW_XOR:
PHONGO_GET_INT64(value2, op2);
OPERATION_RESULT_INT64(value1 ^ value2);
return SUCCESS;
case ZEND_BW_NOT:
OPERATION_RESULT_INT64(~value1);
return SUCCESS;
default:
return FAILURE;
}
}
static zend_result php_phongo_int64_do_operation(zend_uchar opcode, zval* result, zval* op1, zval* op2)
{
zval op1_copy;
int retval;
// Copy op1 for unary operations (e.g. $int64++) to ensure correct return values
if (result == op1) {
ZVAL_COPY_VALUE(&op1_copy, op1);
op1 = &op1_copy;
}
retval = php_phongo_int64_do_operation_ex(opcode, result, op1, op2);
if (retval == SUCCESS && op1 == &op1_copy) {
zval_ptr_dtor(op1);
}
return retval;
}
#undef OPERATION_RESULT_INT64
#undef PHONGO_GET_INT64
#undef INT64_SIGN_MASK
static HashTable* php_phongo_int64_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return php_phongo_int64_get_properties_hash(object, true);
}
static HashTable* php_phongo_int64_get_properties(zend_object* object)
{
return php_phongo_int64_get_properties_hash(object, false);
}
void php_phongo_int64_init_ce(INIT_FUNC_ARGS)
{
php_phongo_int64_ce = register_class_MongoDB_BSON_Int64(php_phongo_json_serializable_ce, php_phongo_type_ce, zend_ce_stringable);
php_phongo_int64_ce->create_object = php_phongo_int64_create_object;
memcpy(&php_phongo_handler_int64, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_int64.compare = php_phongo_int64_compare_objects;
php_phongo_handler_int64.clone_obj = php_phongo_int64_clone_object;
php_phongo_handler_int64.get_debug_info = php_phongo_int64_get_debug_info;
php_phongo_handler_int64.get_properties = php_phongo_int64_get_properties;
php_phongo_handler_int64.free_obj = php_phongo_int64_free_object;
php_phongo_handler_int64.offset = XtOffsetOf(php_phongo_int64_t, std);
php_phongo_handler_int64.cast_object = php_phongo_int64_cast_object;
php_phongo_handler_int64.do_operation = php_phongo_int64_do_operation;
}
bool phongo_int64_new(zval* object, int64_t integer)
{
php_phongo_int64_t* intern;
object_init_ex(object, php_phongo_int64_ce);
intern = Z_INT64_OBJ_P(object);
intern->integer = integer;
intern->initialized = true;
return true;
}
mongodb-2.1.0/src/BSON/Int64.h 0000644 0001751 0000166 00000001355 15014033047 012466 0 ustar /*
* Copyright 2023-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_BSON_INT64_H
#define PHONGO_BSON_INT64_H
bool phongo_int64_new(zval* object, int64_t integer);
#endif /* PHONGO_BSON_INT64_H */
mongodb-2.1.0/src/BSON/Int64_arginfo.h 0000644 0001751 0000166 00000005271 15014033047 014174 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: ecb9f0dd09b4af79334ef03ac2a5e04f111ab7b3 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_BSON_Int64___construct, 0, 0, 1)
ZEND_ARG_TYPE_MASK(0, value, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Int64___toString, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_Int64___set_state, 0, 1, MongoDB\\BSON\\Int64, 0)
ZEND_ARG_TYPE_INFO(0, properties, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Int64___unserialize, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Int64___serialize, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Int64_jsonSerialize, 0, 0, IS_MIXED, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_BSON_Int64, __construct);
static ZEND_METHOD(MongoDB_BSON_Int64, __toString);
static ZEND_METHOD(MongoDB_BSON_Int64, __set_state);
static ZEND_METHOD(MongoDB_BSON_Int64, __unserialize);
static ZEND_METHOD(MongoDB_BSON_Int64, __serialize);
static ZEND_METHOD(MongoDB_BSON_Int64, jsonSerialize);
static const zend_function_entry class_MongoDB_BSON_Int64_methods[] = {
ZEND_ME(MongoDB_BSON_Int64, __construct, arginfo_class_MongoDB_BSON_Int64___construct, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Int64, __toString, arginfo_class_MongoDB_BSON_Int64___toString, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Int64, __set_state, arginfo_class_MongoDB_BSON_Int64___set_state, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Int64, __unserialize, arginfo_class_MongoDB_BSON_Int64___unserialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Int64, __serialize, arginfo_class_MongoDB_BSON_Int64___serialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Int64, jsonSerialize, arginfo_class_MongoDB_BSON_Int64_jsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_Int64(zend_class_entry *class_entry_JsonSerializable, zend_class_entry *class_entry_MongoDB_BSON_Type, zend_class_entry *class_entry_Stringable)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Int64", class_MongoDB_BSON_Int64_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
zend_class_implements(class_entry, 3, class_entry_JsonSerializable, class_entry_MongoDB_BSON_Type, class_entry_Stringable);
return class_entry;
}
mongodb-2.1.0/src/BSON/Iterator.c 0000644 0001751 0000166 00000024357 15014033047 013355 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include
#include
#include
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php_phongo.h"
#include "phongo_error.h"
#include "BSON/Iterator.h"
#include "BSON/Iterator_arginfo.h"
zend_class_entry* php_phongo_iterator_ce;
static const bson_t* php_phongo_iterator_get_bson_from_zval(zval* zbson)
{
if (Z_TYPE_P(zbson) != IS_OBJECT) {
return NULL;
}
if (instanceof_function(Z_OBJCE_P(zbson), php_phongo_document_ce)) {
return Z_DOCUMENT_OBJ_P(zbson)->bson;
} else if (instanceof_function(Z_OBJCE_P(zbson), php_phongo_packedarray_ce)) {
return Z_PACKEDARRAY_OBJ_P(zbson)->bson;
} else {
return NULL;
}
}
static bool php_phongo_iterator_init_with_zval(php_phongo_iterator_t* iterator, zval* zbson)
{
const bson_t* bson;
bson = php_phongo_iterator_get_bson_from_zval(zbson);
if (!bson) {
/* Should never happen, but if it does: exception */
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Could not create iterator for %s instance", zend_zval_type_name(zbson));
return false;
}
if (!bson_iter_init(&iterator->iter, bson)) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "Could not create iterator for %s instance", zend_zval_type_name(zbson));
return false;
}
ZVAL_COPY(&iterator->bson, zbson);
if (instanceof_function(Z_OBJCE_P(zbson), php_phongo_packedarray_ce)) {
iterator->is_array = true;
}
iterator->valid = bson_iter_next(&iterator->iter);
return true;
}
static void php_phongo_iterator_free_current(php_phongo_iterator_t* intern)
{
if (Z_ISUNDEF(intern->current)) {
return;
}
zval_ptr_dtor(&intern->current);
ZVAL_UNDEF(&intern->current);
}
static void php_phongo_iterator_build_current(php_phongo_iterator_t* intern)
{
php_phongo_iterator_free_current(intern);
phongo_bson_value_to_zval(bson_iter_value(&intern->iter), &intern->current);
}
static zval* php_phongo_iterator_get_current(php_phongo_iterator_t* intern)
{
if (!intern->valid) {
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Cannot call current() on an exhausted iterator");
return NULL;
}
if (Z_ISUNDEF(intern->current)) {
php_phongo_iterator_build_current(intern);
}
return &intern->current;
}
static void php_phongo_iterator_next(php_phongo_iterator_t* intern)
{
intern->valid = bson_iter_next(&intern->iter);
intern->key++;
php_phongo_iterator_free_current(intern);
}
static bool php_phongo_iterator_key(php_phongo_iterator_t* intern, zval* key)
{
const char* ckey;
if (!intern->valid) {
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Cannot call key() on an exhausted iterator");
return false;
}
if (intern->is_array) {
ZVAL_LONG(key, intern->key);
return true;
}
ckey = bson_iter_key(&intern->iter);
if (!bson_utf8_validate(ckey, strlen(ckey), false)) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "Detected corrupt BSON data at offset %d", intern->iter.off);
return false;
}
ZVAL_STRING(key, ckey);
return true;
}
static void php_phongo_iterator_rewind(php_phongo_iterator_t* intern)
{
/* Don't re-initialise iterator if we're still on the first item */
if (intern->key == 0) {
return;
}
php_phongo_iterator_free_current(intern);
bson_iter_init(&intern->iter, php_phongo_iterator_get_bson_from_zval(&intern->bson));
intern->key = 0;
intern->valid = bson_iter_next(&intern->iter);
}
static HashTable* php_phongo_iterator_get_properties_hash(zend_object* object, bool is_temp)
{
php_phongo_iterator_t* intern;
HashTable* props;
intern = Z_OBJ_ITERATOR(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_temp, intern, props, 1);
zend_hash_str_update(props, "bson", sizeof("bson") - 1, &intern->bson);
Z_TRY_ADDREF(intern->bson);
return props;
}
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_BSON_Iterator)
static PHP_METHOD(MongoDB_BSON_Iterator, current)
{
php_phongo_iterator_t* intern = Z_ITERATOR_OBJ_P(getThis());
zval* data;
PHONGO_PARSE_PARAMETERS_NONE();
data = php_phongo_iterator_get_current(intern);
if (!data) {
// Exception already thrown
RETURN_NULL();
}
if (Z_ISUNDEF_P(data)) {
RETURN_NULL();
} else {
ZVAL_COPY_DEREF(return_value, data);
}
}
static PHP_METHOD(MongoDB_BSON_Iterator, key)
{
php_phongo_iterator_t* intern = Z_ITERATOR_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
if (!php_phongo_iterator_key(intern, return_value)) {
// Exception already thrown
return;
}
}
static PHP_METHOD(MongoDB_BSON_Iterator, next)
{
php_phongo_iterator_t* intern = Z_ITERATOR_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
php_phongo_iterator_next(intern);
}
static PHP_METHOD(MongoDB_BSON_Iterator, valid)
{
php_phongo_iterator_t* intern = Z_ITERATOR_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_BOOL(intern->valid);
}
static PHP_METHOD(MongoDB_BSON_Iterator, rewind)
{
php_phongo_iterator_t* intern = Z_ITERATOR_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
php_phongo_iterator_rewind(intern);
}
void phongo_iterator_init(zval* return_value, zval* document_or_packedarray)
{
php_phongo_iterator_t* intern;
object_init_ex(return_value, php_phongo_iterator_ce);
intern = Z_ITERATOR_OBJ_P(return_value);
php_phongo_iterator_init_with_zval(intern, document_or_packedarray);
}
/* MongoDB\BSON\Iterator object handlers */
static zend_object_handlers php_phongo_handler_iterator;
static void php_phongo_iterator_free_object(zend_object* object)
{
php_phongo_iterator_t* intern = Z_OBJ_ITERATOR(object);
zend_object_std_dtor(&intern->std);
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
php_phongo_iterator_free_current(intern);
zval_ptr_dtor(&intern->bson);
}
static zend_object* php_phongo_iterator_create_object(zend_class_entry* class_type)
{
php_phongo_iterator_t* intern = zend_object_alloc(sizeof(php_phongo_iterator_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_iterator;
return &intern->std;
}
static zend_object* php_phongo_iterator_clone_object(zend_object* object)
{
php_phongo_iterator_t* intern;
php_phongo_iterator_t* new_intern;
zend_object* new_object;
intern = Z_OBJ_ITERATOR(object);
new_object = php_phongo_iterator_create_object(object->ce);
new_intern = Z_OBJ_ITERATOR(new_object);
php_phongo_iterator_init_with_zval(new_intern, &intern->bson);
zend_objects_clone_members(&new_intern->std, &intern->std);
return new_object;
}
static HashTable* php_phongo_iterator_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return php_phongo_iterator_get_properties_hash(object, true);
}
static HashTable* php_phongo_iterator_get_properties(zend_object* object)
{
return php_phongo_iterator_get_properties_hash(object, false);
}
/* Iterator handlers */
static void php_phongo_iterator_it_dtor(zend_object_iterator* iter)
{
zval_ptr_dtor(&iter->data);
}
static int php_phongo_iterator_it_valid(zend_object_iterator* iter)
{
php_phongo_iterator_t* intern = Z_ITERATOR_OBJ_P(&iter->data);
return intern->valid ? SUCCESS : FAILURE;
}
static zval* php_phongo_iterator_it_get_current_data(zend_object_iterator* iter)
{
php_phongo_iterator_t* intern = Z_ITERATOR_OBJ_P(&iter->data);
return php_phongo_iterator_get_current(intern);
}
static void php_phongo_iterator_it_get_current_key(zend_object_iterator* iter, zval* key)
{
php_phongo_iterator_t* intern = Z_ITERATOR_OBJ_P(&iter->data);
if (!php_phongo_iterator_key(intern, key)) {
// Exception already thrown
return;
}
}
static void php_phongo_iterator_it_move_forward(zend_object_iterator* iter)
{
php_phongo_iterator_t* intern = Z_ITERATOR_OBJ_P(&iter->data);
php_phongo_iterator_next(intern);
}
static void php_phongo_iterator_it_rewind(zend_object_iterator* iter)
{
php_phongo_iterator_t* intern = Z_ITERATOR_OBJ_P(&iter->data);
php_phongo_iterator_rewind(intern);
}
static HashTable* php_phongo_iterator_it_get_gc(zend_object_iterator* iter, zval** table, int* n)
{
*n = 1;
*table = &iter->data;
return NULL;
}
static const zend_object_iterator_funcs php_phongo_iterator_it_funcs = {
php_phongo_iterator_it_dtor,
php_phongo_iterator_it_valid,
php_phongo_iterator_it_get_current_data,
php_phongo_iterator_it_get_current_key,
php_phongo_iterator_it_move_forward,
php_phongo_iterator_it_rewind,
NULL, /* invalidate_current */
php_phongo_iterator_it_get_gc
};
static zend_object_iterator* php_phongo_iterator_get_iterator(zend_class_entry* ce, zval* object, int by_ref)
{
zend_object_iterator* iterator;
if (by_ref) {
phongo_throw_exception(PHONGO_ERROR_LOGIC, "An iterator cannot be used with foreach by reference");
return NULL;
}
iterator = emalloc(sizeof(zend_object_iterator));
zend_iterator_init(iterator);
ZVAL_OBJ_COPY(&iterator->data, Z_OBJ_P(object));
iterator->funcs = &php_phongo_iterator_it_funcs;
return iterator;
}
void php_phongo_iterator_init_ce(INIT_FUNC_ARGS)
{
php_phongo_iterator_ce = register_class_MongoDB_BSON_Iterator(zend_ce_iterator);
php_phongo_iterator_ce->create_object = php_phongo_iterator_create_object;
php_phongo_iterator_ce->get_iterator = php_phongo_iterator_get_iterator;
memcpy(&php_phongo_handler_iterator, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_iterator.clone_obj = php_phongo_iterator_clone_object;
php_phongo_handler_iterator.get_debug_info = php_phongo_iterator_get_debug_info;
php_phongo_handler_iterator.get_properties = php_phongo_iterator_get_properties;
php_phongo_handler_iterator.free_obj = php_phongo_iterator_free_object;
php_phongo_handler_iterator.offset = XtOffsetOf(php_phongo_iterator_t, std);
}
mongodb-2.1.0/src/BSON/Iterator.h 0000644 0001751 0000166 00000001403 15014033047 013345 0 ustar /*
* Copyright 2022-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_ITERATOR_H
#define PHONGO_ITERATOR_H
#include
void phongo_iterator_init(zval* return_value, zval* document_or_packedarray);
#endif /* PHONGO_ITERATOR_H */
mongodb-2.1.0/src/BSON/Iterator_arginfo.h 0000644 0001751 0000166 00000004474 15014033047 015065 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: b1cb9bc973c616b9ec005232e95368bf1b233480 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_BSON_Iterator___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Iterator_current, 0, 0, IS_MIXED, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_class_MongoDB_BSON_Iterator_key, 0, 0, MAY_BE_STRING|MAY_BE_LONG)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Iterator_next, 0, 0, IS_VOID, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_BSON_Iterator_rewind arginfo_class_MongoDB_BSON_Iterator_next
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Iterator_valid, 0, 0, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_BSON_Iterator, __construct);
static ZEND_METHOD(MongoDB_BSON_Iterator, current);
static ZEND_METHOD(MongoDB_BSON_Iterator, key);
static ZEND_METHOD(MongoDB_BSON_Iterator, next);
static ZEND_METHOD(MongoDB_BSON_Iterator, rewind);
static ZEND_METHOD(MongoDB_BSON_Iterator, valid);
static const zend_function_entry class_MongoDB_BSON_Iterator_methods[] = {
ZEND_ME(MongoDB_BSON_Iterator, __construct, arginfo_class_MongoDB_BSON_Iterator___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Iterator, current, arginfo_class_MongoDB_BSON_Iterator_current, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Iterator, key, arginfo_class_MongoDB_BSON_Iterator_key, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Iterator, next, arginfo_class_MongoDB_BSON_Iterator_next, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Iterator, rewind, arginfo_class_MongoDB_BSON_Iterator_rewind, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Iterator, valid, arginfo_class_MongoDB_BSON_Iterator_valid, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_Iterator(zend_class_entry *class_entry_Iterator)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Iterator", class_MongoDB_BSON_Iterator_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
zend_class_implements(class_entry, 1, class_entry_Iterator);
return class_entry;
}
mongodb-2.1.0/src/BSON/Javascript.c 0000644 0001751 0000166 00000023721 15014033047 013664 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bson/bson.h"
#include
#include
#include "php_phongo.h"
#include "phongo_bson_encode.h"
#include "phongo_error.h"
#include "Javascript_arginfo.h"
zend_class_entry* php_phongo_javascript_ce;
/* Initialize the object and return whether it was successful. An exception will
* be thrown on error. */
static bool php_phongo_javascript_init(php_phongo_javascript_t* intern, const char* code, size_t code_len, zval* scope)
{
if (scope && Z_TYPE_P(scope) != IS_OBJECT && Z_TYPE_P(scope) != IS_ARRAY && Z_TYPE_P(scope) != IS_NULL) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected scope to be array or object, %s given", zend_get_type_by_const(Z_TYPE_P(scope)));
return false;
}
if (strlen(code) != (size_t) code_len) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Code cannot contain null bytes");
return false;
}
intern->code = estrndup(code, code_len);
intern->code_len = code_len;
if (scope && (Z_TYPE_P(scope) == IS_OBJECT || Z_TYPE_P(scope) == IS_ARRAY)) {
intern->scope = bson_new();
php_phongo_zval_to_bson(scope, PHONGO_BSON_NONE, intern->scope, NULL);
} else {
intern->scope = NULL;
}
return true;
}
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_javascript_init_from_hash(php_phongo_javascript_t* intern, HashTable* props)
{
zval *code, *scope;
if ((code = zend_hash_str_find(props, "code", sizeof("code") - 1)) && Z_TYPE_P(code) == IS_STRING) {
scope = zend_hash_str_find(props, "scope", sizeof("scope") - 1);
return php_phongo_javascript_init(intern, Z_STRVAL_P(code), Z_STRLEN_P(code), scope);
}
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"code\" string field", ZSTR_VAL(php_phongo_javascript_ce->name));
return false;
}
HashTable* php_phongo_javascript_get_properties_hash(zend_object* object, bool is_temp)
{
php_phongo_javascript_t* intern;
HashTable* props;
intern = Z_OBJ_JAVASCRIPT(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_temp, intern, props, 2);
if (!intern->code) {
return props;
}
{
zval code;
ZVAL_STRING(&code, intern->code);
zend_hash_str_update(props, "code", sizeof("code") - 1, &code);
if (intern->scope) {
php_phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
if (!php_phongo_bson_to_zval_ex(intern->scope, &state)) {
zval_ptr_dtor(&state.zchild);
goto failure;
}
zend_hash_str_update(props, "scope", sizeof("scope") - 1, &state.zchild);
} else {
zval scope;
ZVAL_NULL(&scope);
zend_hash_str_update(props, "scope", sizeof("scope") - 1, &scope);
}
}
return props;
failure:
PHONGO_GET_PROPERTY_HASH_FREE_PROPS(is_temp, props);
return NULL;
}
/* Construct a new BSON Javascript type. The scope is a document mapping
identifiers and values, representing the scope in which the code string will
be evaluated. Note that this type cannot be represented as Extended JSON. */
static PHP_METHOD(MongoDB_BSON_Javascript, __construct)
{
php_phongo_javascript_t* intern;
char* code;
size_t code_len;
zval* scope = NULL;
intern = Z_JAVASCRIPT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_STRING(code, code_len)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_OBJECT_EX(scope, 1, 0)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_javascript_init(intern, code, code_len, scope);
}
static PHP_METHOD(MongoDB_BSON_Javascript, __set_state)
{
php_phongo_javascript_t* intern;
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
object_init_ex(return_value, php_phongo_javascript_ce);
intern = Z_JAVASCRIPT_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_javascript_init_from_hash(intern, props);
}
/* Return the Javascript's code string. */
static PHP_METHOD(MongoDB_BSON_Javascript, __toString)
{
php_phongo_javascript_t* intern;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_JAVASCRIPT_OBJ_P(getThis());
RETURN_STRINGL(intern->code, intern->code_len);
}
static PHP_METHOD(MongoDB_BSON_Javascript, getCode)
{
php_phongo_javascript_t* intern;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_JAVASCRIPT_OBJ_P(getThis());
RETURN_STRINGL(intern->code, intern->code_len);
}
static PHP_METHOD(MongoDB_BSON_Javascript, getScope)
{
php_phongo_javascript_t* intern;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_JAVASCRIPT_OBJ_P(getThis());
if (!intern->scope) {
RETURN_NULL();
}
if (intern->scope->len) {
php_phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
if (!php_phongo_bson_to_zval_ex(intern->scope, &state)) {
zval_ptr_dtor(&state.zchild);
return;
}
RETURN_ZVAL(&state.zchild, 0, 1);
} else {
RETURN_NULL();
}
}
static PHP_METHOD(MongoDB_BSON_Javascript, jsonSerialize)
{
php_phongo_javascript_t* intern;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_JAVASCRIPT_OBJ_P(getThis());
array_init_size(return_value, 2);
ADD_ASSOC_STRINGL(return_value, "$code", intern->code, intern->code_len);
if (intern->scope && intern->scope->len) {
php_phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
if (!php_phongo_bson_to_zval_ex(intern->scope, &state)) {
zval_ptr_dtor(&state.zchild);
return;
}
ADD_ASSOC_ZVAL_EX(return_value, "$scope", &state.zchild);
}
}
static PHP_METHOD(MongoDB_BSON_Javascript, __serialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_ARR(php_phongo_javascript_get_properties_hash(Z_OBJ_P(getThis()), true));
}
static PHP_METHOD(MongoDB_BSON_Javascript, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_javascript_init_from_hash(Z_JAVASCRIPT_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\Javascript object handlers */
static zend_object_handlers php_phongo_handler_javascript;
static void php_phongo_javascript_free_object(zend_object* object)
{
php_phongo_javascript_t* intern = Z_OBJ_JAVASCRIPT(object);
zend_object_std_dtor(&intern->std);
if (intern->code) {
efree(intern->code);
}
if (intern->scope) {
bson_destroy(intern->scope);
intern->scope = NULL;
}
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
}
zend_object* php_phongo_javascript_create_object(zend_class_entry* class_type)
{
php_phongo_javascript_t* intern = zend_object_alloc(sizeof(php_phongo_javascript_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_javascript;
return &intern->std;
}
static zend_object* php_phongo_javascript_clone_object(zend_object* object)
{
php_phongo_javascript_t* intern;
php_phongo_javascript_t* new_intern;
zend_object* new_object;
intern = Z_OBJ_JAVASCRIPT(object);
new_object = php_phongo_javascript_create_object(object->ce);
new_intern = Z_OBJ_JAVASCRIPT(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
php_phongo_javascript_init(new_intern, intern->code, intern->code_len, NULL);
new_intern->scope = bson_copy(intern->scope);
return new_object;
}
static int php_phongo_javascript_compare_objects(zval* o1, zval* o2)
{
php_phongo_javascript_t *intern1, *intern2;
ZEND_COMPARE_OBJECTS_FALLBACK(o1, o2);
intern1 = Z_JAVASCRIPT_OBJ_P(o1);
intern2 = Z_JAVASCRIPT_OBJ_P(o2);
/* Do not consider the scope document for comparisons */
return strcmp(intern1->code, intern2->code);
}
static HashTable* php_phongo_javascript_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return php_phongo_javascript_get_properties_hash(object, true);
}
static HashTable* php_phongo_javascript_get_properties(zend_object* object)
{
return php_phongo_javascript_get_properties_hash(object, false);
}
void php_phongo_javascript_init_ce(INIT_FUNC_ARGS)
{
php_phongo_javascript_ce = register_class_MongoDB_BSON_Javascript(php_phongo_javascript_interface_ce, php_phongo_json_serializable_ce, php_phongo_type_ce, zend_ce_stringable);
php_phongo_javascript_ce->create_object = php_phongo_javascript_create_object;
memcpy(&php_phongo_handler_javascript, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_javascript.compare = php_phongo_javascript_compare_objects;
php_phongo_handler_javascript.clone_obj = php_phongo_javascript_clone_object;
php_phongo_handler_javascript.get_debug_info = php_phongo_javascript_get_debug_info;
php_phongo_handler_javascript.get_properties = php_phongo_javascript_get_properties;
php_phongo_handler_javascript.free_obj = php_phongo_javascript_free_object;
php_phongo_handler_javascript.offset = XtOffsetOf(php_phongo_javascript_t, std);
}
bool phongo_javascript_new(zval* object, const char* code, size_t code_len, const bson_t* scope)
{
php_phongo_javascript_t* intern;
if (scope) {
php_phongo_bson_state state;
bool valid_scope;
PHONGO_BSON_INIT_STATE(state);
valid_scope = php_phongo_bson_to_zval_ex(scope, &state);
zval_ptr_dtor(&state.zchild);
if (!valid_scope) {
return false;
}
}
object_init_ex(object, php_phongo_javascript_ce);
intern = Z_JAVASCRIPT_OBJ_P(object);
intern->code = estrndup(code, code_len);
intern->code_len = code_len;
intern->scope = scope ? bson_copy(scope) : NULL;
return true;
}
mongodb-2.1.0/src/BSON/Javascript.h 0000644 0001751 0000166 00000001450 15014033047 013664 0 ustar /*
* Copyright 2023-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_BSON_JAVASCRIPT_H
#define PHONGO_BSON_JAVASCRIPT_H
bool phongo_javascript_new(zval* object, const char* code, size_t code_len, const bson_t* scope);
#endif /* PHONGO_BSON_JAVASCRIPT_H */
mongodb-2.1.0/src/BSON/JavascriptInterface.c 0000644 0001751 0000166 00000001601 15014033047 015476 0 ustar /*
* Copyright 2017-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "JavascriptInterface_arginfo.h"
zend_class_entry* php_phongo_javascript_interface_ce;
void php_phongo_javascript_interface_init_ce(INIT_FUNC_ARGS)
{
php_phongo_javascript_interface_ce = register_class_MongoDB_BSON_JavascriptInterface();
}
mongodb-2.1.0/src/BSON/JavascriptInterface_arginfo.h 0000644 0001751 0000166 00000002627 15014033047 017221 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: d2335273fc900e95ba3ce8731fa241792beeec88 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_JavascriptInterface_getCode, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_JavascriptInterface_getScope, 0, 0, IS_OBJECT, 1)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_BSON_JavascriptInterface___toString arginfo_class_MongoDB_BSON_JavascriptInterface_getCode
static const zend_function_entry class_MongoDB_BSON_JavascriptInterface_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_BSON_JavascriptInterface, getCode, arginfo_class_MongoDB_BSON_JavascriptInterface_getCode, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_BSON_JavascriptInterface, getScope, arginfo_class_MongoDB_BSON_JavascriptInterface_getScope, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_BSON_JavascriptInterface, __toString, arginfo_class_MongoDB_BSON_JavascriptInterface___toString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_JavascriptInterface(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "JavascriptInterface", class_MongoDB_BSON_JavascriptInterface_methods);
class_entry = zend_register_internal_interface(&ce);
return class_entry;
}
mongodb-2.1.0/src/BSON/Javascript_arginfo.h 0000644 0001751 0000166 00000007073 15014033047 015400 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 017421710f18d98547b7f987309bcd932a076245 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_BSON_Javascript___construct, 0, 0, 1)
ZEND_ARG_TYPE_INFO(0, code, IS_STRING, 0)
ZEND_ARG_TYPE_MASK(0, scope, MAY_BE_ARRAY|MAY_BE_OBJECT|MAY_BE_NULL, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_Javascript___set_state, 0, 1, MongoDB\\BSON\\Javascript, 0)
ZEND_ARG_TYPE_INFO(0, properties, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Javascript_getCode, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Javascript_getScope, 0, 0, IS_OBJECT, 1)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_BSON_Javascript___toString arginfo_class_MongoDB_BSON_Javascript_getCode
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Javascript___unserialize, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Javascript___serialize, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Javascript_jsonSerialize, 0, 0, IS_MIXED, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_BSON_Javascript, __construct);
static ZEND_METHOD(MongoDB_BSON_Javascript, __set_state);
static ZEND_METHOD(MongoDB_BSON_Javascript, getCode);
static ZEND_METHOD(MongoDB_BSON_Javascript, getScope);
static ZEND_METHOD(MongoDB_BSON_Javascript, __toString);
static ZEND_METHOD(MongoDB_BSON_Javascript, __unserialize);
static ZEND_METHOD(MongoDB_BSON_Javascript, __serialize);
static ZEND_METHOD(MongoDB_BSON_Javascript, jsonSerialize);
static const zend_function_entry class_MongoDB_BSON_Javascript_methods[] = {
ZEND_ME(MongoDB_BSON_Javascript, __construct, arginfo_class_MongoDB_BSON_Javascript___construct, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Javascript, __set_state, arginfo_class_MongoDB_BSON_Javascript___set_state, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Javascript, getCode, arginfo_class_MongoDB_BSON_Javascript_getCode, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Javascript, getScope, arginfo_class_MongoDB_BSON_Javascript_getScope, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Javascript, __toString, arginfo_class_MongoDB_BSON_Javascript___toString, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Javascript, __unserialize, arginfo_class_MongoDB_BSON_Javascript___unserialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Javascript, __serialize, arginfo_class_MongoDB_BSON_Javascript___serialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Javascript, jsonSerialize, arginfo_class_MongoDB_BSON_Javascript_jsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_Javascript(zend_class_entry *class_entry_MongoDB_BSON_JavascriptInterface, zend_class_entry *class_entry_JsonSerializable, zend_class_entry *class_entry_MongoDB_BSON_Type, zend_class_entry *class_entry_Stringable)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Javascript", class_MongoDB_BSON_Javascript_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
zend_class_implements(class_entry, 4, class_entry_MongoDB_BSON_JavascriptInterface, class_entry_JsonSerializable, class_entry_MongoDB_BSON_Type, class_entry_Stringable);
return class_entry;
}
mongodb-2.1.0/src/BSON/MaxKey.c 0000644 0001751 0000166 00000005255 15014033047 012756 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "MaxKey_arginfo.h"
zend_class_entry* php_phongo_maxkey_ce;
static PHP_METHOD(MongoDB_BSON_MaxKey, __set_state)
{
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
object_init_ex(return_value, php_phongo_maxkey_ce);
}
static PHP_METHOD(MongoDB_BSON_MaxKey, jsonSerialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
array_init_size(return_value, 1);
ADD_ASSOC_LONG_EX(return_value, "$maxKey", 1);
}
static PHP_METHOD(MongoDB_BSON_MaxKey, __serialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
array_init_size(return_value, 0);
}
static PHP_METHOD(MongoDB_BSON_MaxKey, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
}
/* MongoDB\BSON\MaxKey object handlers */
static zend_object_handlers php_phongo_handler_maxkey;
static void php_phongo_maxkey_free_object(zend_object* object)
{
php_phongo_maxkey_t* intern = Z_OBJ_MAXKEY(object);
zend_object_std_dtor(&intern->std);
}
static zend_object* php_phongo_maxkey_create_object(zend_class_entry* class_type)
{
php_phongo_maxkey_t* intern = zend_object_alloc(sizeof(php_phongo_maxkey_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_maxkey;
return &intern->std;
}
void php_phongo_maxkey_init_ce(INIT_FUNC_ARGS)
{
php_phongo_maxkey_ce = register_class_MongoDB_BSON_MaxKey(php_phongo_maxkey_interface_ce, php_phongo_json_serializable_ce, php_phongo_type_ce);
php_phongo_maxkey_ce->create_object = php_phongo_maxkey_create_object;
memcpy(&php_phongo_handler_maxkey, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
/* Re-assign default handler previously removed in php_phongo.c */
php_phongo_handler_maxkey.clone_obj = zend_objects_clone_obj;
php_phongo_handler_maxkey.free_obj = php_phongo_maxkey_free_object;
php_phongo_handler_maxkey.offset = XtOffsetOf(php_phongo_maxkey_t, std);
}
mongodb-2.1.0/src/BSON/MaxKeyInterface.c 0000644 0001751 0000166 00000001555 15014033047 014576 0 ustar /*
* Copyright 2017-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "MaxKeyInterface_arginfo.h"
zend_class_entry* php_phongo_maxkey_interface_ce;
void php_phongo_maxkey_interface_init_ce(INIT_FUNC_ARGS)
{
php_phongo_maxkey_interface_ce = register_class_MongoDB_BSON_MaxKeyInterface();
}
mongodb-2.1.0/src/BSON/MaxKeyInterface_arginfo.h 0000644 0001751 0000166 00000001011 15014033047 016273 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 6c27815fcc33b0b03365b6b24d4145d8621cf13d */
static const zend_function_entry class_MongoDB_BSON_MaxKeyInterface_methods[] = {
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_MaxKeyInterface(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "MaxKeyInterface", class_MongoDB_BSON_MaxKeyInterface_methods);
class_entry = zend_register_internal_interface(&ce);
return class_entry;
}
mongodb-2.1.0/src/BSON/MaxKey_arginfo.h 0000644 0001751 0000166 00000004173 15014033047 014466 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: df810b4d4876637e555a0e129e940acc5177b892 */
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_MaxKey___set_state, 0, 1, MongoDB\\BSON\\MaxKey, 0)
ZEND_ARG_TYPE_INFO(0, properties, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_MaxKey___unserialize, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_MaxKey___serialize, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_MaxKey_jsonSerialize, 0, 0, IS_MIXED, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_BSON_MaxKey, __set_state);
static ZEND_METHOD(MongoDB_BSON_MaxKey, __unserialize);
static ZEND_METHOD(MongoDB_BSON_MaxKey, __serialize);
static ZEND_METHOD(MongoDB_BSON_MaxKey, jsonSerialize);
static const zend_function_entry class_MongoDB_BSON_MaxKey_methods[] = {
ZEND_ME(MongoDB_BSON_MaxKey, __set_state, arginfo_class_MongoDB_BSON_MaxKey___set_state, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_MaxKey, __unserialize, arginfo_class_MongoDB_BSON_MaxKey___unserialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_MaxKey, __serialize, arginfo_class_MongoDB_BSON_MaxKey___serialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_MaxKey, jsonSerialize, arginfo_class_MongoDB_BSON_MaxKey_jsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_MaxKey(zend_class_entry *class_entry_MongoDB_BSON_MaxKeyInterface, zend_class_entry *class_entry_JsonSerializable, zend_class_entry *class_entry_MongoDB_BSON_Type)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "MaxKey", class_MongoDB_BSON_MaxKey_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
zend_class_implements(class_entry, 3, class_entry_MongoDB_BSON_MaxKeyInterface, class_entry_JsonSerializable, class_entry_MongoDB_BSON_Type);
return class_entry;
}
mongodb-2.1.0/src/BSON/MinKey.c 0000644 0001751 0000166 00000005255 15014033047 012754 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "MinKey_arginfo.h"
zend_class_entry* php_phongo_minkey_ce;
static PHP_METHOD(MongoDB_BSON_MinKey, __set_state)
{
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
object_init_ex(return_value, php_phongo_minkey_ce);
}
static PHP_METHOD(MongoDB_BSON_MinKey, jsonSerialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
array_init_size(return_value, 1);
ADD_ASSOC_LONG_EX(return_value, "$minKey", 1);
}
static PHP_METHOD(MongoDB_BSON_MinKey, __serialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
array_init_size(return_value, 0);
}
static PHP_METHOD(MongoDB_BSON_MinKey, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
}
/* MongoDB\BSON\MinKey object handlers */
static zend_object_handlers php_phongo_handler_minkey;
static void php_phongo_minkey_free_object(zend_object* object)
{
php_phongo_minkey_t* intern = Z_OBJ_MINKEY(object);
zend_object_std_dtor(&intern->std);
}
static zend_object* php_phongo_minkey_create_object(zend_class_entry* class_type)
{
php_phongo_minkey_t* intern = zend_object_alloc(sizeof(php_phongo_minkey_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_minkey;
return &intern->std;
}
void php_phongo_minkey_init_ce(INIT_FUNC_ARGS)
{
php_phongo_minkey_ce = register_class_MongoDB_BSON_MinKey(php_phongo_minkey_interface_ce, php_phongo_json_serializable_ce, php_phongo_type_ce);
php_phongo_minkey_ce->create_object = php_phongo_minkey_create_object;
memcpy(&php_phongo_handler_minkey, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
/* Re-assign default handler previously removed in php_phongo.c */
php_phongo_handler_minkey.clone_obj = zend_objects_clone_obj;
php_phongo_handler_minkey.free_obj = php_phongo_minkey_free_object;
php_phongo_handler_minkey.offset = XtOffsetOf(php_phongo_minkey_t, std);
}
mongodb-2.1.0/src/BSON/MinKeyInterface.c 0000644 0001751 0000166 00000001555 15014033047 014574 0 ustar /*
* Copyright 2017-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "MinKeyInterface_arginfo.h"
zend_class_entry* php_phongo_minkey_interface_ce;
void php_phongo_minkey_interface_init_ce(INIT_FUNC_ARGS)
{
php_phongo_minkey_interface_ce = register_class_MongoDB_BSON_MinKeyInterface();
}
mongodb-2.1.0/src/BSON/MinKeyInterface_arginfo.h 0000644 0001751 0000166 00000001011 15014033047 016271 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: c9b23e875d9dc9ebb0ed3391d88cb2458ed96407 */
static const zend_function_entry class_MongoDB_BSON_MinKeyInterface_methods[] = {
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_MinKeyInterface(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "MinKeyInterface", class_MongoDB_BSON_MinKeyInterface_methods);
class_entry = zend_register_internal_interface(&ce);
return class_entry;
}
mongodb-2.1.0/src/BSON/MinKey_arginfo.h 0000644 0001751 0000166 00000004173 15014033047 014464 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 75a01ebbfa05e7a9b38aa1bd1a0bef3e0a06637e */
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_MinKey___set_state, 0, 1, MongoDB\\BSON\\MinKey, 0)
ZEND_ARG_TYPE_INFO(0, properties, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_MinKey___unserialize, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_MinKey___serialize, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_MinKey_jsonSerialize, 0, 0, IS_MIXED, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_BSON_MinKey, __set_state);
static ZEND_METHOD(MongoDB_BSON_MinKey, __unserialize);
static ZEND_METHOD(MongoDB_BSON_MinKey, __serialize);
static ZEND_METHOD(MongoDB_BSON_MinKey, jsonSerialize);
static const zend_function_entry class_MongoDB_BSON_MinKey_methods[] = {
ZEND_ME(MongoDB_BSON_MinKey, __set_state, arginfo_class_MongoDB_BSON_MinKey___set_state, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_MinKey, __unserialize, arginfo_class_MongoDB_BSON_MinKey___unserialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_MinKey, __serialize, arginfo_class_MongoDB_BSON_MinKey___serialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_MinKey, jsonSerialize, arginfo_class_MongoDB_BSON_MinKey_jsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_MinKey(zend_class_entry *class_entry_MongoDB_BSON_MinKeyInterface, zend_class_entry *class_entry_JsonSerializable, zend_class_entry *class_entry_MongoDB_BSON_Type)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "MinKey", class_MongoDB_BSON_MinKey_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
zend_class_implements(class_entry, 3, class_entry_MongoDB_BSON_MinKeyInterface, class_entry_JsonSerializable, class_entry_MongoDB_BSON_Type);
return class_entry;
}
mongodb-2.1.0/src/BSON/ObjectId.c 0000644 0001751 0000166 00000017622 15014033047 013244 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bson/bson.h"
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "ObjectId_arginfo.h"
#define PHONGO_OID_SIZE sizeof(((php_phongo_objectid_t*) 0)->oid)
#define PHONGO_OID_LEN (PHONGO_OID_SIZE - 1)
zend_class_entry* php_phongo_objectid_ce;
/* Initialize the object with a generated value and return whether it was
* successful. */
static bool php_phongo_objectid_init(php_phongo_objectid_t* intern)
{
bson_oid_t oid;
intern->initialized = true;
bson_oid_init(&oid, NULL);
bson_oid_to_string(&oid, intern->oid);
return true;
}
/* Initialize the object from a hex string and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_objectid_init_from_hex_string(php_phongo_objectid_t* intern, const char* hex, size_t hex_len)
{
if (bson_oid_is_valid(hex, hex_len)) {
bson_oid_t oid;
bson_oid_init_from_string(&oid, hex);
bson_oid_to_string(&oid, intern->oid);
intern->initialized = true;
return true;
}
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Error parsing ObjectId string: %s", hex);
return false;
}
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_objectid_init_from_hash(php_phongo_objectid_t* intern, HashTable* props)
{
zval* z_oid;
z_oid = zend_hash_str_find(props, "oid", sizeof("oid") - 1);
if (z_oid && Z_TYPE_P(z_oid) == IS_STRING) {
return php_phongo_objectid_init_from_hex_string(intern, Z_STRVAL_P(z_oid), Z_STRLEN_P(z_oid));
}
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"oid\" string field", ZSTR_VAL(php_phongo_objectid_ce->name));
return false;
}
static HashTable* php_phongo_objectid_get_properties_hash(zend_object* object, bool is_temp)
{
php_phongo_objectid_t* intern;
HashTable* props;
intern = Z_OBJ_OBJECTID(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_temp, intern, props, 1);
if (!intern->initialized) {
return props;
}
{
zval zv;
ZVAL_STRING(&zv, intern->oid);
zend_hash_str_update(props, "oid", sizeof("oid") - 1, &zv);
}
return props;
}
/* Constructs a new BSON ObjectId type, optionally from a hex string. */
static PHP_METHOD(MongoDB_BSON_ObjectId, __construct)
{
php_phongo_objectid_t* intern;
char* id = NULL;
size_t id_len;
intern = Z_OBJECTID_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_STRING_OR_NULL(id, id_len)
PHONGO_PARSE_PARAMETERS_END();
if (id) {
php_phongo_objectid_init_from_hex_string(intern, id, id_len);
} else {
php_phongo_objectid_init(intern);
}
}
static PHP_METHOD(MongoDB_BSON_ObjectId, getTimestamp)
{
php_phongo_objectid_t* intern;
bson_oid_t tmp_oid;
intern = Z_OBJECTID_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
bson_oid_init_from_string(&tmp_oid, intern->oid);
RETVAL_LONG(bson_oid_get_time_t(&tmp_oid));
}
static PHP_METHOD(MongoDB_BSON_ObjectId, __set_state)
{
php_phongo_objectid_t* intern;
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
object_init_ex(return_value, php_phongo_objectid_ce);
intern = Z_OBJECTID_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_objectid_init_from_hash(intern, props);
}
static PHP_METHOD(MongoDB_BSON_ObjectId, __toString)
{
php_phongo_objectid_t* intern;
intern = Z_OBJECTID_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_STRINGL(intern->oid, PHONGO_OID_LEN);
}
static PHP_METHOD(MongoDB_BSON_ObjectId, jsonSerialize)
{
php_phongo_objectid_t* intern;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_OBJECTID_OBJ_P(getThis());
array_init_size(return_value, 1);
ADD_ASSOC_STRINGL(return_value, "$oid", intern->oid, PHONGO_OID_LEN);
}
static PHP_METHOD(MongoDB_BSON_ObjectId, __serialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_ARR(php_phongo_objectid_get_properties_hash(Z_OBJ_P(getThis()), true));
}
static PHP_METHOD(MongoDB_BSON_ObjectId, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_objectid_init_from_hash(Z_OBJECTID_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\ObjectId object handlers */
static zend_object_handlers php_phongo_handler_objectid;
static void php_phongo_objectid_free_object(zend_object* object)
{
php_phongo_objectid_t* intern = Z_OBJ_OBJECTID(object);
zend_object_std_dtor(&intern->std);
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
}
static zend_object* php_phongo_objectid_create_object(zend_class_entry* class_type)
{
php_phongo_objectid_t* intern = zend_object_alloc(sizeof(php_phongo_objectid_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_objectid;
return &intern->std;
}
static zend_object* php_phongo_objectid_clone_object(zend_object* object)
{
php_phongo_objectid_t* intern;
php_phongo_objectid_t* new_intern;
zend_object* new_object;
intern = Z_OBJ_OBJECTID(object);
new_object = php_phongo_objectid_create_object(object->ce);
new_intern = Z_OBJ_OBJECTID(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
// Use memcpy to copy bson value to avoid converting to string and back
memcpy(&new_intern->oid, &intern->oid, PHONGO_OID_SIZE);
new_intern->initialized = true;
return new_object;
}
static int php_phongo_objectid_compare_objects(zval* o1, zval* o2)
{
php_phongo_objectid_t* intern1;
php_phongo_objectid_t* intern2;
ZEND_COMPARE_OBJECTS_FALLBACK(o1, o2);
intern1 = Z_OBJECTID_OBJ_P(o1);
intern2 = Z_OBJECTID_OBJ_P(o2);
return strcmp(intern1->oid, intern2->oid);
}
static HashTable* php_phongo_objectid_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return php_phongo_objectid_get_properties_hash(object, true);
}
static HashTable* php_phongo_objectid_get_properties(zend_object* object)
{
return php_phongo_objectid_get_properties_hash(object, false);
}
void php_phongo_objectid_init_ce(INIT_FUNC_ARGS)
{
php_phongo_objectid_ce = register_class_MongoDB_BSON_ObjectId(php_phongo_objectid_interface_ce, php_phongo_json_serializable_ce, php_phongo_type_ce, zend_ce_stringable);
php_phongo_objectid_ce->create_object = php_phongo_objectid_create_object;
memcpy(&php_phongo_handler_objectid, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_objectid.compare = php_phongo_objectid_compare_objects;
php_phongo_handler_objectid.clone_obj = php_phongo_objectid_clone_object;
php_phongo_handler_objectid.get_debug_info = php_phongo_objectid_get_debug_info;
php_phongo_handler_objectid.get_properties = php_phongo_objectid_get_properties;
php_phongo_handler_objectid.free_obj = php_phongo_objectid_free_object;
php_phongo_handler_objectid.offset = XtOffsetOf(php_phongo_objectid_t, std);
}
bool phongo_objectid_new(zval* return_value, const bson_oid_t* oid)
{
php_phongo_objectid_t* intern;
object_init_ex(return_value, php_phongo_objectid_ce);
intern = Z_OBJECTID_OBJ_P(return_value);
bson_oid_to_string(oid, intern->oid);
intern->initialized = true;
return true;
}
mongodb-2.1.0/src/BSON/ObjectId.h 0000644 0001751 0000166 00000001457 15014033047 013250 0 ustar /*
* Copyright 2022-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_BSON_OBJECTID_H
#define PHONGO_BSON_OBJECTID_H
#include "bson/bson.h"
#include
bool phongo_objectid_new(zval* return_value, const bson_oid_t* oid);
#endif /* PHONGO_BSON_OBJECTID_H */
mongodb-2.1.0/src/BSON/ObjectIdInterface.c 0000644 0001751 0000166 00000001567 15014033047 015066 0 ustar /*
* Copyright 2017-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "ObjectIdInterface_arginfo.h"
zend_class_entry* php_phongo_objectid_interface_ce;
void php_phongo_objectid_interface_init_ce(INIT_FUNC_ARGS)
{
php_phongo_objectid_interface_ce = register_class_MongoDB_BSON_ObjectIdInterface();
}
mongodb-2.1.0/src/BSON/ObjectIdInterface_arginfo.h 0000644 0001751 0000166 00000002163 15014033047 016571 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 918396361a59962098b767437a61efe5fa2ab259 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_ObjectIdInterface_getTimestamp, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_ObjectIdInterface___toString, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
static const zend_function_entry class_MongoDB_BSON_ObjectIdInterface_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_BSON_ObjectIdInterface, getTimestamp, arginfo_class_MongoDB_BSON_ObjectIdInterface_getTimestamp, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_BSON_ObjectIdInterface, __toString, arginfo_class_MongoDB_BSON_ObjectIdInterface___toString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_ObjectIdInterface(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "ObjectIdInterface", class_MongoDB_BSON_ObjectIdInterface_methods);
class_entry = zend_register_internal_interface(&ce);
return class_entry;
}
mongodb-2.1.0/src/BSON/ObjectId_arginfo.h 0000644 0001751 0000166 00000006271 15014033047 014754 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: beb5fbef79a5e5c826c086ffbf912748dd15f19b */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_BSON_ObjectId___construct, 0, 0, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, id, IS_STRING, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_ObjectId_getTimestamp, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_ObjectId___toString, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_ObjectId___set_state, 0, 1, MongoDB\\BSON\\ObjectId, 0)
ZEND_ARG_TYPE_INFO(0, properties, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_ObjectId___unserialize, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_ObjectId___serialize, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_ObjectId_jsonSerialize, 0, 0, IS_MIXED, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_BSON_ObjectId, __construct);
static ZEND_METHOD(MongoDB_BSON_ObjectId, getTimestamp);
static ZEND_METHOD(MongoDB_BSON_ObjectId, __toString);
static ZEND_METHOD(MongoDB_BSON_ObjectId, __set_state);
static ZEND_METHOD(MongoDB_BSON_ObjectId, __unserialize);
static ZEND_METHOD(MongoDB_BSON_ObjectId, __serialize);
static ZEND_METHOD(MongoDB_BSON_ObjectId, jsonSerialize);
static const zend_function_entry class_MongoDB_BSON_ObjectId_methods[] = {
ZEND_ME(MongoDB_BSON_ObjectId, __construct, arginfo_class_MongoDB_BSON_ObjectId___construct, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_ObjectId, getTimestamp, arginfo_class_MongoDB_BSON_ObjectId_getTimestamp, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_ObjectId, __toString, arginfo_class_MongoDB_BSON_ObjectId___toString, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_ObjectId, __set_state, arginfo_class_MongoDB_BSON_ObjectId___set_state, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_ObjectId, __unserialize, arginfo_class_MongoDB_BSON_ObjectId___unserialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_ObjectId, __serialize, arginfo_class_MongoDB_BSON_ObjectId___serialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_ObjectId, jsonSerialize, arginfo_class_MongoDB_BSON_ObjectId_jsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_ObjectId(zend_class_entry *class_entry_MongoDB_BSON_ObjectIdInterface, zend_class_entry *class_entry_JsonSerializable, zend_class_entry *class_entry_MongoDB_BSON_Type, zend_class_entry *class_entry_Stringable)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "ObjectId", class_MongoDB_BSON_ObjectId_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
zend_class_implements(class_entry, 4, class_entry_MongoDB_BSON_ObjectIdInterface, class_entry_JsonSerializable, class_entry_MongoDB_BSON_Type, class_entry_Stringable);
return class_entry;
}
mongodb-2.1.0/src/BSON/PackedArray.c 0000644 0001751 0000166 00000040265 15014033047 013746 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include
#include
#include
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php_phongo.h"
#include "phongo_error.h"
#include "phongo_bson_encode.h"
#include "BSON/PackedArray_arginfo.h"
#include "BSON/Iterator.h"
zend_class_entry* php_phongo_packedarray_ce;
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_packedarray_init_from_hash(php_phongo_packedarray_t* intern, HashTable* props)
{
zval* data;
if ((data = zend_hash_str_find(props, "data", sizeof("data") - 1)) && Z_TYPE_P(data) == IS_STRING) {
zend_string* decoded = php_base64_decode_str(Z_STR_P(data));
intern->bson = bson_new_from_data((const uint8_t*) ZSTR_VAL(decoded), ZSTR_LEN(decoded));
zend_string_free(decoded);
if (intern->bson == NULL) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires valid BSON", ZSTR_VAL(php_phongo_packedarray_ce->name));
return false;
}
return true;
}
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"data\" string field", ZSTR_VAL(php_phongo_packedarray_ce->name));
return false;
}
static HashTable* php_phongo_packedarray_get_properties_hash(zend_object* object, bool is_temp, int size)
{
php_phongo_packedarray_t* intern;
HashTable* props;
intern = Z_OBJ_PACKEDARRAY(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_temp, intern, props, size);
if (!intern->bson) {
return props;
}
{
zval data;
ZVAL_STR(&data, php_base64_encode((const unsigned char*) bson_get_data(intern->bson), intern->bson->len));
zend_hash_str_update(props, "data", sizeof("data") - 1, &data);
}
return props;
}
static bool php_phongo_packedarray_to_json(zval* return_value, bson_json_mode_t mode, const bson_t* bson)
{
char* json = NULL;
size_t json_len;
bson_json_opts_t* opts = bson_json_opts_new(mode, BSON_MAX_LEN_UNLIMITED);
bool ret = false;
bson_json_opts_set_outermost_array(opts, true);
json = bson_as_json_with_opts(bson, &json_len, opts);
if (json) {
ZVAL_STRINGL(return_value, json, json_len);
bson_free(json);
ret = true;
} else {
ZVAL_UNDEF(return_value);
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "Could not convert BSON array to a JSON string");
}
bson_json_opts_destroy(opts);
return ret;
}
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_BSON_PackedArray)
static PHP_METHOD(MongoDB_BSON_PackedArray, fromJSON)
{
zval zv;
php_phongo_packedarray_t* intern;
zend_string* json;
bson_t* bson;
bson_error_t error;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STR(json)
PHONGO_PARSE_PARAMETERS_END();
bson = bson_new_from_json((const uint8_t*) ZSTR_VAL(json), ZSTR_LEN(json), &error);
if (!bson) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "%s", error.domain == BSON_ERROR_JSON ? error.message : "Error parsing JSON");
return;
}
// Check if BSON contains only numeric keys
if (!bson_empty(bson)) {
bson_iter_t iter;
uint32_t expected_key = 0;
char expected_key_str[11];
const char* key_str;
if (!bson_iter_init(&iter, bson)) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "Received invalid JSON array");
bson_destroy(bson);
return;
}
while (bson_iter_next(&iter)) {
key_str = bson_iter_key(&iter);
snprintf(expected_key_str, sizeof(expected_key_str), "%" PRIu32, expected_key);
if (strcmp(key_str, expected_key_str)) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "Received invalid JSON array: expected key %" PRIu32 ", but found \"%s\"", expected_key, key_str);
bson_destroy(bson);
return;
}
expected_key++;
}
}
object_init_ex(&zv, php_phongo_packedarray_ce);
intern = Z_PACKEDARRAY_OBJ_P(&zv);
intern->bson = bson;
RETURN_ZVAL(&zv, 1, 1);
}
static PHP_METHOD(MongoDB_BSON_PackedArray, fromPHP)
{
zval zv;
php_phongo_packedarray_t* intern;
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
if (!zend_array_is_list(Z_ARRVAL_P(data))) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected value to be a list, but given array is not");
return;
}
object_init_ex(&zv, php_phongo_packedarray_ce);
intern = Z_PACKEDARRAY_OBJ_P(&zv);
intern->bson = bson_new();
php_phongo_zval_to_bson(data, PHONGO_BSON_NONE, intern->bson, NULL);
RETURN_ZVAL(&zv, 1, 1);
}
static bool seek_iter_to_index(bson_iter_t* iter, zend_long index)
{
for (zend_long i = 0; i <= index; i++) {
if (!bson_iter_next(iter)) {
return false;
}
}
return true;
}
static bool php_phongo_packedarray_get(php_phongo_packedarray_t* intern, zend_long index, zval* return_value, bool null_if_missing)
{
bson_iter_t iter;
if (!bson_iter_init(&iter, intern->bson)) {
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Could not initialize BSON iterator");
return false;
}
if (!seek_iter_to_index(&iter, index)) {
if (null_if_missing) {
ZVAL_NULL(return_value);
return true;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Could not find index \"%d\" in BSON array", index);
return false;
}
phongo_bson_value_to_zval(bson_iter_value(&iter), return_value);
return true;
}
static PHP_METHOD(MongoDB_BSON_PackedArray, get)
{
php_phongo_packedarray_t* intern;
zend_long index;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_LONG(index)
PHONGO_PARSE_PARAMETERS_END();
intern = Z_PACKEDARRAY_OBJ_P(getThis());
if (!php_phongo_packedarray_get(intern, index, return_value, false)) {
// Exception already thrown
RETURN_NULL();
}
}
static PHP_METHOD(MongoDB_BSON_PackedArray, getIterator)
{
PHONGO_PARSE_PARAMETERS_NONE();
phongo_iterator_init(return_value, getThis());
}
static bool php_phongo_packedarray_has(php_phongo_packedarray_t* intern, zend_long index)
{
bson_iter_t iter;
if (!bson_iter_init(&iter, intern->bson)) {
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Could not initialize BSON iterator");
return false;
}
return seek_iter_to_index(&iter, index);
}
static PHP_METHOD(MongoDB_BSON_PackedArray, has)
{
php_phongo_packedarray_t* intern;
zend_long index;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_LONG(index)
PHONGO_PARSE_PARAMETERS_END();
intern = Z_PACKEDARRAY_OBJ_P(getThis());
RETURN_BOOL(php_phongo_packedarray_has(intern, index));
}
static PHP_METHOD(MongoDB_BSON_PackedArray, toCanonicalExtendedJSON)
{
php_phongo_packedarray_t* intern;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_PACKEDARRAY_OBJ_P(getThis());
php_phongo_packedarray_to_json(return_value, BSON_JSON_MODE_CANONICAL, intern->bson);
}
static PHP_METHOD(MongoDB_BSON_PackedArray, toRelaxedExtendedJSON)
{
php_phongo_packedarray_t* intern;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_PACKEDARRAY_OBJ_P(getThis());
php_phongo_packedarray_to_json(return_value, BSON_JSON_MODE_RELAXED, intern->bson);
}
static PHP_METHOD(MongoDB_BSON_PackedArray, toPHP)
{
php_phongo_packedarray_t* intern;
zval* typemap = NULL;
php_phongo_bson_state state;
PHONGO_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY(typemap)
PHONGO_PARSE_PARAMETERS_END();
PHONGO_BSON_INIT_STATE(state);
if (!php_phongo_bson_typemap_to_state(typemap, &state.map)) {
return;
}
intern = Z_PACKEDARRAY_OBJ_P(getThis());
state.is_visiting_array = true;
state.map.int64_as_object = true;
if (!php_phongo_bson_to_zval_ex(intern->bson, &state)) {
zval_ptr_dtor(&state.zchild);
php_phongo_bson_typemap_dtor(&state.map);
RETURN_NULL();
}
php_phongo_bson_typemap_dtor(&state.map);
RETURN_ZVAL(&state.zchild, 0, 1);
}
static PHP_METHOD(MongoDB_BSON_PackedArray, offsetExists)
{
php_phongo_packedarray_t* intern;
zval* key;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ZVAL(key)
PHONGO_PARSE_PARAMETERS_END();
intern = Z_PACKEDARRAY_OBJ_P(getThis());
if (Z_TYPE_P(key) != IS_LONG) {
RETURN_FALSE;
}
RETURN_BOOL(php_phongo_packedarray_has(intern, Z_LVAL_P(key)));
}
static PHP_METHOD(MongoDB_BSON_PackedArray, offsetGet)
{
php_phongo_packedarray_t* intern;
zval* key;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ZVAL(key)
PHONGO_PARSE_PARAMETERS_END();
intern = Z_PACKEDARRAY_OBJ_P(getThis());
if (Z_TYPE_P(key) != IS_LONG) {
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Could not find index of type \"%s\" in BSON array", zend_zval_type_name(key));
return;
}
// May throw, in which case we do nothing
php_phongo_packedarray_get(intern, Z_LVAL_P(key), return_value, false);
}
static PHP_METHOD(MongoDB_BSON_PackedArray, offsetSet)
{
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Cannot write to %s offset", ZSTR_VAL(php_phongo_packedarray_ce->name));
}
static PHP_METHOD(MongoDB_BSON_PackedArray, offsetUnset)
{
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Cannot unset %s offset", ZSTR_VAL(php_phongo_packedarray_ce->name));
}
static PHP_METHOD(MongoDB_BSON_PackedArray, __toString)
{
php_phongo_packedarray_t* intern;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_PACKEDARRAY_OBJ_P(getThis());
RETVAL_STRINGL((const char*) bson_get_data(intern->bson), intern->bson->len);
}
static PHP_METHOD(MongoDB_BSON_PackedArray, __set_state)
{
php_phongo_packedarray_t* intern;
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
object_init_ex(return_value, php_phongo_packedarray_ce);
intern = Z_PACKEDARRAY_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_packedarray_init_from_hash(intern, props);
}
static PHP_METHOD(MongoDB_BSON_PackedArray, __serialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_ARR(php_phongo_packedarray_get_properties_hash(Z_OBJ_P(getThis()), true, 1));
}
static PHP_METHOD(MongoDB_BSON_PackedArray, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_packedarray_init_from_hash(Z_PACKEDARRAY_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\PackedArray object handlers */
static zend_object_handlers php_phongo_handler_packedarray;
static void php_phongo_packedarray_free_object(zend_object* object)
{
php_phongo_packedarray_t* intern = Z_OBJ_PACKEDARRAY(object);
zend_object_std_dtor(&intern->std);
if (intern->bson) {
bson_destroy(intern->bson);
}
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
}
static zend_object* php_phongo_packedarray_create_object(zend_class_entry* class_type)
{
php_phongo_packedarray_t* intern = zend_object_alloc(sizeof(php_phongo_packedarray_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_packedarray;
return &intern->std;
}
static zend_object* php_phongo_packedarray_clone_object(zend_object* object)
{
php_phongo_packedarray_t* intern;
php_phongo_packedarray_t* new_intern;
zend_object* new_object;
intern = Z_OBJ_PACKEDARRAY(object);
new_object = php_phongo_packedarray_create_object(object->ce);
new_intern = Z_OBJ_PACKEDARRAY(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
new_intern->bson = bson_copy(intern->bson);
return new_object;
}
static int php_phongo_packedarray_compare_objects(zval* o1, zval* o2)
{
php_phongo_packedarray_t *intern1, *intern2;
ZEND_COMPARE_OBJECTS_FALLBACK(o1, o2);
intern1 = Z_PACKEDARRAY_OBJ_P(o1);
intern2 = Z_PACKEDARRAY_OBJ_P(o2);
return bson_compare(intern1->bson, intern2->bson);
}
static HashTable* php_phongo_packedarray_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_packedarray_t* intern;
HashTable* props;
*is_temp = 1;
intern = Z_OBJ_PACKEDARRAY(object);
/* This get_debug_info handler reports an additional property. This does not
* conflict with other uses of php_phongo_document_get_properties_hash since
* we always allocated a new HashTable with is_temp=true. */
props = php_phongo_packedarray_get_properties_hash(object, true, 2);
{
php_phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
state.is_visiting_array = true;
state.map.array.type = PHONGO_TYPEMAP_BSON;
state.map.document.type = PHONGO_TYPEMAP_BSON;
if (!php_phongo_bson_to_zval_ex(intern->bson, &state)) {
zval_ptr_dtor(&state.zchild);
goto failure;
}
zend_hash_str_update(props, "value", sizeof("value") - 1, &state.zchild);
}
return props;
failure:
PHONGO_GET_PROPERTY_HASH_FREE_PROPS(is_temp, props);
return NULL;
}
static HashTable* php_phongo_packedarray_get_properties(zend_object* object)
{
return php_phongo_packedarray_get_properties_hash(object, false, 1);
}
zval* php_phongo_packedarray_read_dimension(zend_object* object, zval* offset, int type, zval* rv)
{
php_phongo_packedarray_t* intern;
intern = Z_OBJ_PACKEDARRAY(object);
if (Z_TYPE_P(offset) != IS_LONG) {
if (type == BP_VAR_IS) {
ZVAL_NULL(rv);
return rv;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Could not find index of type \"%s\" in BSON array", zend_zval_type_name(offset));
return &EG(uninitialized_zval);
}
if (!php_phongo_packedarray_get(intern, Z_LVAL_P(offset), rv, type == BP_VAR_IS)) {
// Exception already thrown
return &EG(uninitialized_zval);
}
return rv;
}
void php_phongo_packedarray_write_dimension(zend_object* object, zval* offset, zval* value)
{
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Cannot write to %s offset", ZSTR_VAL(php_phongo_packedarray_ce->name));
}
int php_phongo_packedarray_has_dimension(zend_object* object, zval* member, int check_empty)
{
php_phongo_packedarray_t* intern;
intern = Z_OBJ_PACKEDARRAY(object);
if (Z_TYPE_P(member) != IS_LONG) {
return false;
}
return php_phongo_packedarray_has(intern, Z_LVAL_P(member));
}
void php_phongo_packedarray_unset_dimension(zend_object* object, zval* offset)
{
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Cannot unset %s offset", ZSTR_VAL(php_phongo_packedarray_ce->name));
}
void php_phongo_packedarray_init_ce(INIT_FUNC_ARGS)
{
php_phongo_packedarray_ce = register_class_MongoDB_BSON_PackedArray(zend_ce_aggregate, zend_ce_arrayaccess, php_phongo_type_ce, zend_ce_stringable);
php_phongo_packedarray_ce->create_object = php_phongo_packedarray_create_object;
memcpy(&php_phongo_handler_packedarray, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_packedarray.compare = php_phongo_packedarray_compare_objects;
php_phongo_handler_packedarray.clone_obj = php_phongo_packedarray_clone_object;
php_phongo_handler_packedarray.get_debug_info = php_phongo_packedarray_get_debug_info;
php_phongo_handler_packedarray.get_properties = php_phongo_packedarray_get_properties;
php_phongo_handler_packedarray.free_obj = php_phongo_packedarray_free_object;
php_phongo_handler_packedarray.read_dimension = php_phongo_packedarray_read_dimension;
php_phongo_handler_packedarray.write_dimension = php_phongo_packedarray_write_dimension;
php_phongo_handler_packedarray.has_dimension = php_phongo_packedarray_has_dimension;
php_phongo_handler_packedarray.unset_dimension = php_phongo_packedarray_unset_dimension;
php_phongo_handler_packedarray.offset = XtOffsetOf(php_phongo_packedarray_t, std);
}
bool phongo_packedarray_new(zval* object, bson_t* bson, bool copy)
{
php_phongo_packedarray_t* intern;
object_init_ex(object, php_phongo_packedarray_ce);
intern = Z_PACKEDARRAY_OBJ_P(object);
intern->bson = copy ? bson_copy(bson) : bson;
return true;
}
mongodb-2.1.0/src/BSON/PackedArray.h 0000644 0001751 0000166 00000001415 15014033047 013745 0 ustar /*
* Copyright 2023-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_BSON_PACKEDARRAY_H
#define PHONGO_BSON_PACKEDARRAY_H
bool phongo_packedarray_new(zval* object, bson_t* bson, bool copy);
#endif /* PHONGO_BSON_PACKEDARRAY_H */
mongodb-2.1.0/src/BSON/PackedArray_arginfo.h 0000644 0001751 0000166 00000015355 15014033047 015462 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 497915f5aa3a10fc5e4bf222c82cdcb5c891a1bd */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_BSON_PackedArray___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_PackedArray_fromJSON, 0, 1, MongoDB\\BSON\\PackedArray, 0)
ZEND_ARG_TYPE_INFO(0, json, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_PackedArray_fromPHP, 0, 1, MongoDB\\BSON\\PackedArray, 0)
ZEND_ARG_TYPE_INFO(0, value, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_PackedArray_get, 0, 1, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO(0, index, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_PackedArray_getIterator, 0, 0, MongoDB\\BSON\\Iterator, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_PackedArray_has, 0, 1, _IS_BOOL, 0)
ZEND_ARG_TYPE_INFO(0, index, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_class_MongoDB_BSON_PackedArray_toPHP, 0, 0, MAY_BE_ARRAY|MAY_BE_OBJECT)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, typeMap, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_PackedArray_toCanonicalExtendedJSON, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_BSON_PackedArray_toRelaxedExtendedJSON arginfo_class_MongoDB_BSON_PackedArray_toCanonicalExtendedJSON
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_PackedArray_offsetExists, 0, 1, _IS_BOOL, 0)
ZEND_ARG_TYPE_INFO(0, offset, IS_MIXED, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_PackedArray_offsetGet, 0, 1, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO(0, offset, IS_MIXED, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_PackedArray_offsetSet, 0, 2, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, offset, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO(0, value, IS_MIXED, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_PackedArray_offsetUnset, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, offset, IS_MIXED, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_BSON_PackedArray___toString arginfo_class_MongoDB_BSON_PackedArray_toCanonicalExtendedJSON
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_PackedArray___set_state, 0, 1, MongoDB\\BSON\\PackedArray, 0)
ZEND_ARG_TYPE_INFO(0, properties, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_PackedArray___unserialize, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_PackedArray___serialize, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_BSON_PackedArray, __construct);
static ZEND_METHOD(MongoDB_BSON_PackedArray, fromJSON);
static ZEND_METHOD(MongoDB_BSON_PackedArray, fromPHP);
static ZEND_METHOD(MongoDB_BSON_PackedArray, get);
static ZEND_METHOD(MongoDB_BSON_PackedArray, getIterator);
static ZEND_METHOD(MongoDB_BSON_PackedArray, has);
static ZEND_METHOD(MongoDB_BSON_PackedArray, toPHP);
static ZEND_METHOD(MongoDB_BSON_PackedArray, toCanonicalExtendedJSON);
static ZEND_METHOD(MongoDB_BSON_PackedArray, toRelaxedExtendedJSON);
static ZEND_METHOD(MongoDB_BSON_PackedArray, offsetExists);
static ZEND_METHOD(MongoDB_BSON_PackedArray, offsetGet);
static ZEND_METHOD(MongoDB_BSON_PackedArray, offsetSet);
static ZEND_METHOD(MongoDB_BSON_PackedArray, offsetUnset);
static ZEND_METHOD(MongoDB_BSON_PackedArray, __toString);
static ZEND_METHOD(MongoDB_BSON_PackedArray, __set_state);
static ZEND_METHOD(MongoDB_BSON_PackedArray, __unserialize);
static ZEND_METHOD(MongoDB_BSON_PackedArray, __serialize);
static const zend_function_entry class_MongoDB_BSON_PackedArray_methods[] = {
ZEND_ME(MongoDB_BSON_PackedArray, __construct, arginfo_class_MongoDB_BSON_PackedArray___construct, ZEND_ACC_PRIVATE)
ZEND_ME(MongoDB_BSON_PackedArray, fromJSON, arginfo_class_MongoDB_BSON_PackedArray_fromJSON, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_PackedArray, fromPHP, arginfo_class_MongoDB_BSON_PackedArray_fromPHP, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_PackedArray, get, arginfo_class_MongoDB_BSON_PackedArray_get, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_PackedArray, getIterator, arginfo_class_MongoDB_BSON_PackedArray_getIterator, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_PackedArray, has, arginfo_class_MongoDB_BSON_PackedArray_has, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_PackedArray, toPHP, arginfo_class_MongoDB_BSON_PackedArray_toPHP, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_PackedArray, toCanonicalExtendedJSON, arginfo_class_MongoDB_BSON_PackedArray_toCanonicalExtendedJSON, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_PackedArray, toRelaxedExtendedJSON, arginfo_class_MongoDB_BSON_PackedArray_toRelaxedExtendedJSON, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_PackedArray, offsetExists, arginfo_class_MongoDB_BSON_PackedArray_offsetExists, ZEND_ACC_PUBLIC)
ZEND_ME(MongoDB_BSON_PackedArray, offsetGet, arginfo_class_MongoDB_BSON_PackedArray_offsetGet, ZEND_ACC_PUBLIC)
ZEND_ME(MongoDB_BSON_PackedArray, offsetSet, arginfo_class_MongoDB_BSON_PackedArray_offsetSet, ZEND_ACC_PUBLIC)
ZEND_ME(MongoDB_BSON_PackedArray, offsetUnset, arginfo_class_MongoDB_BSON_PackedArray_offsetUnset, ZEND_ACC_PUBLIC)
ZEND_ME(MongoDB_BSON_PackedArray, __toString, arginfo_class_MongoDB_BSON_PackedArray___toString, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_PackedArray, __set_state, arginfo_class_MongoDB_BSON_PackedArray___set_state, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_PackedArray, __unserialize, arginfo_class_MongoDB_BSON_PackedArray___unserialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_PackedArray, __serialize, arginfo_class_MongoDB_BSON_PackedArray___serialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_PackedArray(zend_class_entry *class_entry_IteratorAggregate, zend_class_entry *class_entry_ArrayAccess, zend_class_entry *class_entry_MongoDB_BSON_Type, zend_class_entry *class_entry_Stringable)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "PackedArray", class_MongoDB_BSON_PackedArray_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
zend_class_implements(class_entry, 4, class_entry_IteratorAggregate, class_entry_ArrayAccess, class_entry_MongoDB_BSON_Type, class_entry_Stringable);
return class_entry;
}
mongodb-2.1.0/src/BSON/Persistable.c 0000644 0001751 0000166 00000002513 15014033047 014027 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "Persistable_arginfo.h"
zend_class_entry* php_phongo_persistable_ce;
static int php_phongo_implement_persistable(zend_class_entry* interface, zend_class_entry* class_type)
{
if (class_type->ce_flags & ZEND_ACC_ENUM) {
zend_error_noreturn(E_ERROR, "Enum class %s cannot implement interface %s", ZSTR_VAL(class_type->name), ZSTR_VAL(interface->name));
return FAILURE;
}
return SUCCESS;
}
void php_phongo_persistable_init_ce(INIT_FUNC_ARGS)
{
php_phongo_persistable_ce = register_class_MongoDB_BSON_Persistable(php_phongo_serializable_ce, php_phongo_unserializable_ce);
php_phongo_persistable_ce->interface_gets_implemented = php_phongo_implement_persistable;
}
mongodb-2.1.0/src/BSON/Persistable_arginfo.h 0000644 0001751 0000166 00000002053 15014033047 015540 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 8a5634034ae5939cd0c182b80243b246e8bd8558 */
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_TYPE_MASK_EX(arginfo_class_MongoDB_BSON_Persistable_bsonSerialize, 0, 0, stdClass|MongoDB\\BSON\\Document, MAY_BE_ARRAY)
ZEND_END_ARG_INFO()
static const zend_function_entry class_MongoDB_BSON_Persistable_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_BSON_Persistable, bsonSerialize, arginfo_class_MongoDB_BSON_Persistable_bsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_Persistable(zend_class_entry *class_entry_MongoDB_BSON_Serializable, zend_class_entry *class_entry_MongoDB_BSON_Unserializable)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Persistable", class_MongoDB_BSON_Persistable_methods);
class_entry = zend_register_internal_interface(&ce);
zend_class_implements(class_entry, 2, class_entry_MongoDB_BSON_Serializable, class_entry_MongoDB_BSON_Unserializable);
return class_entry;
}
mongodb-2.1.0/src/BSON/Regex.c 0000644 0001751 0000166 00000022132 15014033047 012623 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "Regex_arginfo.h"
zend_class_entry* php_phongo_regex_ce;
/* qsort() compare callback for alphabetizing regex flags upon initialization */
static int php_phongo_regex_compare_flags(const void* f1, const void* f2)
{
if (*(const char*) f1 == *(const char*) f2) {
return 0;
}
return (*(const char*) f1 > *(const char*) f2) ? 1 : -1;
}
/* Initialize the object and return whether it was successful. An exception will
* be thrown on error. */
static bool php_phongo_regex_init(php_phongo_regex_t* intern, const char* pattern, size_t pattern_len, const char* flags, size_t flags_len)
{
if (strlen(pattern) != (size_t) pattern_len) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Pattern cannot contain null bytes");
return false;
}
intern->pattern = estrndup(pattern, pattern_len);
intern->pattern_len = pattern_len;
if (flags) {
if (strlen(flags) != (size_t) flags_len) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Flags cannot contain null bytes");
return false;
}
intern->flags = estrndup(flags, flags_len);
intern->flags_len = flags_len;
/* Ensure flags are alphabetized upon initialization */
qsort((void*) intern->flags, flags_len, 1, php_phongo_regex_compare_flags);
} else {
intern->flags = estrdup("");
intern->flags_len = 0;
}
return true;
}
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_regex_init_from_hash(php_phongo_regex_t* intern, HashTable* props)
{
zval *pattern, *flags;
if ((pattern = zend_hash_str_find(props, "pattern", sizeof("pattern") - 1)) && Z_TYPE_P(pattern) == IS_STRING &&
(flags = zend_hash_str_find(props, "flags", sizeof("flags") - 1)) && Z_TYPE_P(flags) == IS_STRING) {
return php_phongo_regex_init(intern, Z_STRVAL_P(pattern), Z_STRLEN_P(pattern), Z_STRVAL_P(flags), Z_STRLEN_P(flags));
}
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"pattern\" and \"flags\" string fields", ZSTR_VAL(php_phongo_regex_ce->name));
return false;
}
static HashTable* php_phongo_regex_get_properties_hash(zend_object* object, bool is_temp)
{
php_phongo_regex_t* intern;
HashTable* props;
intern = Z_OBJ_REGEX(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_temp, intern, props, 2);
if (!intern->pattern) {
return props;
}
{
zval pattern, flags;
ZVAL_STRINGL(&pattern, intern->pattern, intern->pattern_len);
zend_hash_str_update(props, "pattern", sizeof("pattern") - 1, &pattern);
ZVAL_STRINGL(&flags, intern->flags, intern->flags_len);
zend_hash_str_update(props, "flags", sizeof("flags") - 1, &flags);
}
return props;
}
/* Constructs a new BSON regular expression type. */
static PHP_METHOD(MongoDB_BSON_Regex, __construct)
{
php_phongo_regex_t* intern;
char* pattern;
size_t pattern_len;
char* flags = NULL;
size_t flags_len = 0;
intern = Z_REGEX_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_STRING(pattern, pattern_len)
Z_PARAM_OPTIONAL
Z_PARAM_STRING(flags, flags_len)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_regex_init(intern, pattern, pattern_len, flags, flags_len);
}
static PHP_METHOD(MongoDB_BSON_Regex, getPattern)
{
php_phongo_regex_t* intern;
intern = Z_REGEX_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_STRINGL(intern->pattern, intern->pattern_len);
}
static PHP_METHOD(MongoDB_BSON_Regex, getFlags)
{
php_phongo_regex_t* intern;
intern = Z_REGEX_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_STRINGL(intern->flags, intern->flags_len);
}
static PHP_METHOD(MongoDB_BSON_Regex, __set_state)
{
php_phongo_regex_t* intern;
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
object_init_ex(return_value, php_phongo_regex_ce);
intern = Z_REGEX_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_regex_init_from_hash(intern, props);
}
/* Returns a string in the form: /pattern/flags */
static PHP_METHOD(MongoDB_BSON_Regex, __toString)
{
php_phongo_regex_t* intern;
char* regex;
int regex_len;
intern = Z_REGEX_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
regex_len = spprintf(®ex, 0, "/%s/%s", intern->pattern, intern->flags);
RETVAL_STRINGL(regex, regex_len);
efree(regex);
}
static PHP_METHOD(MongoDB_BSON_Regex, jsonSerialize)
{
php_phongo_regex_t* intern;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_REGEX_OBJ_P(getThis());
array_init_size(return_value, 2);
ADD_ASSOC_STRINGL(return_value, "$regex", intern->pattern, intern->pattern_len);
ADD_ASSOC_STRINGL(return_value, "$options", intern->flags, intern->flags_len);
}
static PHP_METHOD(MongoDB_BSON_Regex, __serialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_ARR(php_phongo_regex_get_properties_hash(Z_OBJ_P(getThis()), true));
}
static PHP_METHOD(MongoDB_BSON_Regex, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_regex_init_from_hash(Z_REGEX_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\Regex object handlers */
static zend_object_handlers php_phongo_handler_regex;
static void php_phongo_regex_free_object(zend_object* object)
{
php_phongo_regex_t* intern = Z_OBJ_REGEX(object);
zend_object_std_dtor(&intern->std);
if (intern->pattern) {
efree(intern->pattern);
}
if (intern->flags) {
efree(intern->flags);
}
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
}
static zend_object* php_phongo_regex_create_object(zend_class_entry* class_type)
{
php_phongo_regex_t* intern = zend_object_alloc(sizeof(php_phongo_regex_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_regex;
return &intern->std;
}
static zend_object* php_phongo_regex_clone_object(zend_object* object)
{
php_phongo_regex_t* intern;
php_phongo_regex_t* new_intern;
zend_object* new_object;
intern = Z_OBJ_REGEX(object);
new_object = php_phongo_regex_create_object(object->ce);
new_intern = Z_OBJ_REGEX(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
php_phongo_regex_init(new_intern, intern->pattern, intern->pattern_len, intern->flags, intern->flags_len);
return new_object;
}
static int php_phongo_regex_compare_objects(zval* o1, zval* o2)
{
php_phongo_regex_t *intern1, *intern2;
int retval;
ZEND_COMPARE_OBJECTS_FALLBACK(o1, o2);
intern1 = Z_REGEX_OBJ_P(o1);
intern2 = Z_REGEX_OBJ_P(o2);
/* MongoDB compares the pattern string before the flags. */
retval = strcmp(intern1->pattern, intern2->pattern);
if (retval != 0) {
return retval;
}
return strcmp(intern1->flags, intern2->flags);
}
static HashTable* php_phongo_regex_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return php_phongo_regex_get_properties_hash(object, true);
}
static HashTable* php_phongo_regex_get_properties(zend_object* object)
{
return php_phongo_regex_get_properties_hash(object, false);
}
void php_phongo_regex_init_ce(INIT_FUNC_ARGS)
{
php_phongo_regex_ce = register_class_MongoDB_BSON_Regex(php_phongo_regex_interface_ce, php_phongo_json_serializable_ce, php_phongo_type_ce, zend_ce_stringable);
php_phongo_regex_ce->create_object = php_phongo_regex_create_object;
memcpy(&php_phongo_handler_regex, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_regex.compare = php_phongo_regex_compare_objects;
php_phongo_handler_regex.clone_obj = php_phongo_regex_clone_object;
php_phongo_handler_regex.get_debug_info = php_phongo_regex_get_debug_info;
php_phongo_handler_regex.get_properties = php_phongo_regex_get_properties;
php_phongo_handler_regex.free_obj = php_phongo_regex_free_object;
php_phongo_handler_regex.offset = XtOffsetOf(php_phongo_regex_t, std);
}
bool phongo_regex_new(zval* object, const char* pattern, const char* flags)
{
php_phongo_regex_t* intern;
object_init_ex(object, php_phongo_regex_ce);
intern = Z_REGEX_OBJ_P(object);
intern->pattern_len = strlen(pattern);
intern->pattern = estrndup(pattern, intern->pattern_len);
intern->flags_len = strlen(flags);
intern->flags = estrndup(flags, intern->flags_len);
return true;
}
mongodb-2.1.0/src/BSON/Regex.h 0000644 0001751 0000166 00000001404 15014033047 012627 0 ustar /*
* Copyright 2023-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_BSON_REGEX_H
#define PHONGO_BSON_REGEX_H
bool phongo_regex_new(zval* object, const char* pattern, const char* flags);
#endif /* PHONGO_BSON_REGEX_H */
mongodb-2.1.0/src/BSON/RegexInterface.c 0000644 0001751 0000166 00000001550 15014033047 014445 0 ustar /*
* Copyright 2017-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "RegexInterface_arginfo.h"
zend_class_entry* php_phongo_regex_interface_ce;
void php_phongo_regex_interface_init_ce(INIT_FUNC_ARGS)
{
php_phongo_regex_interface_ce = register_class_MongoDB_BSON_RegexInterface();
}
mongodb-2.1.0/src/BSON/RegexInterface_arginfo.h 0000644 0001751 0000166 00000002511 15014033047 016155 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 3d2702dde50173adc1d9b3c69257814256f26173 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_RegexInterface_getPattern, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_BSON_RegexInterface_getFlags arginfo_class_MongoDB_BSON_RegexInterface_getPattern
#define arginfo_class_MongoDB_BSON_RegexInterface___toString arginfo_class_MongoDB_BSON_RegexInterface_getPattern
static const zend_function_entry class_MongoDB_BSON_RegexInterface_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_BSON_RegexInterface, getPattern, arginfo_class_MongoDB_BSON_RegexInterface_getPattern, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_BSON_RegexInterface, getFlags, arginfo_class_MongoDB_BSON_RegexInterface_getFlags, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_BSON_RegexInterface, __toString, arginfo_class_MongoDB_BSON_RegexInterface___toString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_RegexInterface(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "RegexInterface", class_MongoDB_BSON_RegexInterface_methods);
class_entry = zend_register_internal_interface(&ce);
return class_entry;
}
mongodb-2.1.0/src/BSON/Regex_arginfo.h 0000644 0001751 0000166 00000006541 15014033047 014343 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 5fb63bbe527f9b0cadf1898ac21e97bbba8dbb6c */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_BSON_Regex___construct, 0, 0, 1)
ZEND_ARG_TYPE_INFO(0, pattern, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, flags, IS_STRING, 0, "\'\'")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Regex_getPattern, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_BSON_Regex_getFlags arginfo_class_MongoDB_BSON_Regex_getPattern
#define arginfo_class_MongoDB_BSON_Regex___toString arginfo_class_MongoDB_BSON_Regex_getPattern
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_Regex___set_state, 0, 1, MongoDB\\BSON\\Regex, 0)
ZEND_ARG_TYPE_INFO(0, properties, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Regex___unserialize, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Regex___serialize, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Regex_jsonSerialize, 0, 0, IS_MIXED, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_BSON_Regex, __construct);
static ZEND_METHOD(MongoDB_BSON_Regex, getPattern);
static ZEND_METHOD(MongoDB_BSON_Regex, getFlags);
static ZEND_METHOD(MongoDB_BSON_Regex, __toString);
static ZEND_METHOD(MongoDB_BSON_Regex, __set_state);
static ZEND_METHOD(MongoDB_BSON_Regex, __unserialize);
static ZEND_METHOD(MongoDB_BSON_Regex, __serialize);
static ZEND_METHOD(MongoDB_BSON_Regex, jsonSerialize);
static const zend_function_entry class_MongoDB_BSON_Regex_methods[] = {
ZEND_ME(MongoDB_BSON_Regex, __construct, arginfo_class_MongoDB_BSON_Regex___construct, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Regex, getPattern, arginfo_class_MongoDB_BSON_Regex_getPattern, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Regex, getFlags, arginfo_class_MongoDB_BSON_Regex_getFlags, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Regex, __toString, arginfo_class_MongoDB_BSON_Regex___toString, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Regex, __set_state, arginfo_class_MongoDB_BSON_Regex___set_state, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Regex, __unserialize, arginfo_class_MongoDB_BSON_Regex___unserialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Regex, __serialize, arginfo_class_MongoDB_BSON_Regex___serialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Regex, jsonSerialize, arginfo_class_MongoDB_BSON_Regex_jsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_Regex(zend_class_entry *class_entry_MongoDB_BSON_RegexInterface, zend_class_entry *class_entry_JsonSerializable, zend_class_entry *class_entry_MongoDB_BSON_Type, zend_class_entry *class_entry_Stringable)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Regex", class_MongoDB_BSON_Regex_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
zend_class_implements(class_entry, 4, class_entry_MongoDB_BSON_RegexInterface, class_entry_JsonSerializable, class_entry_MongoDB_BSON_Type, class_entry_Stringable);
return class_entry;
}
mongodb-2.1.0/src/BSON/Serializable.c 0000644 0001751 0000166 00000001555 15014033047 014165 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "Serializable_arginfo.h"
zend_class_entry* php_phongo_serializable_ce;
void php_phongo_serializable_init_ce(INIT_FUNC_ARGS)
{
php_phongo_serializable_ce = register_class_MongoDB_BSON_Serializable(php_phongo_type_ce);
}
mongodb-2.1.0/src/BSON/Serializable_arginfo.h 0000644 0001751 0000166 00000001731 15014033047 015673 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 0d23d26a86f14abf19f9fb44b350a134534df5ac */
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_TYPE_MASK_EX(arginfo_class_MongoDB_BSON_Serializable_bsonSerialize, 0, 0, stdClass|MongoDB\\BSON\\Document|MongoDB\\BSON\\PackedArray, MAY_BE_ARRAY)
ZEND_END_ARG_INFO()
static const zend_function_entry class_MongoDB_BSON_Serializable_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_BSON_Serializable, bsonSerialize, arginfo_class_MongoDB_BSON_Serializable_bsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_Serializable(zend_class_entry *class_entry_MongoDB_BSON_Type)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Serializable", class_MongoDB_BSON_Serializable_methods);
class_entry = zend_register_internal_interface(&ce);
zend_class_implements(class_entry, 1, class_entry_MongoDB_BSON_Type);
return class_entry;
}
mongodb-2.1.0/src/BSON/Symbol.c 0000644 0001751 0000166 00000015005 15014033047 013017 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "Symbol_arginfo.h"
zend_class_entry* php_phongo_symbol_ce;
/* Initialize the object and return whether it was successful. An exception will
* be thrown on error. */
static bool php_phongo_symbol_init(php_phongo_symbol_t* intern, const char* symbol, size_t symbol_len)
{
if (strlen(symbol) != (size_t) symbol_len) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Symbol cannot contain null bytes");
return false;
}
intern->symbol = estrndup(symbol, symbol_len);
intern->symbol_len = symbol_len;
return true;
}
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_symbol_init_from_hash(php_phongo_symbol_t* intern, HashTable* props)
{
zval* symbol;
if ((symbol = zend_hash_str_find(props, "symbol", sizeof("symbol") - 1)) && Z_TYPE_P(symbol) == IS_STRING) {
return php_phongo_symbol_init(intern, Z_STRVAL_P(symbol), Z_STRLEN_P(symbol));
}
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"symbol\" string field", ZSTR_VAL(php_phongo_symbol_ce->name));
return false;
}
HashTable* php_phongo_symbol_get_properties_hash(zend_object* object, bool is_temp)
{
php_phongo_symbol_t* intern;
HashTable* props;
intern = Z_OBJ_SYMBOL(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_temp, intern, props, 2);
if (!intern->symbol) {
return props;
}
{
zval symbol;
ZVAL_STRING(&symbol, intern->symbol);
zend_hash_str_update(props, "symbol", sizeof("symbol") - 1, &symbol);
}
return props;
}
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_BSON_Symbol)
/* Return the Symbol's symbol string. */
static PHP_METHOD(MongoDB_BSON_Symbol, __toString)
{
php_phongo_symbol_t* intern;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_SYMBOL_OBJ_P(getThis());
RETURN_STRINGL(intern->symbol, intern->symbol_len);
}
static PHP_METHOD(MongoDB_BSON_Symbol, __set_state)
{
php_phongo_symbol_t* intern;
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
object_init_ex(return_value, php_phongo_symbol_ce);
intern = Z_SYMBOL_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_symbol_init_from_hash(intern, props);
}
static PHP_METHOD(MongoDB_BSON_Symbol, jsonSerialize)
{
php_phongo_symbol_t* intern;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_SYMBOL_OBJ_P(getThis());
array_init_size(return_value, 1);
ADD_ASSOC_STRINGL(return_value, "$symbol", intern->symbol, intern->symbol_len);
}
static PHP_METHOD(MongoDB_BSON_Symbol, __serialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
ZVAL_ARR(return_value, php_phongo_symbol_get_properties_hash(Z_OBJ_P(getThis()), true));
}
static PHP_METHOD(MongoDB_BSON_Symbol, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_symbol_init_from_hash(Z_SYMBOL_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\Symbol object handlers */
static zend_object_handlers php_phongo_handler_symbol;
static void php_phongo_symbol_free_object(zend_object* object)
{
php_phongo_symbol_t* intern = Z_OBJ_SYMBOL(object);
zend_object_std_dtor(&intern->std);
if (intern->symbol) {
efree(intern->symbol);
}
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
}
zend_object* php_phongo_symbol_create_object(zend_class_entry* class_type)
{
php_phongo_symbol_t* intern = zend_object_alloc(sizeof(php_phongo_symbol_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_symbol;
return &intern->std;
}
static zend_object* php_phongo_symbol_clone_object(zend_object* object)
{
php_phongo_symbol_t* intern;
php_phongo_symbol_t* new_intern;
zend_object* new_object;
intern = Z_OBJ_SYMBOL(object);
new_object = php_phongo_symbol_create_object(object->ce);
new_intern = Z_OBJ_SYMBOL(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
php_phongo_symbol_init(new_intern, intern->symbol, intern->symbol_len);
return new_object;
}
static int php_phongo_symbol_compare_objects(zval* o1, zval* o2)
{
php_phongo_symbol_t *intern1, *intern2;
ZEND_COMPARE_OBJECTS_FALLBACK(o1, o2);
intern1 = Z_SYMBOL_OBJ_P(o1);
intern2 = Z_SYMBOL_OBJ_P(o2);
return strcmp(intern1->symbol, intern2->symbol);
}
static HashTable* php_phongo_symbol_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return php_phongo_symbol_get_properties_hash(object, true);
}
static HashTable* php_phongo_symbol_get_properties(zend_object* object)
{
return php_phongo_symbol_get_properties_hash(object, false);
}
void php_phongo_symbol_init_ce(INIT_FUNC_ARGS)
{
php_phongo_symbol_ce = register_class_MongoDB_BSON_Symbol(php_phongo_json_serializable_ce, php_phongo_type_ce, zend_ce_stringable);
php_phongo_symbol_ce->create_object = php_phongo_symbol_create_object;
memcpy(&php_phongo_handler_symbol, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_symbol.compare = php_phongo_symbol_compare_objects;
php_phongo_handler_symbol.clone_obj = php_phongo_symbol_clone_object;
php_phongo_handler_symbol.get_debug_info = php_phongo_symbol_get_debug_info;
php_phongo_handler_symbol.get_properties = php_phongo_symbol_get_properties;
php_phongo_handler_symbol.free_obj = php_phongo_symbol_free_object;
php_phongo_handler_symbol.offset = XtOffsetOf(php_phongo_symbol_t, std);
}
bool phongo_symbol_new(zval* object, const char* symbol, size_t symbol_len)
{
php_phongo_symbol_t* intern;
object_init_ex(object, php_phongo_symbol_ce);
intern = Z_SYMBOL_OBJ_P(object);
intern->symbol = estrndup(symbol, symbol_len);
intern->symbol_len = symbol_len;
return true;
}
mongodb-2.1.0/src/BSON/Symbol.h 0000644 0001751 0000166 00000001407 15014033047 013025 0 ustar /*
* Copyright 2023-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_BSON_SYMBOL_H
#define PHONGO_BSON_SYMBOL_H
bool phongo_symbol_new(zval* object, const char* symbol, size_t symbol_len);
#endif /* PHONGO_BSON_SYMBOL_H */
mongodb-2.1.0/src/BSON/Symbol_arginfo.h 0000644 0001751 0000166 00000005230 15014033047 014530 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 9bd846827a2c2fb7fd6c0cb853a3fec5756073e8 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_BSON_Symbol___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Symbol___toString, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_Symbol___set_state, 0, 1, MongoDB\\BSON\\Symbol, 0)
ZEND_ARG_TYPE_INFO(0, properties, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Symbol___unserialize, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Symbol___serialize, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Symbol_jsonSerialize, 0, 0, IS_MIXED, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_BSON_Symbol, __construct);
static ZEND_METHOD(MongoDB_BSON_Symbol, __toString);
static ZEND_METHOD(MongoDB_BSON_Symbol, __set_state);
static ZEND_METHOD(MongoDB_BSON_Symbol, __unserialize);
static ZEND_METHOD(MongoDB_BSON_Symbol, __serialize);
static ZEND_METHOD(MongoDB_BSON_Symbol, jsonSerialize);
static const zend_function_entry class_MongoDB_BSON_Symbol_methods[] = {
ZEND_ME(MongoDB_BSON_Symbol, __construct, arginfo_class_MongoDB_BSON_Symbol___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Symbol, __toString, arginfo_class_MongoDB_BSON_Symbol___toString, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Symbol, __set_state, arginfo_class_MongoDB_BSON_Symbol___set_state, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Symbol, __unserialize, arginfo_class_MongoDB_BSON_Symbol___unserialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Symbol, __serialize, arginfo_class_MongoDB_BSON_Symbol___serialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Symbol, jsonSerialize, arginfo_class_MongoDB_BSON_Symbol_jsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_Symbol(zend_class_entry *class_entry_JsonSerializable, zend_class_entry *class_entry_MongoDB_BSON_Type, zend_class_entry *class_entry_Stringable)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Symbol", class_MongoDB_BSON_Symbol_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
zend_class_implements(class_entry, 3, class_entry_JsonSerializable, class_entry_MongoDB_BSON_Type, class_entry_Stringable);
return class_entry;
}
mongodb-2.1.0/src/BSON/Timestamp.c 0000644 0001751 0000166 00000026406 15014033047 013524 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "phongo_util.h"
#include "Timestamp_arginfo.h"
zend_class_entry* php_phongo_timestamp_ce;
/* Initialize the object and return whether it was successful. An exception will
* be thrown on error. */
static bool php_phongo_timestamp_init(php_phongo_timestamp_t* intern, int64_t increment, int64_t timestamp)
{
if (increment < 0 || increment > UINT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected increment to be an unsigned 32-bit integer, %" PRId64 " given", increment);
return false;
}
if (timestamp < 0 || timestamp > UINT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected timestamp to be an unsigned 32-bit integer, %" PRId64 " given", timestamp);
return false;
}
intern->increment = (uint32_t) increment;
intern->timestamp = (uint32_t) timestamp;
intern->initialized = true;
return true;
}
/* Initialize the object from numeric strings and return whether it was
* successful. An exception will be thrown on error. */
static bool php_phongo_timestamp_init_from_string(php_phongo_timestamp_t* intern, const char* s_increment, size_t s_increment_len, const char* s_timestamp, size_t s_timestamp_len)
{
int64_t increment, timestamp;
if (!php_phongo_parse_int64(&increment, s_increment, s_increment_len)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Error parsing \"%s\" as 64-bit integer increment for %s initialization", s_increment, ZSTR_VAL(php_phongo_timestamp_ce->name));
return false;
}
if (!php_phongo_parse_int64(×tamp, s_timestamp, s_timestamp_len)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Error parsing \"%s\" as 64-bit integer timestamp for %s initialization", s_timestamp, ZSTR_VAL(php_phongo_timestamp_ce->name));
return false;
}
return php_phongo_timestamp_init(intern, increment, timestamp);
}
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_timestamp_init_from_hash(php_phongo_timestamp_t* intern, HashTable* props)
{
zval *increment, *timestamp;
if ((increment = zend_hash_str_find(props, "increment", sizeof("increment") - 1)) && Z_TYPE_P(increment) == IS_LONG &&
(timestamp = zend_hash_str_find(props, "timestamp", sizeof("timestamp") - 1)) && Z_TYPE_P(timestamp) == IS_LONG) {
return php_phongo_timestamp_init(intern, Z_LVAL_P(increment), Z_LVAL_P(timestamp));
}
if ((increment = zend_hash_str_find(props, "increment", sizeof("increment") - 1)) && Z_TYPE_P(increment) == IS_STRING &&
(timestamp = zend_hash_str_find(props, "timestamp", sizeof("timestamp") - 1)) && Z_TYPE_P(timestamp) == IS_STRING) {
return php_phongo_timestamp_init_from_string(intern, Z_STRVAL_P(increment), Z_STRLEN_P(increment), Z_STRVAL_P(timestamp), Z_STRLEN_P(timestamp));
}
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"increment\" and \"timestamp\" integer or numeric string fields", ZSTR_VAL(php_phongo_timestamp_ce->name));
return false;
}
static HashTable* php_phongo_timestamp_get_properties_hash(zend_object* object, bool is_temp)
{
php_phongo_timestamp_t* intern;
HashTable* props;
char s_increment[24];
char s_timestamp[24];
int s_increment_len;
int s_timestamp_len;
intern = Z_OBJ_TIMESTAMP(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_temp, intern, props, 2);
if (!intern->initialized) {
return props;
}
s_increment_len = snprintf(s_increment, sizeof(s_increment), "%" PRIu32, intern->increment);
s_timestamp_len = snprintf(s_timestamp, sizeof(s_timestamp), "%" PRIu32, intern->timestamp);
{
zval increment, timestamp;
ZVAL_STRINGL(&increment, s_increment, s_increment_len);
zend_hash_str_update(props, "increment", sizeof("increment") - 1, &increment);
ZVAL_STRINGL(×tamp, s_timestamp, s_timestamp_len);
zend_hash_str_update(props, "timestamp", sizeof("timestamp") - 1, ×tamp);
}
return props;
}
/* Construct a new BSON timestamp type, which consists of a 4-byte increment and
4-byte timestamp. */
static PHP_METHOD(MongoDB_BSON_Timestamp, __construct)
{
php_phongo_timestamp_t* intern;
zval * increment = NULL, *timestamp = NULL;
intern = Z_TIMESTAMP_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_ZVAL(increment)
Z_PARAM_ZVAL(timestamp)
PHONGO_PARSE_PARAMETERS_END();
if (Z_TYPE_P(increment) == IS_LONG && Z_TYPE_P(timestamp) == IS_LONG) {
php_phongo_timestamp_init(intern, Z_LVAL_P(increment), Z_LVAL_P(timestamp));
return;
}
if (Z_TYPE_P(increment) == IS_LONG) {
convert_to_string(increment);
}
if (Z_TYPE_P(increment) != IS_STRING) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected increment to be an unsigned 32-bit integer or string, %s given", zend_zval_type_name(increment));
return;
}
if (Z_TYPE_P(timestamp) == IS_LONG) {
convert_to_string(timestamp);
}
if (Z_TYPE_P(timestamp) != IS_STRING) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected timestamp to be an unsigned 32-bit integer or string, %s given", zend_zval_type_name(timestamp));
return;
}
php_phongo_timestamp_init_from_string(intern, Z_STRVAL_P(increment), Z_STRLEN_P(increment), Z_STRVAL_P(timestamp), Z_STRLEN_P(timestamp));
}
static PHP_METHOD(MongoDB_BSON_Timestamp, getIncrement)
{
php_phongo_timestamp_t* intern;
intern = Z_TIMESTAMP_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_LONG(intern->increment);
}
static PHP_METHOD(MongoDB_BSON_Timestamp, getTimestamp)
{
php_phongo_timestamp_t* intern;
intern = Z_TIMESTAMP_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_LONG(intern->timestamp);
}
static PHP_METHOD(MongoDB_BSON_Timestamp, __set_state)
{
php_phongo_timestamp_t* intern;
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
object_init_ex(return_value, php_phongo_timestamp_ce);
intern = Z_TIMESTAMP_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_timestamp_init_from_hash(intern, props);
}
/* Returns a string in the form: [increment:timestamp] */
static PHP_METHOD(MongoDB_BSON_Timestamp, __toString)
{
php_phongo_timestamp_t* intern;
char* retval;
int retval_len;
intern = Z_TIMESTAMP_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
retval_len = spprintf(&retval, 0, "[%" PRIu32 ":%" PRIu32 "]", intern->increment, intern->timestamp);
RETVAL_STRINGL(retval, retval_len);
efree(retval);
}
static PHP_METHOD(MongoDB_BSON_Timestamp, jsonSerialize)
{
php_phongo_timestamp_t* intern;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_TIMESTAMP_OBJ_P(getThis());
array_init_size(return_value, 1);
{
zval ts;
array_init_size(&ts, 2);
ADD_ASSOC_LONG_EX(&ts, "t", intern->timestamp);
ADD_ASSOC_LONG_EX(&ts, "i", intern->increment);
ADD_ASSOC_ZVAL_EX(return_value, "$timestamp", &ts);
}
}
static PHP_METHOD(MongoDB_BSON_Timestamp, __serialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_ARR(php_phongo_timestamp_get_properties_hash(Z_OBJ_P(getThis()), true));
}
static PHP_METHOD(MongoDB_BSON_Timestamp, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_timestamp_init_from_hash(Z_TIMESTAMP_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\Timestamp object handlers */
static zend_object_handlers php_phongo_handler_timestamp;
static void php_phongo_timestamp_free_object(zend_object* object)
{
php_phongo_timestamp_t* intern = Z_OBJ_TIMESTAMP(object);
zend_object_std_dtor(&intern->std);
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
}
static zend_object* php_phongo_timestamp_create_object(zend_class_entry* class_type)
{
php_phongo_timestamp_t* intern = zend_object_alloc(sizeof(php_phongo_timestamp_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_timestamp;
return &intern->std;
}
static zend_object* php_phongo_timestamp_clone_object(zend_object* object)
{
php_phongo_timestamp_t* intern;
php_phongo_timestamp_t* new_intern;
zend_object* new_object;
intern = Z_OBJ_TIMESTAMP(object);
new_object = php_phongo_timestamp_create_object(object->ce);
new_intern = Z_OBJ_TIMESTAMP(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
php_phongo_timestamp_init(new_intern, intern->increment, intern->timestamp);
return new_object;
}
static int php_phongo_timestamp_compare_objects(zval* o1, zval* o2)
{
php_phongo_timestamp_t *intern1, *intern2;
ZEND_COMPARE_OBJECTS_FALLBACK(o1, o2);
intern1 = Z_TIMESTAMP_OBJ_P(o1);
intern2 = Z_TIMESTAMP_OBJ_P(o2);
/* MongoDB compares the timestamp before the increment. */
if (intern1->timestamp != intern2->timestamp) {
return intern1->timestamp < intern2->timestamp ? -1 : 1;
}
if (intern1->increment != intern2->increment) {
return intern1->increment < intern2->increment ? -1 : 1;
}
return 0;
}
static HashTable* php_phongo_timestamp_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return php_phongo_timestamp_get_properties_hash(object, true);
}
static HashTable* php_phongo_timestamp_get_properties(zend_object* object)
{
return php_phongo_timestamp_get_properties_hash(object, false);
}
void php_phongo_timestamp_init_ce(INIT_FUNC_ARGS)
{
php_phongo_timestamp_ce = register_class_MongoDB_BSON_Timestamp(php_phongo_timestamp_interface_ce, php_phongo_json_serializable_ce, php_phongo_type_ce, zend_ce_stringable);
php_phongo_timestamp_ce->create_object = php_phongo_timestamp_create_object;
memcpy(&php_phongo_handler_timestamp, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_timestamp.compare = php_phongo_timestamp_compare_objects;
php_phongo_handler_timestamp.clone_obj = php_phongo_timestamp_clone_object;
php_phongo_handler_timestamp.get_debug_info = php_phongo_timestamp_get_debug_info;
php_phongo_handler_timestamp.get_properties = php_phongo_timestamp_get_properties;
php_phongo_handler_timestamp.free_obj = php_phongo_timestamp_free_object;
php_phongo_handler_timestamp.offset = XtOffsetOf(php_phongo_timestamp_t, std);
}
bool phongo_timestamp_new(zval* object, uint32_t increment, uint32_t timestamp)
{
php_phongo_timestamp_t* intern;
object_init_ex(object, php_phongo_timestamp_ce);
intern = Z_TIMESTAMP_OBJ_P(object);
intern->increment = increment;
intern->timestamp = timestamp;
intern->initialized = true;
return true;
}
mongodb-2.1.0/src/BSON/Timestamp.h 0000644 0001751 0000166 00000001424 15014033047 013522 0 ustar /*
* Copyright 2023-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_BSON_TIMESTAMP_H
#define PHONGO_BSON_TIMESTAMP_H
bool phongo_timestamp_new(zval* object, uint32_t increment, uint32_t timestamp);
#endif /* PHONGO_BSON_TIMESTAMP_H */
mongodb-2.1.0/src/BSON/TimestampInterface.c 0000644 0001751 0000166 00000001574 15014033047 015344 0 ustar /*
* Copyright 2017-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "TimestampInterface_arginfo.h"
zend_class_entry* php_phongo_timestamp_interface_ce;
void php_phongo_timestamp_interface_init_ce(INIT_FUNC_ARGS)
{
php_phongo_timestamp_interface_ce = register_class_MongoDB_BSON_TimestampInterface();
}
mongodb-2.1.0/src/BSON/TimestampInterface_arginfo.h 0000644 0001751 0000166 00000002647 15014033047 017060 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 6943cf9694dde756ed5ad2b7220c1c39e6157165 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_TimestampInterface_getTimestamp, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_BSON_TimestampInterface_getIncrement arginfo_class_MongoDB_BSON_TimestampInterface_getTimestamp
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_TimestampInterface___toString, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
static const zend_function_entry class_MongoDB_BSON_TimestampInterface_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_BSON_TimestampInterface, getTimestamp, arginfo_class_MongoDB_BSON_TimestampInterface_getTimestamp, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_BSON_TimestampInterface, getIncrement, arginfo_class_MongoDB_BSON_TimestampInterface_getIncrement, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_BSON_TimestampInterface, __toString, arginfo_class_MongoDB_BSON_TimestampInterface___toString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_TimestampInterface(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "TimestampInterface", class_MongoDB_BSON_TimestampInterface_methods);
class_entry = zend_register_internal_interface(&ce);
return class_entry;
}
mongodb-2.1.0/src/BSON/Timestamp_arginfo.h 0000644 0001751 0000166 00000007107 15014033047 015233 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 0b768cfa7860b1bde5cbc32742528dd5754b9a85 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_BSON_Timestamp___construct, 0, 0, 2)
ZEND_ARG_TYPE_MASK(0, increment, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_ARG_TYPE_MASK(0, timestamp, MAY_BE_LONG|MAY_BE_STRING, NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Timestamp_getTimestamp, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_BSON_Timestamp_getIncrement arginfo_class_MongoDB_BSON_Timestamp_getTimestamp
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Timestamp___toString, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_Timestamp___set_state, 0, 1, MongoDB\\BSON\\Timestamp, 0)
ZEND_ARG_TYPE_INFO(0, properties, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Timestamp___unserialize, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Timestamp___serialize, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Timestamp_jsonSerialize, 0, 0, IS_MIXED, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_BSON_Timestamp, __construct);
static ZEND_METHOD(MongoDB_BSON_Timestamp, getTimestamp);
static ZEND_METHOD(MongoDB_BSON_Timestamp, getIncrement);
static ZEND_METHOD(MongoDB_BSON_Timestamp, __toString);
static ZEND_METHOD(MongoDB_BSON_Timestamp, __set_state);
static ZEND_METHOD(MongoDB_BSON_Timestamp, __unserialize);
static ZEND_METHOD(MongoDB_BSON_Timestamp, __serialize);
static ZEND_METHOD(MongoDB_BSON_Timestamp, jsonSerialize);
static const zend_function_entry class_MongoDB_BSON_Timestamp_methods[] = {
ZEND_ME(MongoDB_BSON_Timestamp, __construct, arginfo_class_MongoDB_BSON_Timestamp___construct, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Timestamp, getTimestamp, arginfo_class_MongoDB_BSON_Timestamp_getTimestamp, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Timestamp, getIncrement, arginfo_class_MongoDB_BSON_Timestamp_getIncrement, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Timestamp, __toString, arginfo_class_MongoDB_BSON_Timestamp___toString, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Timestamp, __set_state, arginfo_class_MongoDB_BSON_Timestamp___set_state, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Timestamp, __unserialize, arginfo_class_MongoDB_BSON_Timestamp___unserialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Timestamp, __serialize, arginfo_class_MongoDB_BSON_Timestamp___serialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Timestamp, jsonSerialize, arginfo_class_MongoDB_BSON_Timestamp_jsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_Timestamp(zend_class_entry *class_entry_MongoDB_BSON_TimestampInterface, zend_class_entry *class_entry_JsonSerializable, zend_class_entry *class_entry_MongoDB_BSON_Type, zend_class_entry *class_entry_Stringable)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Timestamp", class_MongoDB_BSON_Timestamp_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
zend_class_implements(class_entry, 4, class_entry_MongoDB_BSON_TimestampInterface, class_entry_JsonSerializable, class_entry_MongoDB_BSON_Type, class_entry_Stringable);
return class_entry;
}
mongodb-2.1.0/src/BSON/Type.c 0000644 0001751 0000166 00000001463 15014033047 012476 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "Type_arginfo.h"
zend_class_entry* php_phongo_type_ce;
void php_phongo_type_init_ce(INIT_FUNC_ARGS)
{
php_phongo_type_ce = register_class_MongoDB_BSON_Type();
}
mongodb-2.1.0/src/BSON/Type_arginfo.h 0000644 0001751 0000166 00000000735 15014033047 014211 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: ece602b4c841263e650ab50fa949a83ad265db69 */
static const zend_function_entry class_MongoDB_BSON_Type_methods[] = {
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_Type(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Type", class_MongoDB_BSON_Type_methods);
class_entry = zend_register_internal_interface(&ce);
return class_entry;
}
mongodb-2.1.0/src/BSON/UTCDateTime.c 0000644 0001751 0000166 00000027627 15014033047 013637 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "phongo_util.h"
#include "UTCDateTime_arginfo.h"
zend_class_entry* php_phongo_utcdatetime_ce;
/* Initialize the object and return whether it was successful. */
static bool php_phongo_utcdatetime_init(php_phongo_utcdatetime_t* intern, int64_t milliseconds)
{
intern->milliseconds = milliseconds;
intern->initialized = true;
return true;
}
/* Initialize the object from a numeric string and return whether it was
* successful. An exception will be thrown on error. */
static bool php_phongo_utcdatetime_init_from_string(php_phongo_utcdatetime_t* intern, const char* s_milliseconds, size_t s_milliseconds_len)
{
int64_t milliseconds;
if (!php_phongo_parse_int64(&milliseconds, s_milliseconds, s_milliseconds_len)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Error parsing \"%s\" as 64-bit integer for %s initialization", s_milliseconds, ZSTR_VAL(php_phongo_utcdatetime_ce->name));
return false;
}
return php_phongo_utcdatetime_init(intern, milliseconds);
}
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_utcdatetime_init_from_hash(php_phongo_utcdatetime_t* intern, HashTable* props)
{
zval* milliseconds;
if ((milliseconds = zend_hash_str_find(props, "milliseconds", sizeof("milliseconds") - 1)) && Z_TYPE_P(milliseconds) == IS_LONG) {
return php_phongo_utcdatetime_init(intern, Z_LVAL_P(milliseconds));
}
if ((milliseconds = zend_hash_str_find(props, "milliseconds", sizeof("milliseconds") - 1)) && Z_TYPE_P(milliseconds) == IS_STRING) {
return php_phongo_utcdatetime_init_from_string(intern, Z_STRVAL_P(milliseconds), Z_STRLEN_P(milliseconds));
}
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"milliseconds\" integer or numeric string field", ZSTR_VAL(php_phongo_utcdatetime_ce->name));
return false;
}
/* Initialize the object from the current time and return whether it was
* successful. */
static bool php_phongo_utcdatetime_init_from_current_time(php_phongo_utcdatetime_t* intern)
{
int64_t sec, usec;
struct timeval cur_time;
bson_gettimeofday(&cur_time);
sec = cur_time.tv_sec;
usec = cur_time.tv_usec;
intern->milliseconds = (sec * 1000) + (usec / 1000);
intern->initialized = true;
return true;
}
/* Initialize the object from a DateTime object and return whether it was
* successful. */
static bool php_phongo_utcdatetime_init_from_date(php_phongo_utcdatetime_t* intern, php_date_obj* datetime_obj)
{
int64_t sec, usec;
/* The following assignments use the same logic as date_format() in php_date.c */
sec = datetime_obj->time->sse;
usec = (int64_t) floor(datetime_obj->time->us);
intern->milliseconds = (sec * 1000) + (usec / 1000);
intern->initialized = true;
return true;
}
static bool php_phongo_utcdatetime_init_from_object(php_phongo_utcdatetime_t* intern, zend_object* object)
{
if (instanceof_function(object->ce, php_date_get_interface_ce())) {
php_phongo_utcdatetime_init_from_date(intern, php_date_obj_from_obj(object));
return true;
}
if (instanceof_function(object->ce, php_phongo_int64_ce)) {
php_phongo_utcdatetime_init(intern, php_int64_fetch_object(object)->integer);
return true;
}
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected instance of %s or %s, %s given", ZSTR_VAL(php_date_get_interface_ce()->name), ZSTR_VAL(php_phongo_int64_ce->name), ZSTR_VAL(object->ce->name));
return false;
}
static HashTable* php_phongo_utcdatetime_get_properties_hash(zend_object* object, bool is_temp)
{
php_phongo_utcdatetime_t* intern;
HashTable* props;
intern = Z_OBJ_UTCDATETIME(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_temp, intern, props, 1);
if (!intern->initialized) {
return props;
}
{
zval milliseconds;
ZVAL_INT64_STRING(&milliseconds, intern->milliseconds);
zend_hash_str_update(props, "milliseconds", sizeof("milliseconds") - 1, &milliseconds);
}
return props;
}
static void php_phongo_utcdatetime_to_php_date(zval* return_value, const zval* this, zend_class_entry* ce)
{
php_phongo_utcdatetime_t* intern;
php_date_obj* datetime_obj;
char* sec_str;
size_t sec_len;
int64_t sec, usec;
intern = Z_UTCDATETIME_OBJ_P(this);
object_init_ex(return_value, ce);
datetime_obj = Z_PHPDATE_P(return_value);
sec = intern->milliseconds / 1000;
usec = (llabs(intern->milliseconds) % 1000) * 1000;
if (intern->milliseconds < 0 && usec != 0) {
/* For dates before the unix epoch, we need to subtract the microseconds from the timestamp.
* Since we can't directly pass microseconds when calling php_date_initialize due to a bug in PHP,
* we manually decrement the timestamp and subtract the number of microseconds from a full seconds
* to store in the us field. */
sec--;
usec = 1000000 - usec;
}
/* TODO PHP 8.1.7+: microseconds can be included in the format string */
sec_len = spprintf(&sec_str, 0, "@%" PRId64, sec);
php_date_initialize(datetime_obj, sec_str, sec_len, NULL, NULL, 0);
efree(sec_str);
datetime_obj->time->us = usec;
}
/* Construct a new BSON UTCDateTime type from either the current time,
milliseconds since the epoch, or a DateTimeInterface object. Defaults to the
current time. */
static PHP_METHOD(MongoDB_BSON_UTCDateTime, __construct)
{
php_phongo_utcdatetime_t* intern;
zval* milliseconds = NULL;
intern = Z_UTCDATETIME_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_ZVAL_OR_NULL(milliseconds)
PHONGO_PARSE_PARAMETERS_END();
if (milliseconds == NULL) {
php_phongo_utcdatetime_init_from_current_time(intern);
return;
}
switch (Z_TYPE_P(milliseconds)) {
case IS_OBJECT:
php_phongo_utcdatetime_init_from_object(intern, Z_OBJ_P(milliseconds));
return;
case IS_LONG:
php_phongo_utcdatetime_init(intern, Z_LVAL_P(milliseconds));
return;
}
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected integer or object, %s given", zend_zval_type_name(milliseconds));
}
static PHP_METHOD(MongoDB_BSON_UTCDateTime, __set_state)
{
php_phongo_utcdatetime_t* intern;
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
object_init_ex(return_value, php_phongo_utcdatetime_ce);
intern = Z_UTCDATETIME_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_utcdatetime_init_from_hash(intern, props);
}
/* Returns the UTCDateTime's milliseconds as a string */
static PHP_METHOD(MongoDB_BSON_UTCDateTime, __toString)
{
php_phongo_utcdatetime_t* intern;
intern = Z_UTCDATETIME_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
ZVAL_INT64_STRING(return_value, intern->milliseconds);
}
/* Returns a DateTime object representing this UTCDateTime */
static PHP_METHOD(MongoDB_BSON_UTCDateTime, toDateTime)
{
PHONGO_PARSE_PARAMETERS_NONE();
php_phongo_utcdatetime_to_php_date(return_value, getThis(), php_date_get_date_ce());
}
/* Returns a DateTimeImmutable object representing this UTCDateTime */
static PHP_METHOD(MongoDB_BSON_UTCDateTime, toDateTimeImmutable)
{
PHONGO_PARSE_PARAMETERS_NONE();
php_phongo_utcdatetime_to_php_date(return_value, getThis(), php_date_get_immutable_ce());
}
static PHP_METHOD(MongoDB_BSON_UTCDateTime, jsonSerialize)
{
php_phongo_utcdatetime_t* intern;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_UTCDATETIME_OBJ_P(getThis());
array_init_size(return_value, 1);
{
zval udt;
array_init_size(&udt, 1);
ADD_ASSOC_INT64_AS_STRING(&udt, "$numberLong", intern->milliseconds);
ADD_ASSOC_ZVAL_EX(return_value, "$date", &udt);
}
}
static PHP_METHOD(MongoDB_BSON_UTCDateTime, __serialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_ARR(php_phongo_utcdatetime_get_properties_hash(Z_OBJ_P(getThis()), true));
}
static PHP_METHOD(MongoDB_BSON_UTCDateTime, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_utcdatetime_init_from_hash(Z_UTCDATETIME_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\UTCDateTime object handlers */
static zend_object_handlers php_phongo_handler_utcdatetime;
static void php_phongo_utcdatetime_free_object(zend_object* object)
{
php_phongo_utcdatetime_t* intern = Z_OBJ_UTCDATETIME(object);
zend_object_std_dtor(&intern->std);
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
}
static zend_object* php_phongo_utcdatetime_create_object(zend_class_entry* class_type)
{
php_phongo_utcdatetime_t* intern = zend_object_alloc(sizeof(php_phongo_utcdatetime_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_utcdatetime;
return &intern->std;
}
static zend_object* php_phongo_utcdatetime_clone_object(zend_object* object)
{
php_phongo_utcdatetime_t* intern;
php_phongo_utcdatetime_t* new_intern;
zend_object* new_object;
intern = Z_OBJ_UTCDATETIME(object);
new_object = php_phongo_utcdatetime_create_object(object->ce);
new_intern = Z_OBJ_UTCDATETIME(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
php_phongo_utcdatetime_init(new_intern, intern->milliseconds);
return new_object;
}
static int php_phongo_utcdatetime_compare_objects(zval* o1, zval* o2)
{
php_phongo_utcdatetime_t *intern1, *intern2;
ZEND_COMPARE_OBJECTS_FALLBACK(o1, o2);
intern1 = Z_UTCDATETIME_OBJ_P(o1);
intern2 = Z_UTCDATETIME_OBJ_P(o2);
if (intern1->milliseconds != intern2->milliseconds) {
return intern1->milliseconds < intern2->milliseconds ? -1 : 1;
}
return 0;
}
static HashTable* php_phongo_utcdatetime_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return php_phongo_utcdatetime_get_properties_hash(object, true);
}
static HashTable* php_phongo_utcdatetime_get_properties(zend_object* object)
{
return php_phongo_utcdatetime_get_properties_hash(object, false);
}
void php_phongo_utcdatetime_init_ce(INIT_FUNC_ARGS)
{
php_phongo_utcdatetime_ce = register_class_MongoDB_BSON_UTCDateTime(php_phongo_utcdatetime_interface_ce, php_phongo_json_serializable_ce, php_phongo_type_ce, zend_ce_stringable);
php_phongo_utcdatetime_ce->create_object = php_phongo_utcdatetime_create_object;
memcpy(&php_phongo_handler_utcdatetime, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_utcdatetime.compare = php_phongo_utcdatetime_compare_objects;
php_phongo_handler_utcdatetime.clone_obj = php_phongo_utcdatetime_clone_object;
php_phongo_handler_utcdatetime.get_debug_info = php_phongo_utcdatetime_get_debug_info;
php_phongo_handler_utcdatetime.get_properties = php_phongo_utcdatetime_get_properties;
php_phongo_handler_utcdatetime.free_obj = php_phongo_utcdatetime_free_object;
php_phongo_handler_utcdatetime.offset = XtOffsetOf(php_phongo_utcdatetime_t, std);
}
bool phongo_utcdatetime_new(zval* object, int64_t msec_since_epoch)
{
php_phongo_utcdatetime_t* intern;
object_init_ex(object, php_phongo_utcdatetime_ce);
intern = Z_UTCDATETIME_OBJ_P(object);
intern->milliseconds = msec_since_epoch;
intern->initialized = true;
return true;
}
mongodb-2.1.0/src/BSON/UTCDateTime.h 0000644 0001751 0000166 00000001416 15014033047 013630 0 ustar /*
* Copyright 2023-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_BSON_UTCDATETIME_H
#define PHONGO_BSON_UTCDATETIME_H
bool phongo_utcdatetime_new(zval* object, int64_t msec_since_epoch);
#endif /* PHONGO_BSON_UTCDATETIME_H */
mongodb-2.1.0/src/BSON/UTCDateTimeInterface.c 0000644 0001751 0000166 00000001606 15014033047 015445 0 ustar /*
* Copyright 2017-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "UTCDateTimeInterface_arginfo.h"
zend_class_entry* php_phongo_utcdatetime_interface_ce;
void php_phongo_utcdatetime_interface_init_ce(INIT_FUNC_ARGS)
{
php_phongo_utcdatetime_interface_ce = register_class_MongoDB_BSON_UTCDateTimeInterface();
}
mongodb-2.1.0/src/BSON/UTCDateTimeInterface_arginfo.h 0000644 0001751 0000166 00000002745 15014033047 017164 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 9dfbe17b754382e121289ef990984d39b18117ca */
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_UTCDateTimeInterface_toDateTime, 0, 0, DateTime, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_UTCDateTimeInterface_toDateTimeImmutable, 0, 0, DateTimeImmutable, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_UTCDateTimeInterface___toString, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
static const zend_function_entry class_MongoDB_BSON_UTCDateTimeInterface_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_BSON_UTCDateTimeInterface, toDateTime, arginfo_class_MongoDB_BSON_UTCDateTimeInterface_toDateTime, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_BSON_UTCDateTimeInterface, toDateTimeImmutable, arginfo_class_MongoDB_BSON_UTCDateTimeInterface_toDateTimeImmutable, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_BSON_UTCDateTimeInterface, __toString, arginfo_class_MongoDB_BSON_UTCDateTimeInterface___toString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_UTCDateTimeInterface(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "UTCDateTimeInterface", class_MongoDB_BSON_UTCDateTimeInterface_methods);
class_entry = zend_register_internal_interface(&ce);
return class_entry;
}
mongodb-2.1.0/src/BSON/UTCDateTime_arginfo.h 0000644 0001751 0000166 00000007266 15014033047 015346 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: b5033645ba31d4b4e5040548ea979cef5e3e8adb */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_BSON_UTCDateTime___construct, 0, 0, 0)
ZEND_ARG_OBJ_TYPE_MASK(0, milliseconds, DateTimeInterface|MongoDB\\BSON\\Int64, MAY_BE_LONG|MAY_BE_NULL, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_UTCDateTime_toDateTime, 0, 0, DateTime, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_UTCDateTime_toDateTimeImmutable, 0, 0, DateTimeImmutable, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_UTCDateTime___toString, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_UTCDateTime___set_state, 0, 1, MongoDB\\BSON\\\125TCDateTime, 0)
ZEND_ARG_TYPE_INFO(0, properties, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_UTCDateTime___unserialize, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_UTCDateTime___serialize, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_UTCDateTime_jsonSerialize, 0, 0, IS_MIXED, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_BSON_UTCDateTime, __construct);
static ZEND_METHOD(MongoDB_BSON_UTCDateTime, toDateTime);
static ZEND_METHOD(MongoDB_BSON_UTCDateTime, toDateTimeImmutable);
static ZEND_METHOD(MongoDB_BSON_UTCDateTime, __toString);
static ZEND_METHOD(MongoDB_BSON_UTCDateTime, __set_state);
static ZEND_METHOD(MongoDB_BSON_UTCDateTime, __unserialize);
static ZEND_METHOD(MongoDB_BSON_UTCDateTime, __serialize);
static ZEND_METHOD(MongoDB_BSON_UTCDateTime, jsonSerialize);
static const zend_function_entry class_MongoDB_BSON_UTCDateTime_methods[] = {
ZEND_ME(MongoDB_BSON_UTCDateTime, __construct, arginfo_class_MongoDB_BSON_UTCDateTime___construct, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_UTCDateTime, toDateTime, arginfo_class_MongoDB_BSON_UTCDateTime_toDateTime, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_UTCDateTime, toDateTimeImmutable, arginfo_class_MongoDB_BSON_UTCDateTime_toDateTimeImmutable, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_UTCDateTime, __toString, arginfo_class_MongoDB_BSON_UTCDateTime___toString, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_UTCDateTime, __set_state, arginfo_class_MongoDB_BSON_UTCDateTime___set_state, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_UTCDateTime, __unserialize, arginfo_class_MongoDB_BSON_UTCDateTime___unserialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_UTCDateTime, __serialize, arginfo_class_MongoDB_BSON_UTCDateTime___serialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_UTCDateTime, jsonSerialize, arginfo_class_MongoDB_BSON_UTCDateTime_jsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_UTCDateTime(zend_class_entry *class_entry_MongoDB_BSON_UTCDateTimeInterface, zend_class_entry *class_entry_JsonSerializable, zend_class_entry *class_entry_MongoDB_BSON_Type, zend_class_entry *class_entry_Stringable)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "UTCDateTime", class_MongoDB_BSON_UTCDateTime_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
zend_class_implements(class_entry, 4, class_entry_MongoDB_BSON_UTCDateTimeInterface, class_entry_JsonSerializable, class_entry_MongoDB_BSON_Type, class_entry_Stringable);
return class_entry;
}
mongodb-2.1.0/src/BSON/Undefined.c 0000644 0001751 0000166 00000005676 15014033047 013470 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "Undefined_arginfo.h"
zend_class_entry* php_phongo_undefined_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_BSON_Undefined)
/* Return the empty string. */
static PHP_METHOD(MongoDB_BSON_Undefined, __toString)
{
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_STRINGL("", 0);
}
static PHP_METHOD(MongoDB_BSON_Undefined, __set_state)
{
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
object_init_ex(return_value, php_phongo_undefined_ce);
}
static PHP_METHOD(MongoDB_BSON_Undefined, jsonSerialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
array_init_size(return_value, 1);
ADD_ASSOC_BOOL_EX(return_value, "$undefined", 1);
}
static PHP_METHOD(MongoDB_BSON_Undefined, __serialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
array_init_size(return_value, 0);
}
static PHP_METHOD(MongoDB_BSON_Undefined, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
}
/* MongoDB\BSON\Undefined object handlers */
static zend_object_handlers php_phongo_handler_undefined;
static void php_phongo_undefined_free_object(zend_object* object)
{
php_phongo_undefined_t* intern = Z_OBJ_UNDEFINED(object);
zend_object_std_dtor(&intern->std);
}
static zend_object* php_phongo_undefined_create_object(zend_class_entry* class_type)
{
php_phongo_undefined_t* intern = zend_object_alloc(sizeof(php_phongo_undefined_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_undefined;
return &intern->std;
}
void php_phongo_undefined_init_ce(INIT_FUNC_ARGS)
{
php_phongo_undefined_ce = register_class_MongoDB_BSON_Undefined(php_phongo_json_serializable_ce, php_phongo_type_ce, zend_ce_stringable);
php_phongo_undefined_ce->create_object = php_phongo_undefined_create_object;
memcpy(&php_phongo_handler_undefined, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
/* Re-assign default handler previously removed in php_phongo.c */
php_phongo_handler_undefined.clone_obj = zend_objects_clone_obj;
php_phongo_handler_undefined.free_obj = php_phongo_undefined_free_object;
php_phongo_handler_undefined.offset = XtOffsetOf(php_phongo_undefined_t, std);
}
mongodb-2.1.0/src/BSON/Undefined_arginfo.h 0000644 0001751 0000166 00000005362 15014033047 015172 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 4f9631736bdc048203268e88e70cc395b383aee4 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_BSON_Undefined___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Undefined___toString, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_Undefined___set_state, 0, 1, MongoDB\\BSON\\\125ndefined, 0)
ZEND_ARG_TYPE_INFO(0, properties, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Undefined___unserialize, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Undefined___serialize, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Undefined_jsonSerialize, 0, 0, IS_MIXED, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_BSON_Undefined, __construct);
static ZEND_METHOD(MongoDB_BSON_Undefined, __toString);
static ZEND_METHOD(MongoDB_BSON_Undefined, __set_state);
static ZEND_METHOD(MongoDB_BSON_Undefined, __unserialize);
static ZEND_METHOD(MongoDB_BSON_Undefined, __serialize);
static ZEND_METHOD(MongoDB_BSON_Undefined, jsonSerialize);
static const zend_function_entry class_MongoDB_BSON_Undefined_methods[] = {
ZEND_ME(MongoDB_BSON_Undefined, __construct, arginfo_class_MongoDB_BSON_Undefined___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Undefined, __toString, arginfo_class_MongoDB_BSON_Undefined___toString, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Undefined, __set_state, arginfo_class_MongoDB_BSON_Undefined___set_state, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Undefined, __unserialize, arginfo_class_MongoDB_BSON_Undefined___unserialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Undefined, __serialize, arginfo_class_MongoDB_BSON_Undefined___serialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Undefined, jsonSerialize, arginfo_class_MongoDB_BSON_Undefined_jsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_Undefined(zend_class_entry *class_entry_JsonSerializable, zend_class_entry *class_entry_MongoDB_BSON_Type, zend_class_entry *class_entry_Stringable)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Undefined", class_MongoDB_BSON_Undefined_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
zend_class_implements(class_entry, 3, class_entry_JsonSerializable, class_entry_MongoDB_BSON_Type, class_entry_Stringable);
return class_entry;
}
mongodb-2.1.0/src/BSON/Unserializable.c 0000644 0001751 0000166 00000002453 15014033047 014526 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "Unserializable_arginfo.h"
zend_class_entry* php_phongo_unserializable_ce;
static int php_phongo_implement_unserializable(zend_class_entry* interface, zend_class_entry* class_type)
{
if (class_type->ce_flags & ZEND_ACC_ENUM) {
zend_error_noreturn(E_ERROR, "Enum class %s cannot implement interface %s", ZSTR_VAL(class_type->name), ZSTR_VAL(interface->name));
return FAILURE;
}
return SUCCESS;
}
void php_phongo_unserializable_init_ce(INIT_FUNC_ARGS)
{
php_phongo_unserializable_ce = register_class_MongoDB_BSON_Unserializable();
php_phongo_unserializable_ce->interface_gets_implemented = php_phongo_implement_unserializable;
}
mongodb-2.1.0/src/BSON/Unserializable_arginfo.h 0000644 0001751 0000166 00000001542 15014033047 016236 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: b9746862d533c46cd8977bde20093fe92d8f4440 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Unserializable_bsonUnserialize, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
static const zend_function_entry class_MongoDB_BSON_Unserializable_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_BSON_Unserializable, bsonUnserialize, arginfo_class_MongoDB_BSON_Unserializable_bsonUnserialize, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_BSON_Unserializable(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Unserializable", class_MongoDB_BSON_Unserializable_methods);
class_entry = zend_register_internal_interface(&ce);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Exception/AuthenticationException.c 0000644 0001751 0000166 00000001677 15014033047 021104 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "AuthenticationException_arginfo.h"
zend_class_entry* php_phongo_authenticationexception_ce;
void php_phongo_authenticationexception_init_ce(INIT_FUNC_ARGS)
{
php_phongo_authenticationexception_ce = register_class_MongoDB_Driver_Exception_AuthenticationException(php_phongo_connectionexception_ce);
}
mongodb-2.1.0/src/MongoDB/Exception/AuthenticationException_arginfo.h 0000644 0001751 0000166 00000001331 15014033047 022601 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: dfb57a5b65b8a075b239be872177213a182faf60 */
static const zend_function_entry class_MongoDB_Driver_Exception_AuthenticationException_methods[] = {
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Exception_AuthenticationException(zend_class_entry *class_entry_MongoDB_Driver_Exception_ConnectionException)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "AuthenticationException", class_MongoDB_Driver_Exception_AuthenticationException_methods);
class_entry = zend_register_internal_class_ex(&ce, class_entry_MongoDB_Driver_Exception_ConnectionException);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Exception/BulkWriteCommandException.c 0000644 0001751 0000166 00000014263 15014033047 021327 0 ustar /*
* Copyright 2024-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "BSON/Document.h"
#include "BulkWriteCommandException.h"
#include "BulkWriteCommandException_arginfo.h"
#include "MongoDB/WriteConcernError.h"
#include "MongoDB/WriteError.h"
zend_class_entry* php_phongo_bulkwritecommandexception_ce;
/* Returns the error reply document (if any) from the failed bulk write */
static PHP_METHOD(MongoDB_Driver_Exception_BulkWriteCommandException, getErrorReply)
{
PHONGO_PARSE_PARAMETERS_NONE();
zval rv;
zval* result = zend_read_property(php_phongo_bulkwritecommandexception_ce, Z_OBJ_P(getThis()), ZEND_STRL("errorReply"), 0, &rv);
RETURN_ZVAL(result, 1, 0);
}
/* Returns the partial BulkWriteCommandResult (if any) from the failed bulk write. */
static PHP_METHOD(MongoDB_Driver_Exception_BulkWriteCommandException, getPartialResult)
{
PHONGO_PARSE_PARAMETERS_NONE();
zval rv;
zval* result = zend_read_property(php_phongo_bulkwritecommandexception_ce, Z_OBJ_P(getThis()), ZEND_STRL("partialResult"), 0, &rv);
RETURN_ZVAL(result, 1, 0);
}
/* Returns a map of write errors from the failed bulk write. */
static PHP_METHOD(MongoDB_Driver_Exception_BulkWriteCommandException, getWriteErrors)
{
PHONGO_PARSE_PARAMETERS_NONE();
zval rv;
zval* result = zend_read_property(php_phongo_bulkwritecommandexception_ce, Z_OBJ_P(getThis()), ZEND_STRL("writeErrors"), 0, &rv);
RETURN_ZVAL(result, 1, 0);
}
/* Returns a list of write concern errors from the failed bulk write. */
static PHP_METHOD(MongoDB_Driver_Exception_BulkWriteCommandException, getWriteConcernErrors)
{
PHONGO_PARSE_PARAMETERS_NONE();
zval rv;
zval* result = zend_read_property(php_phongo_bulkwritecommandexception_ce, Z_OBJ_P(getThis()), ZEND_STRL("writeConcernErrors"), 0, &rv);
RETURN_ZVAL(result, 1, 0);
}
void php_phongo_bulkwritecommandexception_init_ce(INIT_FUNC_ARGS)
{
php_phongo_bulkwritecommandexception_ce = register_class_MongoDB_Driver_Exception_BulkWriteCommandException(php_phongo_serverexception_ce);
}
/* Populates return_value with a list of WriteConcernError objects. Returns true
* on success; otherwise, false is returned and an exception is thrown. */
static bool phongo_bulkwritecommandexception_get_writeconcernerrors(const bson_t* write_concern_errors, zval* return_value)
{
bson_iter_t iter;
array_init(return_value);
if (bson_iter_init(&iter, write_concern_errors)) {
while (bson_iter_next(&iter)) {
bson_t bson;
uint32_t len;
const uint8_t* data;
zval write_concern_error;
if (!BSON_ITER_HOLDS_DOCUMENT(&iter)) {
continue;
}
bson_iter_document(&iter, &len, &data);
if (!bson_init_static(&bson, data, len)) {
continue;
}
if (!phongo_writeconcernerror_init(&write_concern_error, &bson)) {
/* Exception already thrown */
zval_ptr_dtor(&write_concern_error);
return false;
}
add_next_index_zval(return_value, &write_concern_error);
}
}
return true;
}
/* Populates return_value with a map of WriteError objects indexed by the offset
* of the corresponding operation. Returns true on success; otherwise, false is
* returned and an exception is thrown. */
static bool phongo_bulkwritecommandexception_get_writeerrors(const bson_t* write_errors, zval* return_value)
{
bson_iter_t iter;
array_init(return_value);
if (bson_iter_init(&iter, write_errors)) {
while (bson_iter_next(&iter)) {
bson_t bson;
uint32_t len;
const uint8_t* data;
zval write_error;
zend_ulong index;
if (!BSON_ITER_HOLDS_DOCUMENT(&iter)) {
continue;
}
bson_iter_document(&iter, &len, &data);
if (!bson_init_static(&bson, data, len)) {
continue;
}
index = (zend_ulong) ZEND_STRTOUL(bson_iter_key(&iter), NULL, 10);
if (!phongo_writeerror_init_ex(&write_error, &bson, (int32_t) index)) {
/* Exception already thrown */
zval_ptr_dtor(&write_error);
return false;
}
add_index_zval(return_value, index, &write_error);
}
}
return true;
}
void php_phongo_bulkwritecommandexception_init_props(zend_object* object, const mongoc_bulkwriteexception_t* bw_exc, zval* result)
{
const bson_t* errorreply = mongoc_bulkwriteexception_errorreply(bw_exc);
zval zwriteconcernerrors, zwriteerrors;
if (!bson_empty(errorreply)) {
zval zerrorreply;
/* Manually copy the bson_t to satisfy phongo_document_new. This can be
* changed once PHPC-2535 is addressed. */
phongo_document_new(&zerrorreply, bson_copy(errorreply), false);
zend_update_property(php_phongo_bulkwritecommandexception_ce, object, ZEND_STRL("errorReply"), &zerrorreply);
zval_ptr_dtor(&zerrorreply);
}
if (result && Z_TYPE_P(result) == IS_OBJECT && instanceof_function(Z_OBJCE_P(result), php_phongo_bulkwritecommandresult_ce)) {
zend_update_property(php_phongo_bulkwritecommandexception_ce, object, ZEND_STRL("partialResult"), result);
}
/* Note: get_writeconcernerrors and get_writeerrors could throw if BSON
* decoding fails, but that risk similarly exists for decoding a command
* result in phongo_throw_exception_from_bson_error_t_and_reply. */
if (phongo_bulkwritecommandexception_get_writeconcernerrors(mongoc_bulkwriteexception_writeconcernerrors(bw_exc), &zwriteconcernerrors)) {
zend_update_property(php_phongo_bulkwritecommandexception_ce, object, ZEND_STRL("writeConcernErrors"), &zwriteconcernerrors);
}
if (phongo_bulkwritecommandexception_get_writeerrors(mongoc_bulkwriteexception_writeerrors(bw_exc), &zwriteerrors)) {
zend_update_property(php_phongo_bulkwritecommandexception_ce, object, ZEND_STRL("writeErrors"), &zwriteerrors);
}
zval_ptr_dtor(&zwriteconcernerrors);
zval_ptr_dtor(&zwriteerrors);
}
mongodb-2.1.0/src/MongoDB/Exception/BulkWriteCommandException.h 0000644 0001751 0000166 00000001625 15014033047 021332 0 ustar /*
* Copyright 2024-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_BULKWRITECOMMANDEXCEPTION_H
#define PHONGO_BULKWRITECOMMANDEXCEPTION_H
#include "mongoc/mongoc.h"
#include
void php_phongo_bulkwritecommandexception_init_props(zend_object* object, const mongoc_bulkwriteexception_t* bw_exc, zval* result);
#endif /* PHONGO_BULKWRITECOMMANDEXCEPTION_H */
mongodb-2.1.0/src/MongoDB/Exception/BulkWriteCommandException_arginfo.h 0000644 0001751 0000166 00000011371 15014033047 023036 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 16a2478ef423f897f914ad7b2ed3dbbdc4036e60 */
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Exception_BulkWriteCommandException_getErrorReply, 0, 0, MongoDB\\BSON\\Document, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Exception_BulkWriteCommandException_getPartialResult, 0, 0, MongoDB\\Driver\\BulkWriteCommandResult, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Exception_BulkWriteCommandException_getWriteErrors, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_Exception_BulkWriteCommandException_getWriteConcernErrors arginfo_class_MongoDB_Driver_Exception_BulkWriteCommandException_getWriteErrors
static ZEND_METHOD(MongoDB_Driver_Exception_BulkWriteCommandException, getErrorReply);
static ZEND_METHOD(MongoDB_Driver_Exception_BulkWriteCommandException, getPartialResult);
static ZEND_METHOD(MongoDB_Driver_Exception_BulkWriteCommandException, getWriteErrors);
static ZEND_METHOD(MongoDB_Driver_Exception_BulkWriteCommandException, getWriteConcernErrors);
static const zend_function_entry class_MongoDB_Driver_Exception_BulkWriteCommandException_methods[] = {
ZEND_ME(MongoDB_Driver_Exception_BulkWriteCommandException, getErrorReply, arginfo_class_MongoDB_Driver_Exception_BulkWriteCommandException_getErrorReply, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Exception_BulkWriteCommandException, getPartialResult, arginfo_class_MongoDB_Driver_Exception_BulkWriteCommandException_getPartialResult, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Exception_BulkWriteCommandException, getWriteErrors, arginfo_class_MongoDB_Driver_Exception_BulkWriteCommandException_getWriteErrors, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Exception_BulkWriteCommandException, getWriteConcernErrors, arginfo_class_MongoDB_Driver_Exception_BulkWriteCommandException_getWriteConcernErrors, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Exception_BulkWriteCommandException(zend_class_entry *class_entry_MongoDB_Driver_Exception_ServerException)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "BulkWriteCommandException", class_MongoDB_Driver_Exception_BulkWriteCommandException_methods);
class_entry = zend_register_internal_class_ex(&ce, class_entry_MongoDB_Driver_Exception_ServerException);
class_entry->ce_flags |= ZEND_ACC_FINAL;
zend_string *property_errorReply_class_MongoDB_BSON_Document = zend_string_init("MongoDB\\BSON\\Document", sizeof("MongoDB\\BSON\\Document")-1, 1);
zval property_errorReply_default_value;
ZVAL_NULL(&property_errorReply_default_value);
zend_string *property_errorReply_name = zend_string_init("errorReply", sizeof("errorReply") - 1, 1);
zend_declare_typed_property(class_entry, property_errorReply_name, &property_errorReply_default_value, ZEND_ACC_PRIVATE, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_errorReply_class_MongoDB_BSON_Document, 0, MAY_BE_NULL));
zend_string_release(property_errorReply_name);
zend_string *property_partialResult_class_MongoDB_Driver_BulkWriteCommandResult = zend_string_init("MongoDB\\Driver\\BulkWriteCommandResult", sizeof("MongoDB\\Driver\\BulkWriteCommandResult")-1, 1);
zval property_partialResult_default_value;
ZVAL_NULL(&property_partialResult_default_value);
zend_string *property_partialResult_name = zend_string_init("partialResult", sizeof("partialResult") - 1, 1);
zend_declare_typed_property(class_entry, property_partialResult_name, &property_partialResult_default_value, ZEND_ACC_PRIVATE, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_partialResult_class_MongoDB_Driver_BulkWriteCommandResult, 0, MAY_BE_NULL));
zend_string_release(property_partialResult_name);
zval property_writeErrors_default_value;
ZVAL_EMPTY_ARRAY(&property_writeErrors_default_value);
zend_string *property_writeErrors_name = zend_string_init("writeErrors", sizeof("writeErrors") - 1, 1);
zend_declare_typed_property(class_entry, property_writeErrors_name, &property_writeErrors_default_value, ZEND_ACC_PRIVATE, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_ARRAY));
zend_string_release(property_writeErrors_name);
zval property_writeConcernErrors_default_value;
ZVAL_EMPTY_ARRAY(&property_writeConcernErrors_default_value);
zend_string *property_writeConcernErrors_name = zend_string_init("writeConcernErrors", sizeof("writeConcernErrors") - 1, 1);
zend_declare_typed_property(class_entry, property_writeConcernErrors_name, &property_writeConcernErrors_default_value, ZEND_ACC_PRIVATE, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_ARRAY));
zend_string_release(property_writeConcernErrors_name);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Exception/BulkWriteException.c 0000644 0001751 0000166 00000002456 15014033047 020031 0 ustar /*
* Copyright 2015-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "BulkWriteException_arginfo.h"
zend_class_entry* php_phongo_bulkwriteexception_ce;
/* Returns the WriteResult from the failed write operation. */
static PHP_METHOD(MongoDB_Driver_Exception_BulkWriteException, getWriteResult)
{
zval* writeresult;
zval rv;
PHONGO_PARSE_PARAMETERS_NONE();
writeresult = zend_read_property(php_phongo_bulkwriteexception_ce, Z_OBJ_P(getThis()), ZEND_STRL("writeResult"), 0, &rv);
RETURN_ZVAL(writeresult, 1, 0);
}
void php_phongo_bulkwriteexception_init_ce(INIT_FUNC_ARGS)
{
php_phongo_bulkwriteexception_ce = register_class_MongoDB_Driver_Exception_BulkWriteException(php_phongo_serverexception_ce);
}
mongodb-2.1.0/src/MongoDB/Exception/BulkWriteException_arginfo.h 0000644 0001751 0000166 00000002743 15014033047 021542 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 3a09fcb79df6117de9924cfce65ba8762d9c8bc2 */
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Exception_BulkWriteException_getWriteResult, 0, 0, MongoDB\\Driver\\WriteResult, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_Exception_BulkWriteException, getWriteResult);
static const zend_function_entry class_MongoDB_Driver_Exception_BulkWriteException_methods[] = {
ZEND_ME(MongoDB_Driver_Exception_BulkWriteException, getWriteResult, arginfo_class_MongoDB_Driver_Exception_BulkWriteException_getWriteResult, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Exception_BulkWriteException(zend_class_entry *class_entry_MongoDB_Driver_Exception_ServerException)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "BulkWriteException", class_MongoDB_Driver_Exception_BulkWriteException_methods);
class_entry = zend_register_internal_class_ex(&ce, class_entry_MongoDB_Driver_Exception_ServerException);
zval property_writeResult_default_value;
ZVAL_NULL(&property_writeResult_default_value);
zend_string *property_writeResult_name = zend_string_init("writeResult", sizeof("writeResult") - 1, 1);
zend_declare_property_ex(class_entry, property_writeResult_name, &property_writeResult_default_value, ZEND_ACC_PROTECTED, NULL);
zend_string_release(property_writeResult_name);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Exception/CommandException.c 0000644 0001751 0000166 00000002453 15014033047 017474 0 ustar /*
* Copyright 2018-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "CommandException_arginfo.h"
zend_class_entry* php_phongo_commandexception_ce;
/* Returns the result document from the failed command. */
static PHP_METHOD(MongoDB_Driver_Exception_CommandException, getResultDocument)
{
zval* resultdocument;
zval rv;
PHONGO_PARSE_PARAMETERS_NONE();
resultdocument = zend_read_property(php_phongo_commandexception_ce, Z_OBJ_P(getThis()), ZEND_STRL("resultDocument"), 0, &rv);
RETURN_ZVAL(resultdocument, 1, 0);
}
void php_phongo_commandexception_init_ce(INIT_FUNC_ARGS)
{
php_phongo_commandexception_ce = register_class_MongoDB_Driver_Exception_CommandException(php_phongo_serverexception_ce);
}
mongodb-2.1.0/src/MongoDB/Exception/CommandException_arginfo.h 0000644 0001751 0000166 00000002745 15014033047 021212 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 55cb6773eee137316b8b5a78cd1050b061b2e24e */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Exception_CommandException_getResultDocument, 0, 0, IS_OBJECT, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_Exception_CommandException, getResultDocument);
static const zend_function_entry class_MongoDB_Driver_Exception_CommandException_methods[] = {
ZEND_ME(MongoDB_Driver_Exception_CommandException, getResultDocument, arginfo_class_MongoDB_Driver_Exception_CommandException_getResultDocument, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Exception_CommandException(zend_class_entry *class_entry_MongoDB_Driver_Exception_ServerException)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "CommandException", class_MongoDB_Driver_Exception_CommandException_methods);
class_entry = zend_register_internal_class_ex(&ce, class_entry_MongoDB_Driver_Exception_ServerException);
zval property_resultDocument_default_value;
ZVAL_NULL(&property_resultDocument_default_value);
zend_string *property_resultDocument_name = zend_string_init("resultDocument", sizeof("resultDocument") - 1, 1);
zend_declare_property_ex(class_entry, property_resultDocument_name, &property_resultDocument_default_value, ZEND_ACC_PROTECTED, NULL);
zend_string_release(property_resultDocument_name);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Exception/ConnectionException.c 0000644 0001751 0000166 00000001650 15014033047 020213 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "ConnectionException_arginfo.h"
zend_class_entry* php_phongo_connectionexception_ce;
void php_phongo_connectionexception_init_ce(INIT_FUNC_ARGS)
{
php_phongo_connectionexception_ce = register_class_MongoDB_Driver_Exception_ConnectionException(php_phongo_runtimeexception_ce);
}
mongodb-2.1.0/src/MongoDB/Exception/ConnectionException_arginfo.h 0000644 0001751 0000166 00000001303 15014033047 021720 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 722ab9f3f73ccb6493c68e6ce4ac888f1aec8955 */
static const zend_function_entry class_MongoDB_Driver_Exception_ConnectionException_methods[] = {
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Exception_ConnectionException(zend_class_entry *class_entry_MongoDB_Driver_Exception_RuntimeException)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "ConnectionException", class_MongoDB_Driver_Exception_ConnectionException_methods);
class_entry = zend_register_internal_class_ex(&ce, class_entry_MongoDB_Driver_Exception_RuntimeException);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Exception/ConnectionTimeoutException.c 0000644 0001751 0000166 00000001716 15014033047 021565 0 ustar /*
* Copyright 2015-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "ConnectionTimeoutException_arginfo.h"
zend_class_entry* php_phongo_connectiontimeoutexception_ce;
void php_phongo_connectiontimeoutexception_init_ce(INIT_FUNC_ARGS)
{
php_phongo_connectiontimeoutexception_ce = register_class_MongoDB_Driver_Exception_ConnectionTimeoutException(php_phongo_connectionexception_ce);
}
mongodb-2.1.0/src/MongoDB/Exception/ConnectionTimeoutException_arginfo.h 0000644 0001751 0000166 00000001417 15014033047 023275 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 60470413296405ec96e76e4331835d8a27dd5ade */
static const zend_function_entry class_MongoDB_Driver_Exception_ConnectionTimeoutException_methods[] = {
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Exception_ConnectionTimeoutException(zend_class_entry *class_entry_MongoDB_Driver_Exception_ConnectionException)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "ConnectionTimeoutException", class_MongoDB_Driver_Exception_ConnectionTimeoutException_methods);
class_entry = zend_register_internal_class_ex(&ce, class_entry_MongoDB_Driver_Exception_ConnectionException);
class_entry->ce_flags |= ZEND_ACC_FINAL;
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Exception/EncryptionException.c 0000644 0001751 0000166 00000001650 15014033047 020246 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "EncryptionException_arginfo.h"
zend_class_entry* php_phongo_encryptionexception_ce;
void php_phongo_encryptionexception_init_ce(INIT_FUNC_ARGS)
{
php_phongo_encryptionexception_ce = register_class_MongoDB_Driver_Exception_EncryptionException(php_phongo_runtimeexception_ce);
}
mongodb-2.1.0/src/MongoDB/Exception/EncryptionException_arginfo.h 0000644 0001751 0000166 00000001303 15014033047 021753 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 432323bdeb13c6e1ce5e0201f0957290f412d26d */
static const zend_function_entry class_MongoDB_Driver_Exception_EncryptionException_methods[] = {
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Exception_EncryptionException(zend_class_entry *class_entry_MongoDB_Driver_Exception_RuntimeException)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "EncryptionException", class_MongoDB_Driver_Exception_EncryptionException_methods);
class_entry = zend_register_internal_class_ex(&ce, class_entry_MongoDB_Driver_Exception_RuntimeException);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Exception/Exception.c 0000644 0001751 0000166 00000001606 15014033047 016174 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include "php_phongo.h"
#include "Exception_arginfo.h"
zend_class_entry* php_phongo_exception_ce;
void php_phongo_exception_init_ce(INIT_FUNC_ARGS)
{
php_phongo_exception_ce = register_class_MongoDB_Driver_Exception_Exception(zend_ce_throwable);
}
mongodb-2.1.0/src/MongoDB/Exception/Exception_arginfo.h 0000644 0001751 0000166 00000001204 15014033047 017700 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 0e426c19c65154d51a01669619579b7ab2b7f60c */
static const zend_function_entry class_MongoDB_Driver_Exception_Exception_methods[] = {
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Exception_Exception(zend_class_entry *class_entry_Throwable)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "Exception", class_MongoDB_Driver_Exception_Exception_methods);
class_entry = zend_register_internal_interface(&ce);
zend_class_implements(class_entry, 1, class_entry_Throwable);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Exception/ExecutionTimeoutException.c 0000644 0001751 0000166 00000001705 15014033047 021427 0 ustar /*
* Copyright 2015-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "ExecutionTimeoutException_arginfo.h"
zend_class_entry* php_phongo_executiontimeoutexception_ce;
void php_phongo_executiontimeoutexception_init_ce(INIT_FUNC_ARGS)
{
php_phongo_executiontimeoutexception_ce = register_class_MongoDB_Driver_Exception_ExecutionTimeoutException(php_phongo_serverexception_ce);
}
mongodb-2.1.0/src/MongoDB/Exception/ExecutionTimeoutException_arginfo.h 0000644 0001751 0000166 00000001403 15014033047 023134 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: e152c0d8d8a6b9d5cd6f43479fb32972ecd585d5 */
static const zend_function_entry class_MongoDB_Driver_Exception_ExecutionTimeoutException_methods[] = {
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Exception_ExecutionTimeoutException(zend_class_entry *class_entry_MongoDB_Driver_Exception_ServerException)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "ExecutionTimeoutException", class_MongoDB_Driver_Exception_ExecutionTimeoutException_methods);
class_entry = zend_register_internal_class_ex(&ce, class_entry_MongoDB_Driver_Exception_ServerException);
class_entry->ce_flags |= ZEND_ACC_FINAL;
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Exception/InvalidArgumentException.c 0000644 0001751 0000166 00000001777 15014033047 021217 0 ustar /*
* Copyright 2015-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include "php_phongo.h"
#include "InvalidArgumentException_arginfo.h"
zend_class_entry* php_phongo_invalidargumentexception_ce;
void php_phongo_invalidargumentexception_init_ce(INIT_FUNC_ARGS)
{
php_phongo_invalidargumentexception_ce = register_class_MongoDB_Driver_Exception_InvalidArgumentException(spl_ce_InvalidArgumentException, php_phongo_exception_ce);
}
mongodb-2.1.0/src/MongoDB/Exception/InvalidArgumentException_arginfo.h 0000644 0001751 0000166 00000001517 15014033047 022721 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 275625c4d5dfb49b5608867b883711c5a4dc2057 */
static const zend_function_entry class_MongoDB_Driver_Exception_InvalidArgumentException_methods[] = {
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Exception_InvalidArgumentException(zend_class_entry *class_entry_InvalidArgumentException, zend_class_entry *class_entry_MongoDB_Driver_Exception_Exception)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "InvalidArgumentException", class_MongoDB_Driver_Exception_InvalidArgumentException_methods);
class_entry = zend_register_internal_class_ex(&ce, class_entry_InvalidArgumentException);
zend_class_implements(class_entry, 1, class_entry_MongoDB_Driver_Exception_Exception);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Exception/LogicException.c 0000644 0001751 0000166 00000001703 15014033047 017150 0 ustar /*
* Copyright 2015-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include "php_phongo.h"
#include "LogicException_arginfo.h"
zend_class_entry* php_phongo_logicexception_ce;
void php_phongo_logicexception_init_ce(INIT_FUNC_ARGS)
{
php_phongo_logicexception_ce = register_class_MongoDB_Driver_Exception_LogicException(spl_ce_LogicException, php_phongo_exception_ce);
}
mongodb-2.1.0/src/MongoDB/Exception/LogicException_arginfo.h 0000644 0001751 0000166 00000001423 15014033047 020661 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: e3bbd956f358c9c22d22617be4d56c4018bd0441 */
static const zend_function_entry class_MongoDB_Driver_Exception_LogicException_methods[] = {
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Exception_LogicException(zend_class_entry *class_entry_LogicException, zend_class_entry *class_entry_MongoDB_Driver_Exception_Exception)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "LogicException", class_MongoDB_Driver_Exception_LogicException_methods);
class_entry = zend_register_internal_class_ex(&ce, class_entry_LogicException);
zend_class_implements(class_entry, 1, class_entry_MongoDB_Driver_Exception_Exception);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Exception/RuntimeException.c 0000644 0001751 0000166 00000003643 15014033047 017543 0 ustar /*
* Copyright 2015-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include "php_array_api.h"
#include "php_phongo.h"
#include "phongo_error.h"
#include "RuntimeException_arginfo.h"
zend_class_entry* php_phongo_runtimeexception_ce;
static bool php_phongo_has_string_array_element(zval* labels, char* label)
{
HashTable* ht_data;
if (Z_TYPE_P(labels) != IS_ARRAY) {
return false;
}
ht_data = HASH_OF(labels);
{
zval* z_label;
ZEND_HASH_FOREACH_VAL_IND(ht_data, z_label)
{
if ((Z_TYPE_P(z_label) == IS_STRING) && (strcmp(Z_STRVAL_P(z_label), label) == 0)) {
return true;
}
}
ZEND_HASH_FOREACH_END();
}
return false;
}
/* Returns whether a specific error label has been set */
static PHP_METHOD(MongoDB_Driver_Exception_RuntimeException, hasErrorLabel)
{
char* label;
size_t label_len;
zval* error_labels;
zval rv;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STRING(label, label_len)
PHONGO_PARSE_PARAMETERS_END();
error_labels = zend_read_property(php_phongo_runtimeexception_ce, Z_OBJ_P(getThis()), ZEND_STRL("errorLabels"), 0, &rv);
RETURN_BOOL(php_phongo_has_string_array_element(error_labels, label));
}
void php_phongo_runtimeexception_init_ce(INIT_FUNC_ARGS)
{
php_phongo_runtimeexception_ce = register_class_MongoDB_Driver_Exception_RuntimeException(spl_ce_RuntimeException, php_phongo_exception_ce);
}
mongodb-2.1.0/src/MongoDB/Exception/RuntimeException_arginfo.h 0000644 0001751 0000166 00000003127 15014033047 021252 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: c895df47a65fcadec95e6f0d4e3f98a0dae827d6 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Exception_RuntimeException_hasErrorLabel, 0, 1, _IS_BOOL, 0)
ZEND_ARG_TYPE_INFO(0, errorLabel, IS_STRING, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_Exception_RuntimeException, hasErrorLabel);
static const zend_function_entry class_MongoDB_Driver_Exception_RuntimeException_methods[] = {
ZEND_ME(MongoDB_Driver_Exception_RuntimeException, hasErrorLabel, arginfo_class_MongoDB_Driver_Exception_RuntimeException_hasErrorLabel, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Exception_RuntimeException(zend_class_entry *class_entry_RuntimeException, zend_class_entry *class_entry_MongoDB_Driver_Exception_Exception)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "RuntimeException", class_MongoDB_Driver_Exception_RuntimeException_methods);
class_entry = zend_register_internal_class_ex(&ce, class_entry_RuntimeException);
zend_class_implements(class_entry, 1, class_entry_MongoDB_Driver_Exception_Exception);
zval property_errorLabels_default_value;
ZVAL_NULL(&property_errorLabels_default_value);
zend_string *property_errorLabels_name = zend_string_init("errorLabels", sizeof("errorLabels") - 1, 1);
zend_declare_property_ex(class_entry, property_errorLabels_name, &property_errorLabels_default_value, ZEND_ACC_PROTECTED, NULL);
zend_string_release(property_errorLabels_name);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Exception/ServerException.c 0000644 0001751 0000166 00000001624 15014033047 017363 0 ustar /*
* Copyright 2018-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "ServerException_arginfo.h"
zend_class_entry* php_phongo_serverexception_ce;
void php_phongo_serverexception_init_ce(INIT_FUNC_ARGS)
{
php_phongo_serverexception_ce = register_class_MongoDB_Driver_Exception_ServerException(php_phongo_runtimeexception_ce);
}
mongodb-2.1.0/src/MongoDB/Exception/ServerException_arginfo.h 0000644 0001751 0000166 00000001263 15014033047 021074 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 62d8bf646599c54ba5a204b38042f80578435322 */
static const zend_function_entry class_MongoDB_Driver_Exception_ServerException_methods[] = {
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Exception_ServerException(zend_class_entry *class_entry_MongoDB_Driver_Exception_RuntimeException)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "ServerException", class_MongoDB_Driver_Exception_ServerException_methods);
class_entry = zend_register_internal_class_ex(&ce, class_entry_MongoDB_Driver_Exception_RuntimeException);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Exception/UnexpectedValueException.c 0000644 0001751 0000166 00000001777 15014033047 021227 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include "php_phongo.h"
#include "UnexpectedValueException_arginfo.h"
zend_class_entry* php_phongo_unexpectedvalueexception_ce;
void php_phongo_unexpectedvalueexception_init_ce(INIT_FUNC_ARGS)
{
php_phongo_unexpectedvalueexception_ce = register_class_MongoDB_Driver_Exception_UnexpectedValueException(spl_ce_UnexpectedValueException, php_phongo_exception_ce);
}
mongodb-2.1.0/src/MongoDB/Exception/UnexpectedValueException_arginfo.h 0000644 0001751 0000166 00000001517 15014033047 022731 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 463206b30ddfa600327f4ba731476ab4196939de */
static const zend_function_entry class_MongoDB_Driver_Exception_UnexpectedValueException_methods[] = {
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Exception_UnexpectedValueException(zend_class_entry *class_entry_UnexpectedValueException, zend_class_entry *class_entry_MongoDB_Driver_Exception_Exception)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Exception", "UnexpectedValueException", class_MongoDB_Driver_Exception_UnexpectedValueException_methods);
class_entry = zend_register_internal_class_ex(&ce, class_entry_UnexpectedValueException);
zend_class_implements(class_entry, 1, class_entry_MongoDB_Driver_Exception_Exception);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Monitoring/CommandFailedEvent.c 0000644 0001751 0000166 00000017702 15014033047 020116 0 ustar /*
* Copyright 2016-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bson/bson.h"
#include
#include
#include "php_phongo.h"
#include "phongo_bson_encode.h"
#include "phongo_error.h"
#include "BSON/ObjectId.h"
#include "MongoDB/Server.h"
#include "CommandFailedEvent_arginfo.h"
zend_class_entry* php_phongo_commandfailedevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_CommandFailedEvent)
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, getCommandName)
{
php_phongo_commandfailedevent_t* intern;
intern = Z_COMMANDFAILEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRING(intern->command_name);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, getDatabaseName)
{
php_phongo_commandfailedevent_t* intern;
intern = Z_COMMANDFAILEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRING(intern->database_name);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, getDurationMicros)
{
php_phongo_commandfailedevent_t* intern;
intern = Z_COMMANDFAILEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_LONG(intern->duration_micros);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, getError)
{
php_phongo_commandfailedevent_t* intern;
intern = Z_COMMANDFAILEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_ZVAL(&intern->z_error, 1, 0);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, getHost)
{
php_phongo_commandfailedevent_t* intern = Z_COMMANDFAILEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRING(intern->host.host);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, getOperationId)
{
php_phongo_commandfailedevent_t* intern;
char operation_id[24];
intern = Z_COMMANDFAILEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
snprintf(operation_id, sizeof(operation_id), "%" PRId64, intern->operation_id);
RETVAL_STRING(operation_id);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, getPort)
{
php_phongo_commandfailedevent_t* intern = Z_COMMANDFAILEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_LONG(intern->host.port);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, getReply)
{
php_phongo_commandfailedevent_t* intern;
php_phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
intern = Z_COMMANDFAILEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
if (!php_phongo_bson_to_zval_ex(intern->reply, &state)) {
zval_ptr_dtor(&state.zchild);
return;
}
RETURN_ZVAL(&state.zchild, 0, 1);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, getRequestId)
{
php_phongo_commandfailedevent_t* intern;
char request_id[24];
intern = Z_COMMANDFAILEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
snprintf(request_id, sizeof(request_id), "%" PRId64, intern->request_id);
RETVAL_STRING(request_id);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, getServiceId)
{
php_phongo_commandfailedevent_t* intern = Z_COMMANDFAILEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
if (!intern->has_service_id) {
RETURN_NULL();
}
phongo_objectid_new(return_value, &intern->service_id);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, getServerConnectionId)
{
php_phongo_commandfailedevent_t* intern = Z_COMMANDFAILEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
/* TODO: Use MONGOC_NO_SERVER_CONNECTION_ID once it is added to libmongoc's public API (CDRIVER-4176) */
if (intern->server_connection_id == -1) {
RETURN_NULL();
}
#if SIZEOF_ZEND_LONG == 4
if (intern->server_connection_id > INT32_MAX || intern->server_connection_id < INT32_MIN) {
zend_error(E_WARNING, "Truncating 64-bit value %" PRId64 " for serverConnectionId", intern->server_connection_id);
}
#endif
RETURN_LONG(intern->server_connection_id);
}
/* MongoDB\Driver\Monitoring\CommandFailedEvent object handlers */
static zend_object_handlers php_phongo_handler_commandfailedevent;
static void php_phongo_commandfailedevent_free_object(zend_object* object)
{
php_phongo_commandfailedevent_t* intern = Z_OBJ_COMMANDFAILEDEVENT(object);
zend_object_std_dtor(&intern->std);
if (!Z_ISUNDEF(intern->z_error)) {
zval_ptr_dtor(&intern->z_error);
}
if (intern->reply) {
bson_destroy(intern->reply);
}
if (intern->command_name) {
efree(intern->command_name);
}
if (intern->database_name) {
efree(intern->database_name);
}
}
static zend_object* php_phongo_commandfailedevent_create_object(zend_class_entry* class_type)
{
php_phongo_commandfailedevent_t* intern = zend_object_alloc(sizeof(php_phongo_commandfailedevent_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_commandfailedevent;
return &intern->std;
}
static HashTable* php_phongo_commandfailedevent_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_commandfailedevent_t* intern;
zval retval = ZVAL_STATIC_INIT;
char operation_id[24], request_id[24];
php_phongo_bson_state reply_state;
PHONGO_BSON_INIT_STATE(reply_state);
intern = Z_OBJ_COMMANDFAILEDEVENT(object);
*is_temp = 1;
array_init_size(&retval, 10);
ADD_ASSOC_STRING(&retval, "host", intern->host.host);
ADD_ASSOC_LONG_EX(&retval, "port", intern->host.port);
ADD_ASSOC_STRING(&retval, "commandName", intern->command_name);
ADD_ASSOC_INT64(&retval, "durationMicros", intern->duration_micros);
ADD_ASSOC_ZVAL_EX(&retval, "error", &intern->z_error);
Z_ADDREF(intern->z_error);
if (!php_phongo_bson_to_zval_ex(intern->reply, &reply_state)) {
zval_ptr_dtor(&reply_state.zchild);
goto done;
}
ADD_ASSOC_ZVAL(&retval, "reply", &reply_state.zchild);
snprintf(operation_id, sizeof(operation_id), "%" PRId64, intern->operation_id);
ADD_ASSOC_STRING(&retval, "operationId", operation_id);
snprintf(request_id, sizeof(request_id), "%" PRId64, intern->request_id);
ADD_ASSOC_STRING(&retval, "requestId", request_id);
if (intern->has_service_id) {
zval service_id;
if (!phongo_objectid_new(&service_id, &intern->service_id)) {
/* Exception should already have been thrown */
goto done;
}
ADD_ASSOC_ZVAL_EX(&retval, "serviceId", &service_id);
} else {
ADD_ASSOC_NULL_EX(&retval, "serviceId");
}
/* TODO: Use MONGOC_NO_SERVER_CONNECTION_ID once it is added to libmongoc's public API (CDRIVER-4176) */
if (intern->server_connection_id == -1) {
ADD_ASSOC_NULL_EX(&retval, "serverConnectionId");
} else {
ADD_ASSOC_LONG_EX(&retval, "serverConnectionId", intern->server_connection_id);
}
done:
return Z_ARRVAL(retval);
}
void php_phongo_commandfailedevent_init_ce(INIT_FUNC_ARGS)
{
php_phongo_commandfailedevent_ce = register_class_MongoDB_Driver_Monitoring_CommandFailedEvent();
php_phongo_commandfailedevent_ce->create_object = php_phongo_commandfailedevent_create_object;
memcpy(&php_phongo_handler_commandfailedevent, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_commandfailedevent.get_debug_info = php_phongo_commandfailedevent_get_debug_info;
php_phongo_handler_commandfailedevent.free_obj = php_phongo_commandfailedevent_free_object;
php_phongo_handler_commandfailedevent.offset = XtOffsetOf(php_phongo_commandfailedevent_t, std);
}
mongodb-2.1.0/src/MongoDB/Monitoring/CommandFailedEvent_arginfo.h 0000644 0001751 0000166 00000012660 15014033047 021626 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 5ee4ff6e75a00cb4456ef87a15dd1d35fa0d3bdd */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getCommandName, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getDatabaseName arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getCommandName
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getDurationMicros, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getError, 0, 0, Exception, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getHost arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getCommandName
#define arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getOperationId arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getCommandName
#define arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getPort arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getDurationMicros
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getReply, 0, 0, IS_OBJECT, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getRequestId arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getCommandName
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getServiceId, 0, 0, MongoDB\\BSON\\ObjectId, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getServerConnectionId, 0, 0, IS_LONG, 1)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, __construct);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, getCommandName);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, getDatabaseName);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, getDurationMicros);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, getError);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, getHost);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, getOperationId);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, getPort);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, getReply);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, getRequestId);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, getServiceId);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandFailedEvent, getServerConnectionId);
static const zend_function_entry class_MongoDB_Driver_Monitoring_CommandFailedEvent_methods[] = {
ZEND_ME(MongoDB_Driver_Monitoring_CommandFailedEvent, __construct, arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandFailedEvent, getCommandName, arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getCommandName, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandFailedEvent, getDatabaseName, arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getDatabaseName, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandFailedEvent, getDurationMicros, arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getDurationMicros, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandFailedEvent, getError, arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getError, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandFailedEvent, getHost, arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getHost, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandFailedEvent, getOperationId, arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getOperationId, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandFailedEvent, getPort, arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getPort, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandFailedEvent, getReply, arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getReply, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandFailedEvent, getRequestId, arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getRequestId, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandFailedEvent, getServiceId, arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getServiceId, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandFailedEvent, getServerConnectionId, arginfo_class_MongoDB_Driver_Monitoring_CommandFailedEvent_getServerConnectionId, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Monitoring_CommandFailedEvent(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Monitoring", "CommandFailedEvent", class_MongoDB_Driver_Monitoring_CommandFailedEvent_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Monitoring/CommandStartedEvent.c 0000644 0001751 0000166 00000016576 15014033047 020350 0 ustar /*
* Copyright 2016-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bson/bson.h"
#include
#include
#include "php_phongo.h"
#include "phongo_bson_encode.h"
#include "phongo_error.h"
#include "BSON/ObjectId.h"
#include "MongoDB/Server.h"
#include "CommandStartedEvent_arginfo.h"
zend_class_entry* php_phongo_commandstartedevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_CommandStartedEvent)
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandStartedEvent, getCommand)
{
php_phongo_commandstartedevent_t* intern;
php_phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
intern = Z_COMMANDSTARTEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
if (!php_phongo_bson_to_zval_ex(intern->command, &state)) {
zval_ptr_dtor(&state.zchild);
return;
}
RETURN_ZVAL(&state.zchild, 0, 1);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandStartedEvent, getCommandName)
{
php_phongo_commandstartedevent_t* intern;
intern = Z_COMMANDSTARTEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRING(intern->command_name);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandStartedEvent, getDatabaseName)
{
php_phongo_commandstartedevent_t* intern;
intern = Z_COMMANDSTARTEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRING(intern->database_name);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandStartedEvent, getHost)
{
php_phongo_commandstartedevent_t* intern = Z_COMMANDSTARTEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRING(intern->host.host);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandStartedEvent, getOperationId)
{
php_phongo_commandstartedevent_t* intern;
char operation_id[24];
intern = Z_COMMANDSTARTEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
snprintf(operation_id, sizeof(operation_id), "%" PRId64, intern->operation_id);
RETVAL_STRING(operation_id);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandStartedEvent, getPort)
{
php_phongo_commandstartedevent_t* intern = Z_COMMANDSTARTEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_LONG(intern->host.port);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandStartedEvent, getRequestId)
{
php_phongo_commandstartedevent_t* intern;
char request_id[24];
intern = Z_COMMANDSTARTEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
snprintf(request_id, sizeof(request_id), "%" PRId64, intern->request_id);
RETVAL_STRING(request_id);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandStartedEvent, getServiceId)
{
php_phongo_commandstartedevent_t* intern = Z_COMMANDSTARTEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
if (!intern->has_service_id) {
RETURN_NULL();
}
phongo_objectid_new(return_value, &intern->service_id);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandStartedEvent, getServerConnectionId)
{
php_phongo_commandstartedevent_t* intern = Z_COMMANDSTARTEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
/* TODO: Use MONGOC_NO_SERVER_CONNECTION_ID once it is added to libmongoc's public API (CDRIVER-4176) */
if (intern->server_connection_id == -1) {
RETURN_NULL();
}
#if SIZEOF_ZEND_LONG == 4
if (intern->server_connection_id > INT32_MAX || intern->server_connection_id < INT32_MIN) {
zend_error(E_WARNING, "Truncating 64-bit value %" PRId64 " for serverConnectionId", intern->server_connection_id);
}
#endif
RETURN_LONG(intern->server_connection_id);
}
/* MongoDB\Driver\Monitoring\CommandStartedEvent object handlers */
static zend_object_handlers php_phongo_handler_commandstartedevent;
static void php_phongo_commandstartedevent_free_object(zend_object* object)
{
php_phongo_commandstartedevent_t* intern = Z_OBJ_COMMANDSTARTEDEVENT(object);
zend_object_std_dtor(&intern->std);
if (intern->command) {
bson_destroy(intern->command);
}
if (intern->command_name) {
efree(intern->command_name);
}
if (intern->database_name) {
efree(intern->database_name);
}
}
static zend_object* php_phongo_commandstartedevent_create_object(zend_class_entry* class_type)
{
php_phongo_commandstartedevent_t* intern = zend_object_alloc(sizeof(php_phongo_commandstartedevent_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_commandstartedevent;
return &intern->std;
}
static HashTable* php_phongo_commandstartedevent_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_commandstartedevent_t* intern;
zval retval = ZVAL_STATIC_INIT;
char operation_id[24], request_id[24];
php_phongo_bson_state command_state;
PHONGO_BSON_INIT_STATE(command_state);
intern = Z_OBJ_COMMANDSTARTEDEVENT(object);
*is_temp = 1;
array_init_size(&retval, 9);
ADD_ASSOC_STRING(&retval, "host", intern->host.host);
ADD_ASSOC_LONG_EX(&retval, "port", intern->host.port);
ADD_ASSOC_STRING(&retval, "commandName", intern->command_name);
ADD_ASSOC_STRING(&retval, "databaseName", intern->database_name);
if (!php_phongo_bson_to_zval_ex(intern->command, &command_state)) {
zval_ptr_dtor(&command_state.zchild);
goto done;
}
ADD_ASSOC_ZVAL(&retval, "command", &command_state.zchild);
snprintf(operation_id, sizeof(operation_id), "%" PRId64, intern->operation_id);
ADD_ASSOC_STRING(&retval, "operationId", operation_id);
snprintf(request_id, sizeof(request_id), "%" PRId64, intern->request_id);
ADD_ASSOC_STRING(&retval, "requestId", request_id);
if (intern->has_service_id) {
zval service_id;
if (!phongo_objectid_new(&service_id, &intern->service_id)) {
/* Exception should already have been thrown */
goto done;
}
ADD_ASSOC_ZVAL_EX(&retval, "serviceId", &service_id);
} else {
ADD_ASSOC_NULL_EX(&retval, "serviceId");
}
/* TODO: Use MONGOC_NO_SERVER_CONNECTION_ID once it is added to libmongoc's public API (CDRIVER-4176) */
if (intern->server_connection_id == -1) {
ADD_ASSOC_NULL_EX(&retval, "serverConnectionId");
} else {
ADD_ASSOC_LONG_EX(&retval, "serverConnectionId", intern->server_connection_id);
}
done:
return Z_ARRVAL(retval);
}
void php_phongo_commandstartedevent_init_ce(INIT_FUNC_ARGS)
{
php_phongo_commandstartedevent_ce = register_class_MongoDB_Driver_Monitoring_CommandStartedEvent();
php_phongo_commandstartedevent_ce->create_object = php_phongo_commandstartedevent_create_object;
memcpy(&php_phongo_handler_commandstartedevent, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_commandstartedevent.get_debug_info = php_phongo_commandstartedevent_get_debug_info;
php_phongo_handler_commandstartedevent.free_obj = php_phongo_commandstartedevent_free_object;
php_phongo_handler_commandstartedevent.offset = XtOffsetOf(php_phongo_commandstartedevent_t, std);
}
mongodb-2.1.0/src/MongoDB/Monitoring/CommandStartedEvent_arginfo.h 0000644 0001751 0000166 00000011261 15014033047 022044 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: c52ae0c5f78d5a61839b24517cc7823f7d9701ad */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent_getCommand, 0, 0, IS_OBJECT, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent_getCommandName, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent_getDatabaseName arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent_getCommandName
#define arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent_getHost arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent_getCommandName
#define arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent_getOperationId arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent_getCommandName
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent_getPort, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent_getRequestId arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent_getCommandName
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent_getServiceId, 0, 0, MongoDB\\BSON\\ObjectId, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent_getServerConnectionId, 0, 0, IS_LONG, 1)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandStartedEvent, __construct);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandStartedEvent, getCommand);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandStartedEvent, getCommandName);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandStartedEvent, getDatabaseName);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandStartedEvent, getHost);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandStartedEvent, getOperationId);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandStartedEvent, getPort);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandStartedEvent, getRequestId);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandStartedEvent, getServiceId);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandStartedEvent, getServerConnectionId);
static const zend_function_entry class_MongoDB_Driver_Monitoring_CommandStartedEvent_methods[] = {
ZEND_ME(MongoDB_Driver_Monitoring_CommandStartedEvent, __construct, arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandStartedEvent, getCommand, arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent_getCommand, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandStartedEvent, getCommandName, arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent_getCommandName, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandStartedEvent, getDatabaseName, arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent_getDatabaseName, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandStartedEvent, getHost, arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent_getHost, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandStartedEvent, getOperationId, arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent_getOperationId, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandStartedEvent, getPort, arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent_getPort, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandStartedEvent, getRequestId, arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent_getRequestId, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandStartedEvent, getServiceId, arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent_getServiceId, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandStartedEvent, getServerConnectionId, arginfo_class_MongoDB_Driver_Monitoring_CommandStartedEvent_getServerConnectionId, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Monitoring_CommandStartedEvent(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Monitoring", "CommandStartedEvent", class_MongoDB_Driver_Monitoring_CommandStartedEvent_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Monitoring/CommandSubscriber.c 0000644 0001751 0000166 00000001631 15014033047 020025 0 ustar /*
* Copyright 2016-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "CommandSubscriber_arginfo.h"
zend_class_entry* php_phongo_commandsubscriber_ce;
void php_phongo_commandsubscriber_init_ce(INIT_FUNC_ARGS)
{
php_phongo_commandsubscriber_ce = register_class_MongoDB_Driver_Monitoring_CommandSubscriber(php_phongo_subscriber_ce);
}
mongodb-2.1.0/src/MongoDB/Monitoring/CommandSubscriber_arginfo.h 0000644 0001751 0000166 00000003770 15014033047 021545 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 9733d9c7cb3460bd7fb85be93cc5c9fbe70e3762 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_CommandSubscriber_commandStarted, 0, 1, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, event, MongoDB\\Driver\\Monitoring\\CommandStartedEvent, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_CommandSubscriber_commandSucceeded, 0, 1, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, event, MongoDB\\Driver\\Monitoring\\CommandSucceededEvent, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_CommandSubscriber_commandFailed, 0, 1, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, event, MongoDB\\Driver\\Monitoring\\CommandFailedEvent, 0)
ZEND_END_ARG_INFO()
static const zend_function_entry class_MongoDB_Driver_Monitoring_CommandSubscriber_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_Driver_Monitoring_CommandSubscriber, commandStarted, arginfo_class_MongoDB_Driver_Monitoring_CommandSubscriber_commandStarted, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_Driver_Monitoring_CommandSubscriber, commandSucceeded, arginfo_class_MongoDB_Driver_Monitoring_CommandSubscriber_commandSucceeded, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_Driver_Monitoring_CommandSubscriber, commandFailed, arginfo_class_MongoDB_Driver_Monitoring_CommandSubscriber_commandFailed, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Monitoring_CommandSubscriber(zend_class_entry *class_entry_MongoDB_Driver_Monitoring_Subscriber)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Monitoring", "CommandSubscriber", class_MongoDB_Driver_Monitoring_CommandSubscriber_methods);
class_entry = zend_register_internal_interface(&ce);
zend_class_implements(class_entry, 1, class_entry_MongoDB_Driver_Monitoring_Subscriber);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Monitoring/CommandSucceededEvent.c 0000644 0001751 0000166 00000017352 15014033047 020617 0 ustar /*
* Copyright 2016-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bson/bson.h"
#include
#include
#include "php_phongo.h"
#include "phongo_bson_encode.h"
#include "phongo_error.h"
#include "BSON/ObjectId.h"
#include "MongoDB/Server.h"
#include "CommandSucceededEvent_arginfo.h"
zend_class_entry* php_phongo_commandsucceededevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_CommandSucceededEvent)
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandSucceededEvent, getCommandName)
{
php_phongo_commandsucceededevent_t* intern;
intern = Z_COMMANDSUCCEEDEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRING(intern->command_name);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandSucceededEvent, getDatabaseName)
{
php_phongo_commandsucceededevent_t* intern;
intern = Z_COMMANDSUCCEEDEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRING(intern->database_name);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandSucceededEvent, getDurationMicros)
{
php_phongo_commandsucceededevent_t* intern;
intern = Z_COMMANDSUCCEEDEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_LONG(intern->duration_micros);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandSucceededEvent, getHost)
{
php_phongo_commandsucceededevent_t* intern = Z_COMMANDSUCCEEDEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRING(intern->host.host);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandSucceededEvent, getOperationId)
{
php_phongo_commandsucceededevent_t* intern;
char operation_id[24];
intern = Z_COMMANDSUCCEEDEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
snprintf(operation_id, sizeof(operation_id), "%" PRId64, intern->operation_id);
RETVAL_STRING(operation_id);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandSucceededEvent, getPort)
{
php_phongo_commandsucceededevent_t* intern = Z_COMMANDSUCCEEDEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_LONG(intern->host.port);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandSucceededEvent, getReply)
{
php_phongo_commandsucceededevent_t* intern;
php_phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
intern = Z_COMMANDSUCCEEDEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
if (!php_phongo_bson_to_zval_ex(intern->reply, &state)) {
zval_ptr_dtor(&state.zchild);
return;
}
RETURN_ZVAL(&state.zchild, 0, 1);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandSucceededEvent, getRequestId)
{
php_phongo_commandsucceededevent_t* intern;
char request_id[24];
intern = Z_COMMANDSUCCEEDEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
snprintf(request_id, sizeof(request_id), "%" PRId64, intern->request_id);
RETVAL_STRING(request_id);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandSucceededEvent, getServiceId)
{
php_phongo_commandsucceededevent_t* intern = Z_COMMANDSUCCEEDEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
if (!intern->has_service_id) {
RETURN_NULL();
}
phongo_objectid_new(return_value, &intern->service_id);
}
static PHP_METHOD(MongoDB_Driver_Monitoring_CommandSucceededEvent, getServerConnectionId)
{
php_phongo_commandsucceededevent_t* intern = Z_COMMANDSUCCEEDEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
/* TODO: Use MONGOC_NO_SERVER_CONNECTION_ID once it is added to libmongoc's public API (CDRIVER-4176) */
if (intern->server_connection_id == -1) {
RETURN_NULL();
}
#if SIZEOF_ZEND_LONG == 4
if (intern->server_connection_id > INT32_MAX || intern->server_connection_id < INT32_MIN) {
zend_error(E_WARNING, "Truncating 64-bit value %" PRId64 " for serverConnectionId", intern->server_connection_id);
}
#endif
RETURN_LONG(intern->server_connection_id);
}
/* MongoDB\Driver\Monitoring\CommandSucceededEvent object handlers */
static zend_object_handlers php_phongo_handler_commandsucceededevent;
static void php_phongo_commandsucceededevent_free_object(zend_object* object)
{
php_phongo_commandsucceededevent_t* intern = Z_OBJ_COMMANDSUCCEEDEDEVENT(object);
zend_object_std_dtor(&intern->std);
if (intern->reply) {
bson_destroy(intern->reply);
}
if (intern->command_name) {
efree(intern->command_name);
}
if (intern->database_name) {
efree(intern->database_name);
}
}
static zend_object* php_phongo_commandsucceededevent_create_object(zend_class_entry* class_type)
{
php_phongo_commandsucceededevent_t* intern = zend_object_alloc(sizeof(php_phongo_commandsucceededevent_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_commandsucceededevent;
return &intern->std;
}
static HashTable* php_phongo_commandsucceededevent_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_commandsucceededevent_t* intern;
zval retval = ZVAL_STATIC_INIT;
char operation_id[24], request_id[24];
php_phongo_bson_state reply_state;
PHONGO_BSON_INIT_STATE(reply_state);
intern = Z_OBJ_COMMANDSUCCEEDEDEVENT(object);
*is_temp = 1;
array_init_size(&retval, 9);
ADD_ASSOC_STRING(&retval, "host", intern->host.host);
ADD_ASSOC_LONG_EX(&retval, "port", intern->host.port);
ADD_ASSOC_STRING(&retval, "commandName", intern->command_name);
ADD_ASSOC_INT64(&retval, "durationMicros", intern->duration_micros);
if (!php_phongo_bson_to_zval_ex(intern->reply, &reply_state)) {
zval_ptr_dtor(&reply_state.zchild);
goto done;
}
ADD_ASSOC_ZVAL(&retval, "reply", &reply_state.zchild);
snprintf(operation_id, sizeof(operation_id), "%" PRId64, intern->operation_id);
ADD_ASSOC_STRING(&retval, "operationId", operation_id);
snprintf(request_id, sizeof(request_id), "%" PRId64, intern->request_id);
ADD_ASSOC_STRING(&retval, "requestId", request_id);
if (intern->has_service_id) {
zval service_id;
if (!phongo_objectid_new(&service_id, &intern->service_id)) {
/* Exception should already have been thrown */
goto done;
}
ADD_ASSOC_ZVAL_EX(&retval, "serviceId", &service_id);
} else {
ADD_ASSOC_NULL_EX(&retval, "serviceId");
}
/* TODO: Use MONGOC_NO_SERVER_CONNECTION_ID once it is added to libmongoc's public API (CDRIVER-4176) */
if (intern->server_connection_id == -1) {
ADD_ASSOC_NULL_EX(&retval, "serverConnectionId");
} else {
ADD_ASSOC_LONG_EX(&retval, "serverConnectionId", intern->server_connection_id);
}
done:
return Z_ARRVAL(retval);
}
void php_phongo_commandsucceededevent_init_ce(INIT_FUNC_ARGS)
{
php_phongo_commandsucceededevent_ce = register_class_MongoDB_Driver_Monitoring_CommandSucceededEvent();
php_phongo_commandsucceededevent_ce->create_object = php_phongo_commandsucceededevent_create_object;
memcpy(&php_phongo_handler_commandsucceededevent, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_commandsucceededevent.get_debug_info = php_phongo_commandsucceededevent_get_debug_info;
php_phongo_handler_commandsucceededevent.free_obj = php_phongo_commandsucceededevent_free_object;
php_phongo_handler_commandsucceededevent.offset = XtOffsetOf(php_phongo_commandsucceededevent_t, std);
}
mongodb-2.1.0/src/MongoDB/Monitoring/CommandSucceededEvent_arginfo.h 0000644 0001751 0000166 00000012310 15014033047 022316 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: d2dfb06b218c9da74356d1b8b322eb79d50e4f90 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getCommandName, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getDatabaseName arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getCommandName
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getDurationMicros, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getHost arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getCommandName
#define arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getOperationId arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getCommandName
#define arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getPort arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getDurationMicros
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getReply, 0, 0, IS_OBJECT, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getRequestId arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getCommandName
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getServiceId, 0, 0, MongoDB\\BSON\\ObjectId, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getServerConnectionId, 0, 0, IS_LONG, 1)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandSucceededEvent, __construct);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandSucceededEvent, getCommandName);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandSucceededEvent, getDatabaseName);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandSucceededEvent, getDurationMicros);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandSucceededEvent, getHost);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandSucceededEvent, getOperationId);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandSucceededEvent, getPort);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandSucceededEvent, getReply);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandSucceededEvent, getRequestId);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandSucceededEvent, getServiceId);
static ZEND_METHOD(MongoDB_Driver_Monitoring_CommandSucceededEvent, getServerConnectionId);
static const zend_function_entry class_MongoDB_Driver_Monitoring_CommandSucceededEvent_methods[] = {
ZEND_ME(MongoDB_Driver_Monitoring_CommandSucceededEvent, __construct, arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandSucceededEvent, getCommandName, arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getCommandName, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandSucceededEvent, getDatabaseName, arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getDatabaseName, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandSucceededEvent, getDurationMicros, arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getDurationMicros, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandSucceededEvent, getHost, arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getHost, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandSucceededEvent, getOperationId, arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getOperationId, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandSucceededEvent, getPort, arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getPort, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandSucceededEvent, getReply, arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getReply, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandSucceededEvent, getRequestId, arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getRequestId, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandSucceededEvent, getServiceId, arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getServiceId, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_CommandSucceededEvent, getServerConnectionId, arginfo_class_MongoDB_Driver_Monitoring_CommandSucceededEvent_getServerConnectionId, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Monitoring_CommandSucceededEvent(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Monitoring", "CommandSucceededEvent", class_MongoDB_Driver_Monitoring_CommandSucceededEvent_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Monitoring/LogSubscriber.c 0000644 0001751 0000166 00000001641 15014033047 017171 0 ustar /*
* Copyright 2016-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mongoc/mongoc.h"
#include
#include "php_phongo.h"
#include "LogSubscriber_arginfo.h"
zend_class_entry* php_phongo_logsubscriber_ce;
void php_phongo_logsubscriber_init_ce(INIT_FUNC_ARGS)
{
php_phongo_logsubscriber_ce = register_class_MongoDB_Driver_Monitoring_LogSubscriber(php_phongo_subscriber_ce);
}
mongodb-2.1.0/src/MongoDB/Monitoring/LogSubscriber_arginfo.h 0000644 0001751 0000166 00000007160 15014033047 020705 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 4920ad21bd26ea586d4322d49bf44c9c3530e494 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_LogSubscriber_log, 0, 3, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, level, IS_LONG, 0)
ZEND_ARG_TYPE_INFO(0, domain, IS_STRING, 0)
ZEND_ARG_TYPE_INFO(0, message, IS_STRING, 0)
ZEND_END_ARG_INFO()
static const zend_function_entry class_MongoDB_Driver_Monitoring_LogSubscriber_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_Driver_Monitoring_LogSubscriber, log, arginfo_class_MongoDB_Driver_Monitoring_LogSubscriber_log, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Monitoring_LogSubscriber(zend_class_entry *class_entry_MongoDB_Driver_Monitoring_Subscriber)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Monitoring", "LogSubscriber", class_MongoDB_Driver_Monitoring_LogSubscriber_methods);
class_entry = zend_register_internal_interface(&ce);
zend_class_implements(class_entry, 1, class_entry_MongoDB_Driver_Monitoring_Subscriber);
zval const_LEVEL_ERROR_value;
ZVAL_LONG(&const_LEVEL_ERROR_value, MONGOC_LOG_LEVEL_ERROR);
zend_string *const_LEVEL_ERROR_name = zend_string_init_interned("LEVEL_ERROR", sizeof("LEVEL_ERROR") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_LEVEL_ERROR_name, &const_LEVEL_ERROR_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_LEVEL_ERROR_name);
ZEND_ASSERT(MONGOC_LOG_LEVEL_ERROR == 0);
zval const_LEVEL_CRITICAL_value;
ZVAL_LONG(&const_LEVEL_CRITICAL_value, MONGOC_LOG_LEVEL_CRITICAL);
zend_string *const_LEVEL_CRITICAL_name = zend_string_init_interned("LEVEL_CRITICAL", sizeof("LEVEL_CRITICAL") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_LEVEL_CRITICAL_name, &const_LEVEL_CRITICAL_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_LEVEL_CRITICAL_name);
ZEND_ASSERT(MONGOC_LOG_LEVEL_CRITICAL == 1);
zval const_LEVEL_WARNING_value;
ZVAL_LONG(&const_LEVEL_WARNING_value, MONGOC_LOG_LEVEL_WARNING);
zend_string *const_LEVEL_WARNING_name = zend_string_init_interned("LEVEL_WARNING", sizeof("LEVEL_WARNING") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_LEVEL_WARNING_name, &const_LEVEL_WARNING_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_LEVEL_WARNING_name);
ZEND_ASSERT(MONGOC_LOG_LEVEL_WARNING == 2);
zval const_LEVEL_MESSAGE_value;
ZVAL_LONG(&const_LEVEL_MESSAGE_value, MONGOC_LOG_LEVEL_MESSAGE);
zend_string *const_LEVEL_MESSAGE_name = zend_string_init_interned("LEVEL_MESSAGE", sizeof("LEVEL_MESSAGE") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_LEVEL_MESSAGE_name, &const_LEVEL_MESSAGE_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_LEVEL_MESSAGE_name);
ZEND_ASSERT(MONGOC_LOG_LEVEL_MESSAGE == 3);
zval const_LEVEL_INFO_value;
ZVAL_LONG(&const_LEVEL_INFO_value, MONGOC_LOG_LEVEL_INFO);
zend_string *const_LEVEL_INFO_name = zend_string_init_interned("LEVEL_INFO", sizeof("LEVEL_INFO") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_LEVEL_INFO_name, &const_LEVEL_INFO_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_LEVEL_INFO_name);
ZEND_ASSERT(MONGOC_LOG_LEVEL_INFO == 4);
zval const_LEVEL_DEBUG_value;
ZVAL_LONG(&const_LEVEL_DEBUG_value, MONGOC_LOG_LEVEL_DEBUG);
zend_string *const_LEVEL_DEBUG_name = zend_string_init_interned("LEVEL_DEBUG", sizeof("LEVEL_DEBUG") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_LEVEL_DEBUG_name, &const_LEVEL_DEBUG_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_LEVEL_DEBUG_name);
ZEND_ASSERT(MONGOC_LOG_LEVEL_DEBUG == 5);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Monitoring/SDAMSubscriber.c 0000644 0001751 0000166 00000001612 15014033047 017172 0 ustar /*
* Copyright 2021-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "SDAMSubscriber_arginfo.h"
zend_class_entry* php_phongo_sdamsubscriber_ce;
void php_phongo_sdamsubscriber_init_ce(INIT_FUNC_ARGS)
{
php_phongo_sdamsubscriber_ce = register_class_MongoDB_Driver_Monitoring_SDAMSubscriber(php_phongo_subscriber_ce);
}
mongodb-2.1.0/src/MongoDB/Monitoring/SDAMSubscriber_arginfo.h 0000644 0001751 0000166 00000011037 15014033047 020706 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 4288cbc04c5e6f432f960e0964ee7022c4a94ac5 */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverChanged, 0, 1, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, event, MongoDB\\Driver\\Monitoring\\ServerChangedEvent, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverClosed, 0, 1, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, event, MongoDB\\Driver\\Monitoring\\ServerClosedEvent, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverOpening, 0, 1, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, event, MongoDB\\Driver\\Monitoring\\ServerOpeningEvent, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverHeartbeatFailed, 0, 1, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, event, MongoDB\\Driver\\Monitoring\\ServerHeartbeatFailedEvent, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverHeartbeatStarted, 0, 1, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, event, MongoDB\\Driver\\Monitoring\\ServerHeartbeatStartedEvent, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverHeartbeatSucceeded, 0, 1, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, event, MongoDB\\Driver\\Monitoring\\ServerHeartbeatSucceededEvent, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_topologyChanged, 0, 1, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, event, MongoDB\\Driver\\Monitoring\\TopologyChangedEvent, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_topologyClosed, 0, 1, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, event, MongoDB\\Driver\\Monitoring\\TopologyClosedEvent, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_topologyOpening, 0, 1, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, event, MongoDB\\Driver\\Monitoring\\TopologyOpeningEvent, 0)
ZEND_END_ARG_INFO()
static const zend_function_entry class_MongoDB_Driver_Monitoring_SDAMSubscriber_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_Driver_Monitoring_SDAMSubscriber, serverChanged, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverChanged, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_Driver_Monitoring_SDAMSubscriber, serverClosed, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverClosed, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_Driver_Monitoring_SDAMSubscriber, serverOpening, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverOpening, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_Driver_Monitoring_SDAMSubscriber, serverHeartbeatFailed, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverHeartbeatFailed, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_Driver_Monitoring_SDAMSubscriber, serverHeartbeatStarted, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverHeartbeatStarted, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_Driver_Monitoring_SDAMSubscriber, serverHeartbeatSucceeded, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverHeartbeatSucceeded, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_Driver_Monitoring_SDAMSubscriber, topologyChanged, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_topologyChanged, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_Driver_Monitoring_SDAMSubscriber, topologyClosed, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_topologyClosed, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_Driver_Monitoring_SDAMSubscriber, topologyOpening, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_topologyOpening, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Monitoring_SDAMSubscriber(zend_class_entry *class_entry_MongoDB_Driver_Monitoring_Subscriber)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Monitoring", "SDAMSubscriber", class_MongoDB_Driver_Monitoring_SDAMSubscriber_methods);
class_entry = zend_register_internal_interface(&ce);
zend_class_implements(class_entry, 1, class_entry_MongoDB_Driver_Monitoring_Subscriber);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Monitoring/ServerChangedEvent.c 0000644 0001751 0000166 00000011756 15014033047 020156 0 ustar /*
* Copyright 2021-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mongoc/mongoc.h"
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "BSON/ObjectId.h"
#include "MongoDB/Server.h"
#include "MongoDB/ServerDescription.h"
#include "ServerChangedEvent_arginfo.h"
zend_class_entry* php_phongo_serverchangedevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_ServerChangedEvent)
/* Returns this event's host */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerChangedEvent, getHost)
{
php_phongo_serverchangedevent_t* intern = Z_SERVERCHANGEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRING(intern->host.host);
}
/* Returns this event's port */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerChangedEvent, getPort)
{
php_phongo_serverchangedevent_t* intern = Z_SERVERCHANGEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_LONG(intern->host.port);
}
/* Returns this event's new description */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerChangedEvent, getNewDescription)
{
php_phongo_serverchangedevent_t* intern = Z_SERVERCHANGEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
phongo_serverdescription_init(return_value, intern->new_server_description);
}
/* Returns this event's previous description */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerChangedEvent, getPreviousDescription)
{
php_phongo_serverchangedevent_t* intern = Z_SERVERCHANGEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
phongo_serverdescription_init(return_value, intern->old_server_description);
}
/* Returns this event's topology id */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerChangedEvent, getTopologyId)
{
php_phongo_serverchangedevent_t* intern = Z_SERVERCHANGEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
phongo_objectid_new(return_value, &intern->topology_id);
}
/* MongoDB\Driver\Monitoring\ServerChangedEvent object handlers */
static zend_object_handlers php_phongo_handler_serverchangedevent;
static void php_phongo_serverchangedevent_free_object(zend_object* object)
{
php_phongo_serverchangedevent_t* intern = Z_OBJ_SERVERCHANGEDEVENT(object);
zend_object_std_dtor(&intern->std);
if (intern->new_server_description) {
mongoc_server_description_destroy(intern->new_server_description);
}
if (intern->old_server_description) {
mongoc_server_description_destroy(intern->old_server_description);
}
}
static zend_object* php_phongo_serverchangedevent_create_object(zend_class_entry* class_type)
{
php_phongo_serverchangedevent_t* intern = zend_object_alloc(sizeof(php_phongo_serverchangedevent_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_serverchangedevent;
return &intern->std;
}
static HashTable* php_phongo_serverchangedevent_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_serverchangedevent_t* intern;
zval retval = ZVAL_STATIC_INIT;
intern = Z_OBJ_SERVERCHANGEDEVENT(object);
*is_temp = 1;
array_init_size(&retval, 4);
ADD_ASSOC_STRING(&retval, "host", intern->host.host);
ADD_ASSOC_LONG_EX(&retval, "port", intern->host.port);
{
zval topology_id;
if (!phongo_objectid_new(&topology_id, &intern->topology_id)) {
/* Exception should already have been thrown */
goto done;
}
ADD_ASSOC_ZVAL_EX(&retval, "topologyId", &topology_id);
}
{
zval new_sd;
phongo_serverdescription_init(&new_sd, intern->new_server_description);
ADD_ASSOC_ZVAL_EX(&retval, "newDescription", &new_sd);
}
{
zval old_sd;
phongo_serverdescription_init(&old_sd, intern->old_server_description);
ADD_ASSOC_ZVAL_EX(&retval, "oldDescription", &old_sd);
}
done:
return Z_ARRVAL(retval);
}
void php_phongo_serverchangedevent_init_ce(INIT_FUNC_ARGS)
{
php_phongo_serverchangedevent_ce = register_class_MongoDB_Driver_Monitoring_ServerChangedEvent();
php_phongo_serverchangedevent_ce->create_object = php_phongo_serverchangedevent_create_object;
memcpy(&php_phongo_handler_serverchangedevent, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_serverchangedevent.get_debug_info = php_phongo_serverchangedevent_get_debug_info;
php_phongo_handler_serverchangedevent.free_obj = php_phongo_serverchangedevent_free_object;
php_phongo_handler_serverchangedevent.offset = XtOffsetOf(php_phongo_serverchangedevent_t, std);
}
mongodb-2.1.0/src/MongoDB/Monitoring/ServerChangedEvent_arginfo.h 0000644 0001751 0000166 00000006103 15014033047 021656 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: d681e2e9936f0846fe8ee7fa6eb25bb218d85902 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerChangedEvent___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerChangedEvent_getPort, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerChangedEvent_getHost, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerChangedEvent_getNewDescription, 0, 0, MongoDB\\Driver\\ServerDescription, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_Monitoring_ServerChangedEvent_getPreviousDescription arginfo_class_MongoDB_Driver_Monitoring_ServerChangedEvent_getNewDescription
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerChangedEvent_getTopologyId, 0, 0, MongoDB\\BSON\\ObjectId, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerChangedEvent, __construct);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerChangedEvent, getPort);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerChangedEvent, getHost);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerChangedEvent, getNewDescription);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerChangedEvent, getPreviousDescription);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerChangedEvent, getTopologyId);
static const zend_function_entry class_MongoDB_Driver_Monitoring_ServerChangedEvent_methods[] = {
ZEND_ME(MongoDB_Driver_Monitoring_ServerChangedEvent, __construct, arginfo_class_MongoDB_Driver_Monitoring_ServerChangedEvent___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerChangedEvent, getPort, arginfo_class_MongoDB_Driver_Monitoring_ServerChangedEvent_getPort, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerChangedEvent, getHost, arginfo_class_MongoDB_Driver_Monitoring_ServerChangedEvent_getHost, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerChangedEvent, getNewDescription, arginfo_class_MongoDB_Driver_Monitoring_ServerChangedEvent_getNewDescription, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerChangedEvent, getPreviousDescription, arginfo_class_MongoDB_Driver_Monitoring_ServerChangedEvent_getPreviousDescription, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerChangedEvent, getTopologyId, arginfo_class_MongoDB_Driver_Monitoring_ServerChangedEvent_getTopologyId, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Monitoring_ServerChangedEvent(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Monitoring", "ServerChangedEvent", class_MongoDB_Driver_Monitoring_ServerChangedEvent_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Monitoring/ServerClosedEvent.c 0000644 0001751 0000166 00000007302 15014033047 020026 0 ustar /*
* Copyright 2021-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "BSON/ObjectId.h"
#include "ServerClosedEvent_arginfo.h"
zend_class_entry* php_phongo_serverclosedevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_ServerClosedEvent)
/* Returns this event's host */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerClosedEvent, getHost)
{
php_phongo_serverclosedevent_t* intern = Z_SERVERCLOSEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRING(intern->host.host);
}
/* Returns this event's port */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerClosedEvent, getPort)
{
php_phongo_serverclosedevent_t* intern = Z_SERVERCLOSEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_LONG(intern->host.port);
}
/* Returns this event's topology id */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerClosedEvent, getTopologyId)
{
php_phongo_serverclosedevent_t* intern = Z_SERVERCLOSEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
phongo_objectid_new(return_value, &intern->topology_id);
}
/* MongoDB\Driver\Monitoring\ServerClosedEvent object handlers */
static zend_object_handlers php_phongo_handler_serverclosedevent;
static void php_phongo_serverclosedevent_free_object(zend_object* object)
{
php_phongo_serverclosedevent_t* intern = Z_OBJ_SERVERCLOSEDEVENT(object);
zend_object_std_dtor(&intern->std);
}
static zend_object* php_phongo_serverclosedevent_create_object(zend_class_entry* class_type)
{
php_phongo_serverclosedevent_t* intern = zend_object_alloc(sizeof(php_phongo_serverclosedevent_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_serverclosedevent;
return &intern->std;
}
static HashTable* php_phongo_serverclosedevent_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_serverclosedevent_t* intern;
zval retval = ZVAL_STATIC_INIT;
intern = Z_OBJ_SERVERCLOSEDEVENT(object);
*is_temp = 1;
array_init_size(&retval, 3);
ADD_ASSOC_STRING(&retval, "host", intern->host.host);
ADD_ASSOC_LONG_EX(&retval, "port", intern->host.port);
{
zval topology_id;
if (!phongo_objectid_new(&topology_id, &intern->topology_id)) {
/* Exception should already have been thrown */
goto done;
}
ADD_ASSOC_ZVAL_EX(&retval, "topologyId", &topology_id);
}
done:
return Z_ARRVAL(retval);
}
void php_phongo_serverclosedevent_init_ce(INIT_FUNC_ARGS)
{
php_phongo_serverclosedevent_ce = register_class_MongoDB_Driver_Monitoring_ServerClosedEvent();
php_phongo_serverclosedevent_ce->create_object = php_phongo_serverclosedevent_create_object;
memcpy(&php_phongo_handler_serverclosedevent, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_serverclosedevent.get_debug_info = php_phongo_serverclosedevent_get_debug_info;
php_phongo_handler_serverclosedevent.free_obj = php_phongo_serverclosedevent_free_object;
php_phongo_handler_serverclosedevent.offset = XtOffsetOf(php_phongo_serverclosedevent_t, std);
}
mongodb-2.1.0/src/MongoDB/Monitoring/ServerClosedEvent_arginfo.h 0000644 0001751 0000166 00000004247 15014033047 021545 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 05a48b4966fb49c82a6ef48b360a93fdc2919f77 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerClosedEvent___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerClosedEvent_getPort, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerClosedEvent_getHost, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerClosedEvent_getTopologyId, 0, 0, MongoDB\\BSON\\ObjectId, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerClosedEvent, __construct);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerClosedEvent, getPort);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerClosedEvent, getHost);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerClosedEvent, getTopologyId);
static const zend_function_entry class_MongoDB_Driver_Monitoring_ServerClosedEvent_methods[] = {
ZEND_ME(MongoDB_Driver_Monitoring_ServerClosedEvent, __construct, arginfo_class_MongoDB_Driver_Monitoring_ServerClosedEvent___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerClosedEvent, getPort, arginfo_class_MongoDB_Driver_Monitoring_ServerClosedEvent_getPort, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerClosedEvent, getHost, arginfo_class_MongoDB_Driver_Monitoring_ServerClosedEvent_getHost, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerClosedEvent, getTopologyId, arginfo_class_MongoDB_Driver_Monitoring_ServerClosedEvent_getTopologyId, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Monitoring_ServerClosedEvent(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Monitoring", "ServerClosedEvent", class_MongoDB_Driver_Monitoring_ServerClosedEvent_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Monitoring/ServerHeartbeatFailedEvent.c 0000644 0001751 0000166 00000011232 15014033047 021616 0 ustar /*
* Copyright 2021-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "ServerHeartbeatFailedEvent_arginfo.h"
zend_class_entry* php_phongo_serverheartbeatfailedevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent)
/* Returns this event's duration in microseconds */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent, getDurationMicros)
{
php_phongo_serverheartbeatfailedevent_t* intern = Z_SERVERHEARTBEATFAILEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_LONG(intern->duration_micros);
}
/* Returns the error associated with the event */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent, getError)
{
php_phongo_serverheartbeatfailedevent_t* intern = Z_SERVERHEARTBEATFAILEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_ZVAL(&intern->z_error, 1, 0);
}
/* Returns this event's host */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent, getHost)
{
php_phongo_serverheartbeatfailedevent_t* intern = Z_SERVERHEARTBEATFAILEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRING(intern->host.host);
}
/* Returns this event's port */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent, getPort)
{
php_phongo_serverheartbeatfailedevent_t* intern = Z_SERVERHEARTBEATFAILEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_LONG(intern->host.port);
}
/* Returns whether this event came from an awaitable hello */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent, isAwaited)
{
php_phongo_serverheartbeatfailedevent_t* intern = Z_SERVERHEARTBEATFAILEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_BOOL(intern->awaited);
}
/* MongoDB\Driver\Monitoring\ServerHeartbeatFailedEvent object handlers */
static zend_object_handlers php_phongo_handler_serverheartbeatfailedevent;
static void php_phongo_serverheartbeatfailedevent_free_object(zend_object* object)
{
php_phongo_serverheartbeatfailedevent_t* intern = Z_OBJ_SERVERHEARTBEATFAILEDEVENT(object);
zend_object_std_dtor(&intern->std);
if (!Z_ISUNDEF(intern->z_error)) {
zval_ptr_dtor(&intern->z_error);
}
}
static zend_object* php_phongo_serverheartbeatfailedevent_create_object(zend_class_entry* class_type)
{
php_phongo_serverheartbeatfailedevent_t* intern = zend_object_alloc(sizeof(php_phongo_serverheartbeatfailedevent_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_serverheartbeatfailedevent;
return &intern->std;
}
static HashTable* php_phongo_serverheartbeatfailedevent_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_serverheartbeatfailedevent_t* intern;
zval retval = ZVAL_STATIC_INIT;
intern = Z_OBJ_SERVERHEARTBEATFAILEDEVENT(object);
*is_temp = 1;
array_init_size(&retval, 5);
ADD_ASSOC_STRING(&retval, "host", intern->host.host);
ADD_ASSOC_LONG_EX(&retval, "port", intern->host.port);
ADD_ASSOC_BOOL_EX(&retval, "awaited", intern->awaited);
ADD_ASSOC_INT64(&retval, "durationMicros", intern->duration_micros);
ADD_ASSOC_ZVAL_EX(&retval, "error", &intern->z_error);
Z_ADDREF(intern->z_error);
return Z_ARRVAL(retval);
}
void php_phongo_serverheartbeatfailedevent_init_ce(INIT_FUNC_ARGS)
{
php_phongo_serverheartbeatfailedevent_ce = register_class_MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent();
php_phongo_serverheartbeatfailedevent_ce->create_object = php_phongo_serverheartbeatfailedevent_create_object;
memcpy(&php_phongo_handler_serverheartbeatfailedevent, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_serverheartbeatfailedevent.get_debug_info = php_phongo_serverheartbeatfailedevent_get_debug_info;
php_phongo_handler_serverheartbeatfailedevent.free_obj = php_phongo_serverheartbeatfailedevent_free_object;
php_phongo_handler_serverheartbeatfailedevent.offset = XtOffsetOf(php_phongo_serverheartbeatfailedevent_t, std);
}
mongodb-2.1.0/src/MongoDB/Monitoring/ServerHeartbeatFailedEvent_arginfo.h 0000644 0001751 0000166 00000006274 15014033047 023342 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: ba0a81f27f99579e332ef8d3a3a477b3ebe1ec31 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent_getDurationMicros, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent_getError, 0, 0, Exception, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent_getPort arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent_getDurationMicros
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent_getHost, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent_isAwaited, 0, 0, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent, __construct);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent, getDurationMicros);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent, getError);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent, getPort);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent, getHost);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent, isAwaited);
static const zend_function_entry class_MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent_methods[] = {
ZEND_ME(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent, __construct, arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent, getDurationMicros, arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent_getDurationMicros, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent, getError, arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent_getError, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent, getPort, arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent_getPort, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent, getHost, arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent_getHost, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent, isAwaited, arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent_isAwaited, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Monitoring", "ServerHeartbeatFailedEvent", class_MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Monitoring/ServerHeartbeatStartedEvent.c 0000644 0001751 0000166 00000007557 15014033047 022057 0 ustar /*
* Copyright 2021-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "ServerHeartbeatStartedEvent_arginfo.h"
zend_class_entry* php_phongo_serverheartbeatstartedevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent)
/* Returns this event's host */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent, getHost)
{
php_phongo_serverheartbeatstartedevent_t* intern = Z_SERVERHEARTBEATSTARTEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRING(intern->host.host);
}
/* Returns this event's port */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent, getPort)
{
php_phongo_serverheartbeatstartedevent_t* intern = Z_SERVERHEARTBEATSTARTEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_LONG(intern->host.port);
}
/* Returns whether this event came from an awaitable hello */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent, isAwaited)
{
php_phongo_serverheartbeatstartedevent_t* intern = Z_SERVERHEARTBEATSTARTEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_BOOL(intern->awaited);
}
/* MongoDB\Driver\Monitoring\ServerHeartbeatStartedEvent object handlers */
static zend_object_handlers php_phongo_handler_serverheartbeatstartedevent;
static void php_phongo_serverheartbeatstartedevent_free_object(zend_object* object)
{
php_phongo_serverheartbeatstartedevent_t* intern = Z_OBJ_SERVERHEARTBEATSTARTEDEVENT(object);
zend_object_std_dtor(&intern->std);
}
static zend_object* php_phongo_serverheartbeatstartedevent_create_object(zend_class_entry* class_type)
{
php_phongo_serverheartbeatstartedevent_t* intern = zend_object_alloc(sizeof(php_phongo_serverheartbeatstartedevent_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_serverheartbeatstartedevent;
return &intern->std;
}
static HashTable* php_phongo_serverheartbeatstartedevent_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_serverheartbeatstartedevent_t* intern;
zval retval = ZVAL_STATIC_INIT;
intern = Z_OBJ_SERVERHEARTBEATSTARTEDEVENT(object);
*is_temp = 1;
array_init_size(&retval, 4);
ADD_ASSOC_STRING(&retval, "host", intern->host.host);
ADD_ASSOC_LONG_EX(&retval, "port", intern->host.port);
ADD_ASSOC_BOOL_EX(&retval, "awaited", intern->awaited);
return Z_ARRVAL(retval);
}
void php_phongo_serverheartbeatstartedevent_init_ce(INIT_FUNC_ARGS)
{
php_phongo_serverheartbeatstartedevent_ce = register_class_MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent();
php_phongo_serverheartbeatstartedevent_ce->create_object = php_phongo_serverheartbeatstartedevent_create_object;
memcpy(&php_phongo_handler_serverheartbeatstartedevent, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_serverheartbeatstartedevent.get_debug_info = php_phongo_serverheartbeatstartedevent_get_debug_info;
php_phongo_handler_serverheartbeatstartedevent.free_obj = php_phongo_serverheartbeatstartedevent_free_object;
php_phongo_handler_serverheartbeatstartedevent.offset = XtOffsetOf(php_phongo_serverheartbeatstartedevent_t, std);
return;
}
mongodb-2.1.0/src/MongoDB/Monitoring/ServerHeartbeatStartedEvent_arginfo.h 0000644 0001751 0000166 00000004521 15014033047 023555 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 7cb420cf908d682f770a9dbc20473e075af9ce53 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent_getPort, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent_getHost, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent_isAwaited, 0, 0, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent, __construct);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent, getPort);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent, getHost);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent, isAwaited);
static const zend_function_entry class_MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent_methods[] = {
ZEND_ME(MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent, __construct, arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent, getPort, arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent_getPort, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent, getHost, arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent_getHost, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent, isAwaited, arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent_isAwaited, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Monitoring", "ServerHeartbeatStartedEvent", class_MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Monitoring/ServerHeartbeatSucceededEvent.c 0000644 0001751 0000166 00000012200 15014033047 022312 0 ustar /*
* Copyright 2021-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "ServerHeartbeatSucceededEvent_arginfo.h"
zend_class_entry* php_phongo_serverheartbeatsucceededevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent)
/* Returns this event's duration in microseconds */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent, getDurationMicros)
{
php_phongo_serverheartbeatsucceededevent_t* intern = Z_SERVERHEARTBEATSUCCEEDEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_LONG(intern->duration_micros);
}
/* Returns this event's host */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent, getHost)
{
php_phongo_serverheartbeatsucceededevent_t* intern = Z_SERVERHEARTBEATSUCCEEDEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRING(intern->host.host);
}
/* Returns this event's port */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent, getPort)
{
php_phongo_serverheartbeatsucceededevent_t* intern = Z_SERVERHEARTBEATSUCCEEDEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_LONG(intern->host.port);
}
/* Returns this event's reply */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent, getReply)
{
php_phongo_serverheartbeatsucceededevent_t* intern = Z_SERVERHEARTBEATSUCCEEDEDEVENT_OBJ_P(getThis());
php_phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
PHONGO_PARSE_PARAMETERS_NONE();
if (!php_phongo_bson_to_zval_ex(intern->reply, &state)) {
zval_ptr_dtor(&state.zchild);
return;
}
RETURN_ZVAL(&state.zchild, 0, 1);
}
/* Returns whether this event came from an awaitable hello */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent, isAwaited)
{
php_phongo_serverheartbeatsucceededevent_t* intern = Z_SERVERHEARTBEATSUCCEEDEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_BOOL(intern->awaited);
}
/* MongoDB\Driver\Monitoring\ServerHeartbeatSucceededEvent object handlers */
static zend_object_handlers php_phongo_handler_serverheartbeatsucceededevent;
static void php_phongo_serverheartbeatsucceededevent_free_object(zend_object* object)
{
php_phongo_serverheartbeatsucceededevent_t* intern = Z_OBJ_SERVERHEARTBEATSUCCEEDEDEVENT(object);
zend_object_std_dtor(&intern->std);
if (intern->reply) {
bson_destroy(intern->reply);
}
}
static zend_object* php_phongo_serverheartbeatsucceededevent_create_object(zend_class_entry* class_type)
{
php_phongo_serverheartbeatsucceededevent_t* intern = zend_object_alloc(sizeof(php_phongo_serverheartbeatsucceededevent_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_serverheartbeatsucceededevent;
return &intern->std;
}
static HashTable* php_phongo_serverheartbeatsucceededevent_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_serverheartbeatsucceededevent_t* intern;
zval retval = ZVAL_STATIC_INIT;
php_phongo_bson_state reply_state;
PHONGO_BSON_INIT_STATE(reply_state);
intern = Z_OBJ_SERVERHEARTBEATSUCCEEDEDEVENT(object);
*is_temp = 1;
array_init_size(&retval, 4);
ADD_ASSOC_STRING(&retval, "host", intern->host.host);
ADD_ASSOC_LONG_EX(&retval, "port", intern->host.port);
ADD_ASSOC_BOOL_EX(&retval, "awaited", intern->awaited);
ADD_ASSOC_INT64(&retval, "durationMicros", intern->duration_micros);
if (!php_phongo_bson_to_zval_ex(intern->reply, &reply_state)) {
zval_ptr_dtor(&reply_state.zchild);
goto done;
}
ADD_ASSOC_ZVAL(&retval, "reply", &reply_state.zchild);
done:
return Z_ARRVAL(retval);
}
void php_phongo_serverheartbeatsucceededevent_init_ce(INIT_FUNC_ARGS)
{
php_phongo_serverheartbeatsucceededevent_ce = register_class_MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent();
php_phongo_serverheartbeatsucceededevent_ce->create_object = php_phongo_serverheartbeatsucceededevent_create_object;
memcpy(&php_phongo_handler_serverheartbeatsucceededevent, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_serverheartbeatsucceededevent.get_debug_info = php_phongo_serverheartbeatsucceededevent_get_debug_info;
php_phongo_handler_serverheartbeatsucceededevent.free_obj = php_phongo_serverheartbeatsucceededevent_free_object;
php_phongo_handler_serverheartbeatsucceededevent.offset = XtOffsetOf(php_phongo_serverheartbeatsucceededevent_t, std);
return;
}
mongodb-2.1.0/src/MongoDB/Monitoring/ServerHeartbeatSucceededEvent_arginfo.h 0000644 0001751 0000166 00000006424 15014033047 024037 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: dce5c76853a5c0a532be89796806527d37d018a1 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent_getDurationMicros, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent_getReply, 0, 0, IS_OBJECT, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent_getPort arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent_getDurationMicros
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent_getHost, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent_isAwaited, 0, 0, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent, __construct);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent, getDurationMicros);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent, getReply);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent, getPort);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent, getHost);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent, isAwaited);
static const zend_function_entry class_MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent_methods[] = {
ZEND_ME(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent, __construct, arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent, getDurationMicros, arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent_getDurationMicros, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent, getReply, arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent_getReply, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent, getPort, arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent_getPort, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent, getHost, arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent_getHost, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent, isAwaited, arginfo_class_MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent_isAwaited, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Monitoring", "ServerHeartbeatSucceededEvent", class_MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Monitoring/ServerOpeningEvent.c 0000644 0001751 0000166 00000007347 15014033047 020225 0 ustar /*
* Copyright 2021-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "BSON/ObjectId.h"
#include "ServerOpeningEvent_arginfo.h"
zend_class_entry* php_phongo_serveropeningevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_ServerOpeningEvent)
/* Returns this event's host */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerOpeningEvent, getHost)
{
php_phongo_serveropeningevent_t* intern = Z_SERVEROPENINGEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRING(intern->host.host);
}
/* Returns this event's port */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerOpeningEvent, getPort)
{
php_phongo_serveropeningevent_t* intern = Z_SERVEROPENINGEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_LONG(intern->host.port);
}
/* Returns this event's topology id */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerOpeningEvent, getTopologyId)
{
php_phongo_serveropeningevent_t* intern = Z_SERVEROPENINGEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
phongo_objectid_new(return_value, &intern->topology_id);
}
/* MongoDB\Driver\Monitoring\ServerOpeningEvent object handlers */
static zend_object_handlers php_phongo_handler_serveropeningevent;
static void php_phongo_serveropeningevent_free_object(zend_object* object)
{
php_phongo_serveropeningevent_t* intern = Z_OBJ_SERVEROPENINGEVENT(object);
zend_object_std_dtor(&intern->std);
}
static zend_object* php_phongo_serveropeningevent_create_object(zend_class_entry* class_type)
{
php_phongo_serveropeningevent_t* intern = zend_object_alloc(sizeof(php_phongo_serveropeningevent_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_serveropeningevent;
return &intern->std;
}
static HashTable* php_phongo_serveropeningevent_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_serveropeningevent_t* intern;
zval retval = ZVAL_STATIC_INIT;
intern = Z_OBJ_SERVEROPENINGEVENT(object);
*is_temp = 1;
array_init_size(&retval, 3);
ADD_ASSOC_STRING(&retval, "host", intern->host.host);
ADD_ASSOC_LONG_EX(&retval, "port", intern->host.port);
{
zval topology_id;
if (!phongo_objectid_new(&topology_id, &intern->topology_id)) {
/* Exception should already have been thrown */
goto done;
}
ADD_ASSOC_ZVAL_EX(&retval, "topologyId", &topology_id);
}
done:
return Z_ARRVAL(retval);
}
void php_phongo_serveropeningevent_init_ce(INIT_FUNC_ARGS)
{
php_phongo_serveropeningevent_ce = register_class_MongoDB_Driver_Monitoring_ServerOpeningEvent();
php_phongo_serveropeningevent_ce->create_object = php_phongo_serveropeningevent_create_object;
memcpy(&php_phongo_handler_serveropeningevent, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_serveropeningevent.get_debug_info = php_phongo_serveropeningevent_get_debug_info;
php_phongo_handler_serveropeningevent.free_obj = php_phongo_serveropeningevent_free_object;
php_phongo_handler_serveropeningevent.offset = XtOffsetOf(php_phongo_serveropeningevent_t, std);
}
mongodb-2.1.0/src/MongoDB/Monitoring/ServerOpeningEvent_arginfo.h 0000644 0001751 0000166 00000004273 15014033047 021732 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 017f3508070fe14083d8839f97ad0d6788470639 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerOpeningEvent___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerOpeningEvent_getPort, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerOpeningEvent_getHost, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_ServerOpeningEvent_getTopologyId, 0, 0, MongoDB\\BSON\\ObjectId, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerOpeningEvent, __construct);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerOpeningEvent, getPort);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerOpeningEvent, getHost);
static ZEND_METHOD(MongoDB_Driver_Monitoring_ServerOpeningEvent, getTopologyId);
static const zend_function_entry class_MongoDB_Driver_Monitoring_ServerOpeningEvent_methods[] = {
ZEND_ME(MongoDB_Driver_Monitoring_ServerOpeningEvent, __construct, arginfo_class_MongoDB_Driver_Monitoring_ServerOpeningEvent___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerOpeningEvent, getPort, arginfo_class_MongoDB_Driver_Monitoring_ServerOpeningEvent_getPort, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerOpeningEvent, getHost, arginfo_class_MongoDB_Driver_Monitoring_ServerOpeningEvent_getHost, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_ServerOpeningEvent, getTopologyId, arginfo_class_MongoDB_Driver_Monitoring_ServerOpeningEvent_getTopologyId, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Monitoring_ServerOpeningEvent(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Monitoring", "ServerOpeningEvent", class_MongoDB_Driver_Monitoring_ServerOpeningEvent_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Monitoring/Subscriber.c 0000644 0001751 0000166 00000001536 15014033047 016532 0 ustar /*
* Copyright 2016-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include "php_phongo.h"
#include "Subscriber_arginfo.h"
zend_class_entry* php_phongo_subscriber_ce;
void php_phongo_subscriber_init_ce(INIT_FUNC_ARGS)
{
php_phongo_subscriber_ce = register_class_MongoDB_Driver_Monitoring_Subscriber();
}
mongodb-2.1.0/src/MongoDB/Monitoring/Subscriber_arginfo.h 0000644 0001751 0000166 00000001052 15014033047 020235 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: f2e7d8f61aa5359716d9c2186c24ba68db5e96b4 */
static const zend_function_entry class_MongoDB_Driver_Monitoring_Subscriber_methods[] = {
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Monitoring_Subscriber(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Monitoring", "Subscriber", class_MongoDB_Driver_Monitoring_Subscriber_methods);
class_entry = zend_register_internal_interface(&ce);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Monitoring/TopologyChangedEvent.c 0000644 0001751 0000166 00000010700 15014033047 020510 0 ustar /*
* Copyright 2021-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mongoc/mongoc.h"
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "BSON/ObjectId.h"
#include "MongoDB/TopologyDescription.h"
#include "TopologyChangedEvent_arginfo.h"
zend_class_entry* php_phongo_topologychangedevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_TopologyChangedEvent)
/* Returns this event's new description */
static PHP_METHOD(MongoDB_Driver_Monitoring_TopologyChangedEvent, getNewDescription)
{
php_phongo_topologychangedevent_t* intern = Z_TOPOLOGYCHANGEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
phongo_topologydescription_init(return_value, intern->new_topology_description);
}
/* Returns this event's previous description */
static PHP_METHOD(MongoDB_Driver_Monitoring_TopologyChangedEvent, getPreviousDescription)
{
php_phongo_topologychangedevent_t* intern = Z_TOPOLOGYCHANGEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
phongo_topologydescription_init(return_value, intern->old_topology_description);
}
/* Returns this event's topology id */
static PHP_METHOD(MongoDB_Driver_Monitoring_TopologyChangedEvent, getTopologyId)
{
php_phongo_topologychangedevent_t* intern = Z_TOPOLOGYCHANGEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
phongo_objectid_new(return_value, &intern->topology_id);
}
/* MongoDB\Driver\Monitoring\TopologyChangedEvent object handlers */
static zend_object_handlers php_phongo_handler_topologychangedevent;
static void php_phongo_topologychangedevent_free_object(zend_object* object)
{
php_phongo_topologychangedevent_t* intern = Z_OBJ_TOPOLOGYCHANGEDEVENT(object);
zend_object_std_dtor(&intern->std);
if (intern->new_topology_description) {
mongoc_topology_description_destroy(intern->new_topology_description);
}
if (intern->old_topology_description) {
mongoc_topology_description_destroy(intern->old_topology_description);
}
}
static zend_object* php_phongo_topologychangedevent_create_object(zend_class_entry* class_type)
{
php_phongo_topologychangedevent_t* intern = zend_object_alloc(sizeof(php_phongo_topologychangedevent_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_topologychangedevent;
return &intern->std;
}
static HashTable* php_phongo_topologychangedevent_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_topologychangedevent_t* intern;
zval retval = ZVAL_STATIC_INIT;
intern = Z_OBJ_TOPOLOGYCHANGEDEVENT(object);
*is_temp = 1;
array_init_size(&retval, 3);
{
zval topology_id;
if (!phongo_objectid_new(&topology_id, &intern->topology_id)) {
/* Exception should already have been thrown */
goto done;
}
ADD_ASSOC_ZVAL_EX(&retval, "topologyId", &topology_id);
}
{
zval new_td;
phongo_topologydescription_init(&new_td, intern->new_topology_description);
ADD_ASSOC_ZVAL_EX(&retval, "newDescription", &new_td);
}
{
zval old_td;
phongo_topologydescription_init(&old_td, intern->old_topology_description);
ADD_ASSOC_ZVAL_EX(&retval, "oldDescription", &old_td);
}
done:
return Z_ARRVAL(retval);
}
void php_phongo_topologychangedevent_init_ce(INIT_FUNC_ARGS)
{
php_phongo_topologychangedevent_ce = register_class_MongoDB_Driver_Monitoring_TopologyChangedEvent();
php_phongo_topologychangedevent_ce->create_object = php_phongo_topologychangedevent_create_object;
memcpy(&php_phongo_handler_topologychangedevent, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_topologychangedevent.get_debug_info = php_phongo_topologychangedevent_get_debug_info;
php_phongo_handler_topologychangedevent.free_obj = php_phongo_topologychangedevent_free_object;
php_phongo_handler_topologychangedevent.offset = XtOffsetOf(php_phongo_topologychangedevent_t, std);
}
mongodb-2.1.0/src/MongoDB/Monitoring/TopologyChangedEvent_arginfo.h 0000644 0001751 0000166 00000004551 15014033047 022231 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 20071882771d0743a38efc1d7d7d19659cfb637b */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_TopologyChangedEvent___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_TopologyChangedEvent_getNewDescription, 0, 0, MongoDB\\Driver\\TopologyDescription, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_Monitoring_TopologyChangedEvent_getPreviousDescription arginfo_class_MongoDB_Driver_Monitoring_TopologyChangedEvent_getNewDescription
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_TopologyChangedEvent_getTopologyId, 0, 0, MongoDB\\BSON\\ObjectId, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_Monitoring_TopologyChangedEvent, __construct);
static ZEND_METHOD(MongoDB_Driver_Monitoring_TopologyChangedEvent, getNewDescription);
static ZEND_METHOD(MongoDB_Driver_Monitoring_TopologyChangedEvent, getPreviousDescription);
static ZEND_METHOD(MongoDB_Driver_Monitoring_TopologyChangedEvent, getTopologyId);
static const zend_function_entry class_MongoDB_Driver_Monitoring_TopologyChangedEvent_methods[] = {
ZEND_ME(MongoDB_Driver_Monitoring_TopologyChangedEvent, __construct, arginfo_class_MongoDB_Driver_Monitoring_TopologyChangedEvent___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_TopologyChangedEvent, getNewDescription, arginfo_class_MongoDB_Driver_Monitoring_TopologyChangedEvent_getNewDescription, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_TopologyChangedEvent, getPreviousDescription, arginfo_class_MongoDB_Driver_Monitoring_TopologyChangedEvent_getPreviousDescription, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_TopologyChangedEvent, getTopologyId, arginfo_class_MongoDB_Driver_Monitoring_TopologyChangedEvent_getTopologyId, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Monitoring_TopologyChangedEvent(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Monitoring", "TopologyChangedEvent", class_MongoDB_Driver_Monitoring_TopologyChangedEvent_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Monitoring/TopologyClosedEvent.c 0000644 0001751 0000166 00000006214 15014033047 020375 0 ustar /*
* Copyright 2021-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "BSON/ObjectId.h"
#include "TopologyClosedEvent_arginfo.h"
zend_class_entry* php_phongo_topologyclosedevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_TopologyClosedEvent)
/* Returns this event's topology id */
static PHP_METHOD(MongoDB_Driver_Monitoring_TopologyClosedEvent, getTopologyId)
{
php_phongo_topologyclosedevent_t* intern = Z_TOPOLOGYCLOSEDEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
phongo_objectid_new(return_value, &intern->topology_id);
}
/* MongoDB\Driver\Monitoring\TopologyClosedEvent object handlers */
static zend_object_handlers php_phongo_handler_topologyclosedevent;
static void php_phongo_topologyclosedevent_free_object(zend_object* object)
{
php_phongo_topologyclosedevent_t* intern = Z_OBJ_TOPOLOGYCLOSEDEVENT(object);
zend_object_std_dtor(&intern->std);
}
static zend_object* php_phongo_topologyclosedevent_create_object(zend_class_entry* class_type)
{
php_phongo_topologyclosedevent_t* intern = zend_object_alloc(sizeof(php_phongo_topologyclosedevent_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_topologyclosedevent;
return &intern->std;
}
static HashTable* php_phongo_topologyclosedevent_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_topologyclosedevent_t* intern;
zval retval = ZVAL_STATIC_INIT;
intern = Z_OBJ_TOPOLOGYCLOSEDEVENT(object);
*is_temp = 1;
array_init_size(&retval, 1);
{
zval topology_id;
if (!phongo_objectid_new(&topology_id, &intern->topology_id)) {
/* Exception should already have been thrown */
goto done;
}
ADD_ASSOC_ZVAL_EX(&retval, "topologyId", &topology_id);
}
done:
return Z_ARRVAL(retval);
}
void php_phongo_topologyclosedevent_init_ce(INIT_FUNC_ARGS)
{
php_phongo_topologyclosedevent_ce = register_class_MongoDB_Driver_Monitoring_TopologyClosedEvent();
php_phongo_topologyclosedevent_ce->create_object = php_phongo_topologyclosedevent_create_object;
memcpy(&php_phongo_handler_topologyclosedevent, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_topologyclosedevent.get_debug_info = php_phongo_topologyclosedevent_get_debug_info;
php_phongo_handler_topologyclosedevent.free_obj = php_phongo_topologyclosedevent_free_object;
php_phongo_handler_topologyclosedevent.offset = XtOffsetOf(php_phongo_topologyclosedevent_t, std);
}
mongodb-2.1.0/src/MongoDB/Monitoring/TopologyClosedEvent_arginfo.h 0000644 0001751 0000166 00000002701 15014033047 022104 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: c636ee276d6ebc18186a6ef4b8f67c48f5b4c29c */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_TopologyClosedEvent___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_TopologyClosedEvent_getTopologyId, 0, 0, MongoDB\\BSON\\ObjectId, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_Monitoring_TopologyClosedEvent, __construct);
static ZEND_METHOD(MongoDB_Driver_Monitoring_TopologyClosedEvent, getTopologyId);
static const zend_function_entry class_MongoDB_Driver_Monitoring_TopologyClosedEvent_methods[] = {
ZEND_ME(MongoDB_Driver_Monitoring_TopologyClosedEvent, __construct, arginfo_class_MongoDB_Driver_Monitoring_TopologyClosedEvent___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_TopologyClosedEvent, getTopologyId, arginfo_class_MongoDB_Driver_Monitoring_TopologyClosedEvent_getTopologyId, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Monitoring_TopologyClosedEvent(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Monitoring", "TopologyClosedEvent", class_MongoDB_Driver_Monitoring_TopologyClosedEvent_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Monitoring/TopologyOpeningEvent.c 0000644 0001751 0000166 00000006253 15014033047 020566 0 ustar /*
* Copyright 2021-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "BSON/ObjectId.h"
#include "TopologyOpeningEvent_arginfo.h"
zend_class_entry* php_phongo_topologyopeningevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_TopologyOpeningEvent)
/* Returns this event's topology id */
static PHP_METHOD(MongoDB_Driver_Monitoring_TopologyOpeningEvent, getTopologyId)
{
php_phongo_topologyopeningevent_t* intern = Z_TOPOLOGYOPENINGEVENT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
phongo_objectid_new(return_value, &intern->topology_id);
}
/* MongoDB\Driver\Monitoring\TopologyOpeningEvent object handlers */
static zend_object_handlers php_phongo_handler_topologyopeningevent;
static void php_phongo_topologyopeningevent_free_object(zend_object* object)
{
php_phongo_topologyopeningevent_t* intern = Z_OBJ_TOPOLOGYOPENINGEVENT(object);
zend_object_std_dtor(&intern->std);
}
static zend_object* php_phongo_topologyopeningevent_create_object(zend_class_entry* class_type)
{
php_phongo_topologyopeningevent_t* intern = zend_object_alloc(sizeof(php_phongo_topologyopeningevent_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_topologyopeningevent;
return &intern->std;
}
static HashTable* php_phongo_topologyopeningevent_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_topologyopeningevent_t* intern;
zval retval = ZVAL_STATIC_INIT;
intern = Z_OBJ_TOPOLOGYOPENINGEVENT(object);
*is_temp = 1;
array_init_size(&retval, 1);
{
zval topology_id;
if (!phongo_objectid_new(&topology_id, &intern->topology_id)) {
/* Exception should already have been thrown */
goto done;
}
ADD_ASSOC_ZVAL_EX(&retval, "topologyId", &topology_id);
}
done:
return Z_ARRVAL(retval);
}
void php_phongo_topologyopeningevent_init_ce(INIT_FUNC_ARGS)
{
php_phongo_topologyopeningevent_ce = register_class_MongoDB_Driver_Monitoring_TopologyOpeningEvent();
php_phongo_topologyopeningevent_ce->create_object = php_phongo_topologyopeningevent_create_object;
memcpy(&php_phongo_handler_topologyopeningevent, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_topologyopeningevent.get_debug_info = php_phongo_topologyopeningevent_get_debug_info;
php_phongo_handler_topologyopeningevent.free_obj = php_phongo_topologyopeningevent_free_object;
php_phongo_handler_topologyopeningevent.offset = XtOffsetOf(php_phongo_topologyopeningevent_t, std);
}
mongodb-2.1.0/src/MongoDB/Monitoring/TopologyOpeningEvent_arginfo.h 0000644 0001751 0000166 00000002715 15014033047 022277 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 6ab1a9ad8b25b5d09ce12c1b0fa0e69885432d6f */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_TopologyOpeningEvent___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Monitoring_TopologyOpeningEvent_getTopologyId, 0, 0, MongoDB\\BSON\\ObjectId, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_Monitoring_TopologyOpeningEvent, __construct);
static ZEND_METHOD(MongoDB_Driver_Monitoring_TopologyOpeningEvent, getTopologyId);
static const zend_function_entry class_MongoDB_Driver_Monitoring_TopologyOpeningEvent_methods[] = {
ZEND_ME(MongoDB_Driver_Monitoring_TopologyOpeningEvent, __construct, arginfo_class_MongoDB_Driver_Monitoring_TopologyOpeningEvent___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Monitoring_TopologyOpeningEvent, getTopologyId, arginfo_class_MongoDB_Driver_Monitoring_TopologyOpeningEvent_getTopologyId, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Monitoring_TopologyOpeningEvent(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver\\Monitoring", "TopologyOpeningEvent", class_MongoDB_Driver_Monitoring_TopologyOpeningEvent_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Monitoring/functions.c 0000644 0001751 0000166 00000006067 15014033047 016443 0 ustar /*
* Copyright 2016-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mongoc/mongoc.h"
#include
#include "php_phongo.h"
#include "phongo_apm.h"
#include "phongo_error.h"
#include "phongo_log.h"
ZEND_EXTERN_MODULE_GLOBALS(mongodb)
#define IS_APM_SUBSCRIBER(zv) \
instanceof_function(Z_OBJCE_P(zv), php_phongo_commandsubscriber_ce) || \
instanceof_function(Z_OBJCE_P(zv), php_phongo_sdamsubscriber_ce)
#define IS_LOG_SUBSCRIBER(zv) instanceof_function(Z_OBJCE_P(zv), php_phongo_logsubscriber_ce)
/* Registers a global event subscriber */
PHP_FUNCTION(MongoDB_Driver_Monitoring_addSubscriber)
{
zval* subscriber;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_OBJECT_OF_CLASS(subscriber, php_phongo_subscriber_ce)
PHONGO_PARSE_PARAMETERS_END();
// TODO: Consider throwing if subscriber is unsupported (see: PHPC-2289)
if (IS_APM_SUBSCRIBER(subscriber)) {
phongo_apm_add_subscriber(MONGODB_G(subscribers), subscriber);
}
if (IS_LOG_SUBSCRIBER(subscriber)) {
phongo_log_add_logger(subscriber);
}
}
/* Unregisters a global event subscriber */
PHP_FUNCTION(MongoDB_Driver_Monitoring_removeSubscriber)
{
zval* subscriber;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_OBJECT_OF_CLASS(subscriber, php_phongo_subscriber_ce)
PHONGO_PARSE_PARAMETERS_END();
if (IS_APM_SUBSCRIBER(subscriber)) {
phongo_apm_remove_subscriber(MONGODB_G(subscribers), subscriber);
}
if (IS_LOG_SUBSCRIBER(subscriber)) {
phongo_log_remove_logger(subscriber);
}
}
/* Log a message through libmongoc (used for internal testing) */
PHP_FUNCTION(MongoDB_Driver_Monitoring_mongoc_log)
{
zend_long level;
char * domain, *message;
size_t domain_len, message_len;
PHONGO_PARSE_PARAMETERS_START(3, 3)
Z_PARAM_LONG(level)
Z_PARAM_STRING(domain, domain_len)
Z_PARAM_STRING(message, message_len)
PHONGO_PARSE_PARAMETERS_END();
if (level < MONGOC_LOG_LEVEL_ERROR || level > MONGOC_LOG_LEVEL_TRACE) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected level to be >= %d and <= %d, %" PHONGO_LONG_FORMAT " given", MONGOC_LOG_LEVEL_ERROR, MONGOC_LOG_LEVEL_TRACE, level);
return;
}
if (strlen(domain) != domain_len) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Domain cannot contain null bytes. Unexpected null byte after \"%s\".", domain);
return;
}
if (strlen(message) != message_len) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Message cannot contain null bytes. Unexpected null byte after \"%s\".", message);
return;
}
mongoc_log(level, domain, "%s", message);
}
mongodb-2.1.0/src/MongoDB/BulkWrite.c 0000644 0001751 0000166 00000046105 15014033047 014213 0 ustar /*
* Copyright 2015-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bson/bson.h"
#include "mongoc/mongoc.h"
#include
#include
#include "php_array_api.h"
#include "php_phongo.h"
#include "phongo_bson_encode.h"
#include "phongo_error.h"
#include "BulkWrite_arginfo.h"
#include "MongoDB/WriteConcern.h"
#define PHONGO_BULKWRITE_BYPASS_UNSET -1
zend_class_entry* php_phongo_bulkwrite_ce;
/* Extracts the "_id" field of a BSON document into a return value. */
static void php_phongo_bulkwrite_extract_id(bson_t* doc, zval** return_value)
{
zval* id = NULL;
php_phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
state.map.root.type = PHONGO_TYPEMAP_NATIVE_ARRAY;
if (!php_phongo_bson_to_zval_ex(doc, &state)) {
goto cleanup;
}
id = php_array_fetchc(&state.zchild, "_id");
if (id) {
ZVAL_ZVAL(*return_value, id, 1, 0);
}
cleanup:
zval_ptr_dtor(&state.zchild);
}
/* Returns whether any top-level field names in the document contain a "$". */
static inline bool php_phongo_bulkwrite_update_has_operators(bson_t* bupdate)
{
bson_iter_t iter;
if (bson_iter_init(&iter, bupdate)) {
while (bson_iter_next(&iter)) {
if (strchr(bson_iter_key(&iter), '$')) {
return true;
}
}
}
return false;
}
/* Returns whether the update document is considered an aggregation pipeline */
static inline bool php_phongo_bulkwrite_update_is_pipeline(bson_t* bupdate)
{
bson_iter_t iter;
bson_iter_t child;
const char* key;
int i = 0;
char* i_str;
if (!bson_iter_init(&iter, bupdate)) {
return false;
}
while (bson_iter_next(&iter)) {
key = bson_iter_key(&iter);
i_str = bson_strdup_printf("%d", i++);
if (strcmp(key, i_str)) {
bson_free(i_str);
return false;
}
bson_free(i_str);
if (BSON_ITER_HOLDS_DOCUMENT(&iter)) {
if (!bson_iter_recurse(&iter, &child)) {
return false;
}
if (!bson_iter_next(&child)) {
return false;
}
key = bson_iter_key(&child);
if (key[0] != '$') {
return false;
}
} else {
return false;
}
}
/* should return false when the document is empty */
return i != 0;
}
/* Returns whether the BSON array's keys are a sequence of integer strings
* starting with "0". BSON_APPEND_ARRAY considers it the caller's responsibility
* to ensure that the array's keys are properly formatted. */
static inline bool php_phongo_bulkwrite_bson_array_has_valid_keys(bson_t* array)
{
bson_iter_t iter;
if (bson_empty(array)) {
return true;
}
if (bson_iter_init(&iter, array)) {
char key[12];
int count = 0;
while (bson_iter_next(&iter)) {
bson_snprintf(key, sizeof(key), "%d", count);
if (0 != strcmp(key, bson_iter_key(&iter))) {
return false;
}
count++;
}
}
return true;
}
/* Appends an array field for the given opts document and key. Returns true on
* success; otherwise, false is returned and an exception is thrown. */
static bool php_phongo_bulkwrite_opts_append_array(bson_t* opts, const char* key, zval* zarr)
{
zval* value = php_array_fetch_deref(zarr, key);
bson_t b = BSON_INITIALIZER;
if (Z_TYPE_P(value) != IS_OBJECT && Z_TYPE_P(value) != IS_ARRAY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"%s\" option to be array or object, %s given", key, zend_get_type_by_const(Z_TYPE_P(value)));
return false;
}
// Explicitly allow MongoDB\BSON\PackedArray for array values
php_phongo_zval_to_bson(value, PHONGO_BSON_ALLOW_ROOT_ARRAY, &b, NULL);
if (EG(exception)) {
bson_destroy(&b);
return false;
}
if (!php_phongo_bulkwrite_bson_array_has_valid_keys(&b)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "\"%s\" option has invalid keys for a BSON array", key);
bson_destroy(&b);
return false;
}
if (!BSON_APPEND_ARRAY(opts, key, &b)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Error appending \"%s\" option", key);
bson_destroy(&b);
return false;
}
bson_destroy(&b);
return true;
}
/* Appends a document field for the given opts document and key. Returns true on
* success; otherwise, false is returned and an exception is thrown. */
static bool php_phongo_bulkwrite_opts_append_document(bson_t* opts, const char* key, zval* zarr)
{
zval* value = php_array_fetch_deref(zarr, key);
bson_t b = BSON_INITIALIZER;
if (Z_TYPE_P(value) != IS_OBJECT && Z_TYPE_P(value) != IS_ARRAY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"%s\" option to be array or object, %s given", key, zend_get_type_by_const(Z_TYPE_P(value)));
return false;
}
php_phongo_zval_to_bson(value, PHONGO_BSON_NONE, &b, NULL);
if (EG(exception)) {
bson_destroy(&b);
return false;
}
if (!BSON_APPEND_DOCUMENT(opts, key, &b)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Error appending \"%s\" option", key);
bson_destroy(&b);
return false;
}
bson_destroy(&b);
return true;
}
#define PHONGO_BULKWRITE_APPEND_BOOL(opt, value) \
if (!BSON_APPEND_BOOL(boptions, (opt), (value))) { \
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Error appending \"%s\" option", (opt)); \
return false; \
}
#define PHONGO_BULKWRITE_APPEND_INT32(opt, value) \
if (!BSON_APPEND_INT32(boptions, (opt), (value))) { \
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Error appending \"%s\" option", (opt)); \
return false; \
}
#define PHONGO_BULKWRITE_OPT_ARRAY(opt) \
if (zoptions && php_array_existsc(zoptions, (opt))) { \
if (!php_phongo_bulkwrite_opts_append_array(boptions, (opt), zoptions)) { \
return false; \
} \
}
#define PHONGO_BULKWRITE_OPT_DOCUMENT(opt) \
if (zoptions && php_array_existsc(zoptions, (opt))) { \
if (!php_phongo_bulkwrite_opts_append_document(boptions, (opt), zoptions)) { \
return false; \
} \
}
/* Initialize the "hint" option. Returns true on success; otherwise, false is
* returned and an exception is thrown.
*
* The "hint" option must be a string or document. Check for both types and
* merge into BSON options accordingly. */
static bool php_phongo_bulkwrite_opt_hint(bson_t* boptions, zval* zoptions)
{
/* The "hint" option (or "$hint" modifier) must be a string or document.
* Check for both types and merge into BSON options accordingly. */
if (zoptions && php_array_existsc(zoptions, "hint")) {
zend_uchar type = Z_TYPE_P(php_array_fetchc_deref(zoptions, "hint"));
if (type == IS_STRING) {
zval* value = php_array_fetchc_deref(zoptions, "hint");
if (!bson_append_utf8(boptions, "hint", 4, Z_STRVAL_P(value), Z_STRLEN_P(value))) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Error appending \"hint\" option");
return false;
}
} else if (type == IS_OBJECT || type == IS_ARRAY) {
PHONGO_BULKWRITE_OPT_DOCUMENT("hint");
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"hint\" option to be string, array, or object, %s given", zend_get_type_by_const(type));
return false;
}
}
return true;
}
/* Applies options (including defaults) for an update operation. */
static bool php_phongo_bulkwrite_update_apply_options(bson_t* boptions, zval* zoptions)
{
bool multi = false, upsert = false;
if (zoptions) {
multi = php_array_fetchc_bool(zoptions, "multi");
upsert = php_array_fetchc_bool(zoptions, "upsert");
}
PHONGO_BULKWRITE_APPEND_BOOL("multi", multi);
PHONGO_BULKWRITE_APPEND_BOOL("upsert", upsert);
PHONGO_BULKWRITE_OPT_ARRAY("arrayFilters");
PHONGO_BULKWRITE_OPT_DOCUMENT("collation");
PHONGO_BULKWRITE_OPT_DOCUMENT("sort");
if (!php_phongo_bulkwrite_opt_hint(boptions, zoptions)) {
return false;
}
return true;
}
/* Applies options (including defaults) for a delete operation. */
static bool php_phongo_bulkwrite_delete_apply_options(bson_t* boptions, zval* zoptions)
{
int32_t limit = 0;
if (zoptions) {
limit = php_array_fetchc_bool(zoptions, "limit") ? 1 : 0;
}
PHONGO_BULKWRITE_APPEND_INT32("limit", limit);
PHONGO_BULKWRITE_OPT_DOCUMENT("collation");
if (!php_phongo_bulkwrite_opt_hint(boptions, zoptions)) {
return false;
}
return true;
}
#undef PHONGO_BULKWRITE_APPEND_BOOL
#undef PHONGO_BULKWRITE_APPEND_INT32
#undef PHONGO_BULKWRITE_OPT_DOCUMENT
/* Constructs a new BulkWrite */
static PHP_METHOD(MongoDB_Driver_BulkWrite, __construct)
{
php_phongo_bulkwrite_t* intern;
zval* options = NULL;
zend_bool ordered = 1;
intern = Z_BULKWRITE_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
if (options && php_array_existsc(options, "ordered")) {
ordered = php_array_fetchc_bool(options, "ordered");
}
intern->bulk = mongoc_bulk_operation_new(ordered);
intern->ordered = ordered;
intern->bypass = PHONGO_BULKWRITE_BYPASS_UNSET;
intern->let = NULL;
intern->num_ops = 0;
intern->executed = false;
if (options && php_array_existsc(options, "bypassDocumentValidation")) {
zend_bool bypass = php_array_fetchc_bool(options, "bypassDocumentValidation");
mongoc_bulk_operation_set_bypass_document_validation(intern->bulk, bypass);
intern->bypass = bypass;
}
if (options && php_array_existsc(options, "let")) {
zval* value = php_array_fetchc_deref(options, "let");
if (Z_TYPE_P(value) != IS_OBJECT && Z_TYPE_P(value) != IS_ARRAY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"let\" option to be array or object, %s given", zend_get_type_by_const(Z_TYPE_P(value)));
return;
}
intern->let = bson_new();
php_phongo_zval_to_bson(value, PHONGO_BSON_NONE, intern->let, NULL);
if (EG(exception)) {
return;
}
mongoc_bulk_operation_set_let(intern->bulk, intern->let);
}
if (options && php_array_existsc(options, "comment")) {
zval* value = php_array_fetchc_deref(options, "comment");
intern->comment = ecalloc(1, sizeof(bson_value_t));
phongo_zval_to_bson_value(value, intern->comment);
if (EG(exception)) {
/* Exception should already have been thrown */
return;
}
mongoc_bulk_operation_set_comment(intern->bulk, intern->comment);
}
}
/* Adds an insert operation to the BulkWrite */
static PHP_METHOD(MongoDB_Driver_BulkWrite, insert)
{
php_phongo_bulkwrite_t* intern;
zval* zdocument;
bson_t bdocument = BSON_INITIALIZER, boptions = BSON_INITIALIZER;
bson_t* bson_out = NULL;
bson_error_t error = { 0 };
intern = Z_BULKWRITE_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY_OR_OBJECT(zdocument)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_zval_to_bson(zdocument, (PHONGO_BSON_ADD_ID | PHONGO_BSON_RETURN_ID), &bdocument, &bson_out);
if (EG(exception)) {
goto cleanup;
}
if (!bson_out) {
phongo_throw_exception(PHONGO_ERROR_LOGIC, "php_phongo_zval_to_bson() did not return an _id. Please file a bug report.");
goto cleanup;
}
if (!mongoc_bulk_operation_insert_with_opts(intern->bulk, &bdocument, &boptions, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
intern->num_ops++;
php_phongo_bulkwrite_extract_id(bson_out, &return_value);
cleanup:
bson_destroy(&bdocument);
bson_destroy(&boptions);
bson_clear(&bson_out);
}
/* Adds an update operation to the BulkWrite */
static PHP_METHOD(MongoDB_Driver_BulkWrite, update)
{
php_phongo_bulkwrite_t* intern;
zval * zquery, *zupdate, *zoptions = NULL;
bson_t bquery = BSON_INITIALIZER, bupdate = BSON_INITIALIZER, boptions = BSON_INITIALIZER;
bson_error_t error = { 0 };
intern = Z_BULKWRITE_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_ARRAY_OR_OBJECT(zquery)
Z_PARAM_ARRAY_OR_OBJECT(zupdate)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(zoptions)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_zval_to_bson(zquery, PHONGO_BSON_NONE, &bquery, NULL);
if (EG(exception)) {
goto cleanup;
}
// Explicitly allow MongoDB\BSON\PackedArray for update pipelines
php_phongo_zval_to_bson(zupdate, PHONGO_BSON_ALLOW_ROOT_ARRAY, &bupdate, NULL);
if (EG(exception)) {
goto cleanup;
}
if (!php_phongo_bulkwrite_update_apply_options(&boptions, zoptions)) {
goto cleanup;
}
if (php_phongo_bulkwrite_update_has_operators(&bupdate) || php_phongo_bulkwrite_update_is_pipeline(&bupdate)) {
if (zoptions && php_array_fetchc_bool(zoptions, "multi")) {
if (!mongoc_bulk_operation_update_many_with_opts(intern->bulk, &bquery, &bupdate, &boptions, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
} else {
if (!mongoc_bulk_operation_update_one_with_opts(intern->bulk, &bquery, &bupdate, &boptions, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
}
} else {
if (zoptions && php_array_fetchc_bool(zoptions, "multi")) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Replacement document conflicts with true \"multi\" option");
goto cleanup;
}
if (!mongoc_bulk_operation_replace_one_with_opts(intern->bulk, &bquery, &bupdate, &boptions, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
}
intern->num_ops++;
cleanup:
bson_destroy(&bquery);
bson_destroy(&bupdate);
bson_destroy(&boptions);
}
/* Adds a delete operation to the BulkWrite */
static PHP_METHOD(MongoDB_Driver_BulkWrite, delete)
{
php_phongo_bulkwrite_t* intern;
zval * zquery, *zoptions = NULL;
bson_t bquery = BSON_INITIALIZER, boptions = BSON_INITIALIZER;
bson_error_t error = { 0 };
intern = Z_BULKWRITE_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_ARRAY_OR_OBJECT(zquery)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(zoptions)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_zval_to_bson(zquery, PHONGO_BSON_NONE, &bquery, NULL);
if (EG(exception)) {
goto cleanup;
}
if (!php_phongo_bulkwrite_delete_apply_options(&boptions, zoptions)) {
goto cleanup;
}
if (zoptions && php_array_fetchc_bool(zoptions, "limit")) {
if (!mongoc_bulk_operation_remove_one_with_opts(intern->bulk, &bquery, &boptions, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
} else {
if (!mongoc_bulk_operation_remove_many_with_opts(intern->bulk, &bquery, &boptions, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
}
intern->num_ops++;
cleanup:
bson_destroy(&bquery);
bson_destroy(&boptions);
}
/* Returns the number of operations that have been added to the BulkWrite */
static PHP_METHOD(MongoDB_Driver_BulkWrite, count)
{
php_phongo_bulkwrite_t* intern;
intern = Z_BULKWRITE_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_LONG(intern->num_ops);
}
/* MongoDB\Driver\BulkWrite object handlers */
static zend_object_handlers php_phongo_handler_bulkwrite;
static void php_phongo_bulkwrite_free_object(zend_object* object)
{
php_phongo_bulkwrite_t* intern = Z_OBJ_BULKWRITE(object);
zend_object_std_dtor(&intern->std);
if (intern->bulk) {
mongoc_bulk_operation_destroy(intern->bulk);
}
if (intern->let) {
bson_clear(&intern->let);
}
if (intern->comment) {
bson_value_destroy(intern->comment);
efree(intern->comment);
}
if (intern->database) {
efree(intern->database);
}
if (intern->collection) {
efree(intern->collection);
}
if (!Z_ISUNDEF(intern->session)) {
zval_ptr_dtor(&intern->session);
}
}
static zend_object* php_phongo_bulkwrite_create_object(zend_class_entry* class_type)
{
php_phongo_bulkwrite_t* intern = zend_object_alloc(sizeof(php_phongo_bulkwrite_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_bulkwrite;
return &intern->std;
}
static HashTable* php_phongo_bulkwrite_get_debug_info(zend_object* object, int* is_temp)
{
zval retval = ZVAL_STATIC_INIT;
php_phongo_bulkwrite_t* intern = NULL;
*is_temp = 1;
intern = Z_OBJ_BULKWRITE(object);
array_init(&retval);
if (intern->database) {
ADD_ASSOC_STRING(&retval, "database", intern->database);
} else {
ADD_ASSOC_NULL_EX(&retval, "database");
}
if (intern->collection) {
ADD_ASSOC_STRING(&retval, "collection", intern->collection);
} else {
ADD_ASSOC_NULL_EX(&retval, "collection");
}
ADD_ASSOC_BOOL_EX(&retval, "ordered", intern->ordered);
if (intern->bypass != PHONGO_BULKWRITE_BYPASS_UNSET) {
ADD_ASSOC_BOOL_EX(&retval, "bypassDocumentValidation", intern->bypass);
} else {
ADD_ASSOC_NULL_EX(&retval, "bypassDocumentValidation");
}
if (intern->comment) {
zval zv;
if (!phongo_bson_value_to_zval_legacy(intern->comment, &zv)) {
zval_ptr_dtor(&zv);
goto done;
}
ADD_ASSOC_ZVAL_EX(&retval, "comment", &zv);
}
if (intern->let) {
zval zv;
if (!php_phongo_bson_to_zval(intern->let, &zv)) {
zval_ptr_dtor(&zv);
goto done;
}
ADD_ASSOC_ZVAL_EX(&retval, "let", &zv);
}
ADD_ASSOC_BOOL_EX(&retval, "executed", intern->executed);
ADD_ASSOC_LONG_EX(&retval, "server_id", mongoc_bulk_operation_get_server_id(intern->bulk));
if (!Z_ISUNDEF(intern->session)) {
ADD_ASSOC_ZVAL_EX(&retval, "session", &intern->session);
Z_ADDREF(intern->session);
} else {
ADD_ASSOC_NULL_EX(&retval, "session");
}
if (mongoc_bulk_operation_get_write_concern(intern->bulk)) {
zval write_concern;
php_phongo_write_concern_to_zval(&write_concern, mongoc_bulk_operation_get_write_concern(intern->bulk));
ADD_ASSOC_ZVAL_EX(&retval, "write_concern", &write_concern);
} else {
ADD_ASSOC_NULL_EX(&retval, "write_concern");
}
done:
return Z_ARRVAL(retval);
}
void php_phongo_bulkwrite_init_ce(INIT_FUNC_ARGS)
{
php_phongo_bulkwrite_ce = register_class_MongoDB_Driver_BulkWrite(zend_ce_countable);
php_phongo_bulkwrite_ce->create_object = php_phongo_bulkwrite_create_object;
memcpy(&php_phongo_handler_bulkwrite, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_bulkwrite.get_debug_info = php_phongo_bulkwrite_get_debug_info;
php_phongo_handler_bulkwrite.free_obj = php_phongo_bulkwrite_free_object;
php_phongo_handler_bulkwrite.offset = XtOffsetOf(php_phongo_bulkwrite_t, std);
}
mongodb-2.1.0/src/MongoDB/BulkWriteCommand.c 0000644 0001751 0000166 00000056657 15014033047 015527 0 ustar /*
* Copyright 2024-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bson/bson.h"
#include "mongoc/mongoc.h"
#include
#include
#include "php_array_api.h"
#include "php_phongo.h"
#include "phongo_bson_encode.h"
#include "phongo_error.h"
#include "phongo_util.h"
#include "BulkWriteCommand_arginfo.h"
#include "MongoDB/WriteConcern.h"
#define PHONGO_BULKWRITECOMMAND_BYPASS_UNSET -1
zend_class_entry* php_phongo_bulkwritecommand_ce;
/* Creates a mongoc_bulkwriteopts_t from internal options, which should be freed
* by the caller. */
mongoc_bulkwriteopts_t* phongo_bwc_assemble_opts(php_phongo_bulkwritecommand_t* intern)
{
mongoc_bulkwriteopts_t* opts = mongoc_bulkwriteopts_new();
if (intern->bypass != PHONGO_BULKWRITECOMMAND_BYPASS_UNSET) {
mongoc_bulkwriteopts_set_bypassdocumentvalidation(opts, intern->bypass);
}
if (intern->comment) {
mongoc_bulkwriteopts_set_comment(opts, intern->comment);
}
if (intern->let) {
mongoc_bulkwriteopts_set_let(opts, intern->let);
}
mongoc_bulkwriteopts_set_ordered(opts, intern->ordered);
mongoc_bulkwriteopts_set_verboseresults(opts, intern->verbose);
return opts;
}
// TODO: Make this a common utility function to share with BulkWrite.c
/* Extracts the "_id" field of a BSON document into a return value. */
static void phongo_bwc_extract_id(bson_t* doc, zval** return_value)
{
zval* id = NULL;
php_phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
state.map.root.type = PHONGO_TYPEMAP_NATIVE_ARRAY;
/* TODO: Instead of converting the entire document, iterate BSON to obtain
* the bson_value_t of the _id field and then use phongo_bson_value_to_zval
* or phongo_bson_value_to_zval_legacy to populate the return value. */
if (!php_phongo_bson_to_zval_ex(doc, &state)) {
goto cleanup;
}
id = php_array_fetchc(&state.zchild, "_id");
if (id) {
ZVAL_ZVAL(*return_value, id, 1, 0);
}
cleanup:
zval_ptr_dtor(&state.zchild);
}
// TODO: Make this a common utility function to share with BulkWrite.c
/* Returns whether the BSON array's keys are a sequence of integer strings
* starting with "0". */
static inline bool phongo_bwc_bson_array_has_valid_keys(bson_t* array)
{
bson_iter_t iter;
if (bson_empty(array)) {
return true;
}
if (bson_iter_init(&iter, array)) {
char key[12];
int count = 0;
while (bson_iter_next(&iter)) {
bson_snprintf(key, sizeof(key), "%d", count);
if (0 != strcmp(key, bson_iter_key(&iter))) {
return false;
}
count++;
}
}
return true;
}
/* Constructs a new BulkWriteCommand */
static PHP_METHOD(MongoDB_Driver_BulkWriteCommand, __construct)
{
php_phongo_bulkwritecommand_t* intern;
zval* zoptions = NULL;
intern = Z_BULKWRITECOMMAND_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(zoptions)
PHONGO_PARSE_PARAMETERS_END();
intern->bw = mongoc_bulkwrite_new();
intern->bypass = PHONGO_BULKWRITECOMMAND_BYPASS_UNSET;
intern->comment = NULL;
intern->let = NULL;
intern->num_ops = 0;
intern->ordered = true;
intern->verbose = false;
if (!zoptions) {
return;
}
if (php_array_existsc(zoptions, "bypassDocumentValidation")) {
intern->bypass = php_array_fetchc_bool(zoptions, "bypassDocumentValidation") ? 1 : 0;
}
if (php_array_existsc(zoptions, "comment")) {
zval* value = php_array_fetchc_deref(zoptions, "comment");
intern->comment = ecalloc(1, sizeof(bson_value_t));
phongo_zval_to_bson_value(value, intern->comment);
if (EG(exception)) {
return;
}
}
if (php_array_existsc(zoptions, "let")) {
zval* value = php_array_fetchc_deref(zoptions, "let");
if (Z_TYPE_P(value) != IS_OBJECT && Z_TYPE_P(value) != IS_ARRAY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"let\" option to be array or object, %s given", zend_get_type_by_const(Z_TYPE_P(value)));
return;
}
intern->let = bson_new();
php_phongo_zval_to_bson(value, PHONGO_BSON_NONE, intern->let, NULL);
if (EG(exception)) {
return;
}
}
if (php_array_existsc(zoptions, "ordered")) {
intern->ordered = php_array_fetchc_bool(zoptions, "ordered");
}
if (php_array_existsc(zoptions, "verboseResults")) {
intern->verbose = php_array_fetchc_bool(zoptions, "verboseResults");
}
}
static PHP_METHOD(MongoDB_Driver_BulkWriteCommand, count)
{
php_phongo_bulkwritecommand_t* intern;
intern = Z_BULKWRITECOMMAND_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_LONG(intern->num_ops);
}
static bool phongo_bwc_parse_hint(zval* zhint, bson_value_t* bhint)
{
if (Z_TYPE_P(zhint) != IS_STRING && Z_TYPE_P(zhint) != IS_OBJECT && Z_TYPE_P(zhint) != IS_ARRAY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"hint\" option to be string, array, or object, %s given", zend_get_type_by_const(Z_TYPE_P(zhint)));
return false;
}
phongo_zval_to_bson_value(zhint, bhint);
if (EG(exception)) {
return false;
}
// Catch the edge case where the option yields a BSON array
if (bhint->value_type != BSON_TYPE_UTF8 && bhint->value_type != BSON_TYPE_DOCUMENT) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"hint\" option to yield string or document but got \"%s\"", php_phongo_bson_type_to_string(bhint->value_type));
return false;
}
return true;
}
static bool phongo_bwc_parse_document(zval* zdocument, bson_t* bdocument, const char* key)
{
if (Z_TYPE_P(zdocument) != IS_OBJECT && Z_TYPE_P(zdocument) != IS_ARRAY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"%s\" option to be array or object, %s given", key, zend_get_type_by_const(Z_TYPE_P(zdocument)));
return false;
}
php_phongo_zval_to_bson(zdocument, PHONGO_BSON_NONE, bdocument, NULL);
if (EG(exception)) {
return false;
}
return true;
}
static bool phongo_bwc_parse_array(zval* zarray, bson_t* barray, const char* key)
{
if (Z_TYPE_P(zarray) != IS_OBJECT && Z_TYPE_P(zarray) != IS_ARRAY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"%s\" option to be array or object, %s given", key, zend_get_type_by_const(Z_TYPE_P(zarray)));
return false;
}
// Explicitly allow MongoDB\BSON\PackedArray for array values
php_phongo_zval_to_bson(zarray, PHONGO_BSON_ALLOW_ROOT_ARRAY, barray, NULL);
if (EG(exception)) {
return false;
}
if (!phongo_bwc_bson_array_has_valid_keys(barray)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"%s\" option to yield array but got non-sequential keys", key);
return false;
}
return true;
}
static PHP_METHOD(MongoDB_Driver_BulkWriteCommand, deleteMany)
{
php_phongo_bulkwritecommand_t* intern;
char* ns;
size_t ns_len;
zval* zfilter;
zval* zoptions = NULL;
bson_t bfilter = BSON_INITIALIZER;
mongoc_bulkwrite_deletemanyopts_t* opts = NULL;
bson_error_t error = { 0 };
intern = Z_BULKWRITECOMMAND_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STRING(ns, ns_len)
Z_PARAM_ARRAY_OR_OBJECT(zfilter)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(zoptions)
PHONGO_PARSE_PARAMETERS_END();
if (strlen(ns) != ns_len) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Namespace string should not contain null bytes");
return;
}
php_phongo_zval_to_bson(zfilter, PHONGO_BSON_NONE, &bfilter, NULL);
if (EG(exception)) {
goto cleanup;
}
if (zoptions) {
opts = mongoc_bulkwrite_deletemanyopts_new();
if (php_array_existsc(zoptions, "hint")) {
bson_value_t bhint = { 0 };
if (!phongo_bwc_parse_hint(php_array_fetchc_deref(zoptions, "hint"), &bhint)) {
bson_value_destroy(&bhint);
goto cleanup;
}
mongoc_bulkwrite_deletemanyopts_set_hint(opts, &bhint);
bson_value_destroy(&bhint);
}
if (php_array_existsc(zoptions, "collation")) {
bson_t bcollation = BSON_INITIALIZER;
if (!phongo_bwc_parse_document(php_array_fetchc_deref(zoptions, "collation"), &bcollation, "collation")) {
bson_destroy(&bcollation);
goto cleanup;
}
mongoc_bulkwrite_deletemanyopts_set_collation(opts, &bcollation);
bson_destroy(&bcollation);
}
}
if (!mongoc_bulkwrite_append_deletemany(intern->bw, ns, &bfilter, opts, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
intern->num_ops++;
cleanup:
bson_destroy(&bfilter);
mongoc_bulkwrite_deletemanyopts_destroy(opts);
}
static PHP_METHOD(MongoDB_Driver_BulkWriteCommand, deleteOne)
{
php_phongo_bulkwritecommand_t* intern;
char* ns;
size_t ns_len;
zval* zfilter;
zval* zoptions = NULL;
bson_t bfilter = BSON_INITIALIZER;
mongoc_bulkwrite_deleteoneopts_t* opts = NULL;
bson_error_t error = { 0 };
intern = Z_BULKWRITECOMMAND_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STRING(ns, ns_len)
Z_PARAM_ARRAY_OR_OBJECT(zfilter)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(zoptions)
PHONGO_PARSE_PARAMETERS_END();
if (strlen(ns) != ns_len) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Namespace string should not contain null bytes");
return;
}
php_phongo_zval_to_bson(zfilter, PHONGO_BSON_NONE, &bfilter, NULL);
if (EG(exception)) {
goto cleanup;
}
if (zoptions) {
opts = mongoc_bulkwrite_deleteoneopts_new();
if (php_array_existsc(zoptions, "hint")) {
bson_value_t bhint = { 0 };
if (!phongo_bwc_parse_hint(php_array_fetchc_deref(zoptions, "hint"), &bhint)) {
bson_value_destroy(&bhint);
goto cleanup;
}
mongoc_bulkwrite_deleteoneopts_set_hint(opts, &bhint);
bson_value_destroy(&bhint);
}
if (php_array_existsc(zoptions, "collation")) {
bson_t bcollation = BSON_INITIALIZER;
if (!phongo_bwc_parse_document(php_array_fetchc_deref(zoptions, "collation"), &bcollation, "collation")) {
bson_destroy(&bcollation);
goto cleanup;
}
mongoc_bulkwrite_deleteoneopts_set_collation(opts, &bcollation);
bson_destroy(&bcollation);
}
}
if (!mongoc_bulkwrite_append_deleteone(intern->bw, ns, &bfilter, opts, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
intern->num_ops++;
cleanup:
bson_destroy(&bfilter);
mongoc_bulkwrite_deleteoneopts_destroy(opts);
}
static PHP_METHOD(MongoDB_Driver_BulkWriteCommand, insertOne)
{
php_phongo_bulkwritecommand_t* intern;
char* ns;
size_t ns_len;
zval* zdocument;
bson_t bdocument = BSON_INITIALIZER;
bson_t* bson_out = NULL;
bson_error_t error = { 0 };
intern = Z_BULKWRITECOMMAND_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_STRING(ns, ns_len)
Z_PARAM_ARRAY_OR_OBJECT(zdocument)
PHONGO_PARSE_PARAMETERS_END();
if (strlen(ns) != ns_len) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Namespace string should not contain null bytes");
return;
}
php_phongo_zval_to_bson(zdocument, (PHONGO_BSON_ADD_ID | PHONGO_BSON_RETURN_ID), &bdocument, &bson_out);
if (EG(exception)) {
goto cleanup;
}
if (!bson_out) {
phongo_throw_exception(PHONGO_ERROR_LOGIC, "php_phongo_zval_to_bson() did not return an _id. Please file a bug report.");
goto cleanup;
}
if (!mongoc_bulkwrite_append_insertone(intern->bw, ns, &bdocument, NULL, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
intern->num_ops++;
phongo_bwc_extract_id(bson_out, &return_value);
cleanup:
bson_destroy(&bdocument);
bson_clear(&bson_out);
}
static PHP_METHOD(MongoDB_Driver_BulkWriteCommand, replaceOne)
{
php_phongo_bulkwritecommand_t* intern;
char* ns;
size_t ns_len;
zval* zfilter;
zval* zreplacement;
zval* zoptions = NULL;
bson_t bfilter = BSON_INITIALIZER;
bson_t breplacement = BSON_INITIALIZER;
mongoc_bulkwrite_replaceoneopts_t* opts = NULL;
bson_error_t error = { 0 };
intern = Z_BULKWRITECOMMAND_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(3, 4)
Z_PARAM_STRING(ns, ns_len)
Z_PARAM_ARRAY_OR_OBJECT(zfilter)
Z_PARAM_ARRAY_OR_OBJECT(zreplacement)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(zoptions)
PHONGO_PARSE_PARAMETERS_END();
if (strlen(ns) != ns_len) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Namespace string should not contain null bytes");
return;
}
php_phongo_zval_to_bson(zfilter, PHONGO_BSON_NONE, &bfilter, NULL);
if (EG(exception)) {
goto cleanup;
}
php_phongo_zval_to_bson(zreplacement, PHONGO_BSON_NONE, &breplacement, NULL);
if (EG(exception)) {
goto cleanup;
}
if (zoptions) {
opts = mongoc_bulkwrite_replaceoneopts_new();
if (php_array_existsc(zoptions, "collation")) {
bson_t bcollation = BSON_INITIALIZER;
if (!phongo_bwc_parse_document(php_array_fetchc_deref(zoptions, "collation"), &bcollation, "collation")) {
bson_destroy(&bcollation);
goto cleanup;
}
mongoc_bulkwrite_replaceoneopts_set_collation(opts, &bcollation);
bson_destroy(&bcollation);
}
if (php_array_existsc(zoptions, "hint")) {
bson_value_t bhint = { 0 };
if (!phongo_bwc_parse_hint(php_array_fetchc_deref(zoptions, "hint"), &bhint)) {
bson_value_destroy(&bhint);
goto cleanup;
}
mongoc_bulkwrite_replaceoneopts_set_hint(opts, &bhint);
bson_value_destroy(&bhint);
}
if (php_array_existsc(zoptions, "sort")) {
bson_t bsort = BSON_INITIALIZER;
if (!phongo_bwc_parse_document(php_array_fetchc_deref(zoptions, "sort"), &bsort, "sort")) {
bson_destroy(&bsort);
goto cleanup;
}
mongoc_bulkwrite_replaceoneopts_set_sort(opts, &bsort);
bson_destroy(&bsort);
}
if (php_array_existsc(zoptions, "upsert")) {
mongoc_bulkwrite_replaceoneopts_set_upsert(opts, php_array_fetchc_bool(zoptions, "upsert"));
}
}
if (!mongoc_bulkwrite_append_replaceone(intern->bw, ns, &bfilter, &breplacement, opts, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
intern->num_ops++;
cleanup:
bson_destroy(&bfilter);
bson_destroy(&breplacement);
mongoc_bulkwrite_replaceoneopts_destroy(opts);
}
static PHP_METHOD(MongoDB_Driver_BulkWriteCommand, updateMany)
{
php_phongo_bulkwritecommand_t* intern;
char* ns;
size_t ns_len;
zval* zfilter;
zval* zupdate;
zval* zoptions = NULL;
bson_t bfilter = BSON_INITIALIZER;
bson_t bupdate = BSON_INITIALIZER;
mongoc_bulkwrite_updatemanyopts_t* opts = NULL;
bson_error_t error = { 0 };
intern = Z_BULKWRITECOMMAND_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(3, 4)
Z_PARAM_STRING(ns, ns_len)
Z_PARAM_ARRAY_OR_OBJECT(zfilter)
Z_PARAM_ARRAY_OR_OBJECT(zupdate)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(zoptions)
PHONGO_PARSE_PARAMETERS_END();
if (strlen(ns) != ns_len) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Namespace string should not contain null bytes");
return;
}
php_phongo_zval_to_bson(zfilter, PHONGO_BSON_NONE, &bfilter, NULL);
if (EG(exception)) {
goto cleanup;
}
// Explicitly allow MongoDB\BSON\PackedArray for update pipelines
php_phongo_zval_to_bson(zupdate, PHONGO_BSON_ALLOW_ROOT_ARRAY, &bupdate, NULL);
if (EG(exception)) {
goto cleanup;
}
if (zoptions) {
opts = mongoc_bulkwrite_updatemanyopts_new();
if (php_array_existsc(zoptions, "arrayFilters")) {
bson_t barrayfilters = BSON_INITIALIZER;
if (!phongo_bwc_parse_array(php_array_fetchc_deref(zoptions, "arrayFilters"), &barrayfilters, "arrayFilters")) {
bson_destroy(&barrayfilters);
goto cleanup;
}
mongoc_bulkwrite_updatemanyopts_set_arrayfilters(opts, &barrayfilters);
bson_destroy(&barrayfilters);
}
if (php_array_existsc(zoptions, "collation")) {
bson_t bcollation = BSON_INITIALIZER;
if (!phongo_bwc_parse_document(php_array_fetchc_deref(zoptions, "collation"), &bcollation, "collation")) {
bson_destroy(&bcollation);
goto cleanup;
}
mongoc_bulkwrite_updatemanyopts_set_collation(opts, &bcollation);
bson_destroy(&bcollation);
}
if (php_array_existsc(zoptions, "hint")) {
bson_value_t bhint = { 0 };
if (!phongo_bwc_parse_hint(php_array_fetchc_deref(zoptions, "hint"), &bhint)) {
bson_value_destroy(&bhint);
goto cleanup;
}
mongoc_bulkwrite_updatemanyopts_set_hint(opts, &bhint);
bson_value_destroy(&bhint);
}
if (php_array_existsc(zoptions, "upsert")) {
mongoc_bulkwrite_updatemanyopts_set_upsert(opts, php_array_fetchc_bool(zoptions, "upsert"));
}
}
if (!mongoc_bulkwrite_append_updatemany(intern->bw, ns, &bfilter, &bupdate, opts, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
intern->num_ops++;
cleanup:
bson_destroy(&bfilter);
bson_destroy(&bupdate);
mongoc_bulkwrite_updatemanyopts_destroy(opts);
}
static PHP_METHOD(MongoDB_Driver_BulkWriteCommand, updateOne)
{
php_phongo_bulkwritecommand_t* intern;
char* ns;
size_t ns_len;
zval* zfilter;
zval* zupdate;
zval* zoptions = NULL;
bson_t bfilter = BSON_INITIALIZER;
bson_t bupdate = BSON_INITIALIZER;
mongoc_bulkwrite_updateoneopts_t* opts = NULL;
bson_error_t error = { 0 };
intern = Z_BULKWRITECOMMAND_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(3, 4)
Z_PARAM_STRING(ns, ns_len)
Z_PARAM_ARRAY_OR_OBJECT(zfilter)
Z_PARAM_ARRAY_OR_OBJECT(zupdate)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(zoptions)
PHONGO_PARSE_PARAMETERS_END();
if (strlen(ns) != ns_len) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Namespace string should not contain null bytes");
return;
}
php_phongo_zval_to_bson(zfilter, PHONGO_BSON_NONE, &bfilter, NULL);
if (EG(exception)) {
goto cleanup;
}
// Explicitly allow MongoDB\BSON\PackedArray for update pipelines
php_phongo_zval_to_bson(zupdate, PHONGO_BSON_ALLOW_ROOT_ARRAY, &bupdate, NULL);
if (EG(exception)) {
goto cleanup;
}
if (zoptions) {
opts = mongoc_bulkwrite_updateoneopts_new();
if (php_array_existsc(zoptions, "arrayFilters")) {
bson_t barrayfilters = BSON_INITIALIZER;
if (!phongo_bwc_parse_array(php_array_fetchc_deref(zoptions, "arrayFilters"), &barrayfilters, "arrayFilters")) {
bson_destroy(&barrayfilters);
goto cleanup;
}
mongoc_bulkwrite_updateoneopts_set_arrayfilters(opts, &barrayfilters);
bson_destroy(&barrayfilters);
}
if (php_array_existsc(zoptions, "collation")) {
bson_t bcollation = BSON_INITIALIZER;
if (!phongo_bwc_parse_document(php_array_fetchc_deref(zoptions, "collation"), &bcollation, "collation")) {
bson_destroy(&bcollation);
goto cleanup;
}
mongoc_bulkwrite_updateoneopts_set_collation(opts, &bcollation);
bson_destroy(&bcollation);
}
if (php_array_existsc(zoptions, "hint")) {
bson_value_t bhint = { 0 };
if (!phongo_bwc_parse_hint(php_array_fetchc_deref(zoptions, "hint"), &bhint)) {
bson_value_destroy(&bhint);
goto cleanup;
}
mongoc_bulkwrite_updateoneopts_set_hint(opts, &bhint);
bson_value_destroy(&bhint);
}
if (php_array_existsc(zoptions, "sort")) {
bson_t bsort = BSON_INITIALIZER;
if (!phongo_bwc_parse_document(php_array_fetchc_deref(zoptions, "sort"), &bsort, "sort")) {
bson_destroy(&bsort);
goto cleanup;
}
mongoc_bulkwrite_updateoneopts_set_sort(opts, &bsort);
bson_destroy(&bsort);
}
if (php_array_existsc(zoptions, "upsert")) {
mongoc_bulkwrite_updateoneopts_set_upsert(opts, php_array_fetchc_bool(zoptions, "upsert"));
}
}
if (!mongoc_bulkwrite_append_updateone(intern->bw, ns, &bfilter, &bupdate, opts, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
intern->num_ops++;
cleanup:
bson_destroy(&bfilter);
bson_destroy(&bupdate);
mongoc_bulkwrite_updateoneopts_destroy(opts);
}
/* MongoDB\Driver\BulkWriteCommand object handlers */
static zend_object_handlers php_phongo_handler_bulkwritecommand;
static void php_phongo_bulkwritecommand_free_object(zend_object* object)
{
php_phongo_bulkwritecommand_t* intern = Z_OBJ_BULKWRITECOMMAND(object);
zend_object_std_dtor(&intern->std);
if (intern->bw) {
mongoc_bulkwrite_destroy(intern->bw);
}
if (intern->let) {
bson_clear(&intern->let);
}
if (intern->comment) {
bson_value_destroy(intern->comment);
efree(intern->comment);
}
if (!Z_ISUNDEF(intern->session)) {
zval_ptr_dtor(&intern->session);
}
}
static zend_object* php_phongo_bulkwritecommand_create_object(zend_class_entry* class_type)
{
php_phongo_bulkwritecommand_t* intern = zend_object_alloc(sizeof(php_phongo_bulkwritecommand_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_bulkwritecommand;
return &intern->std;
}
static HashTable* php_phongo_bulkwritecommand_get_debug_info(zend_object* object, int* is_temp)
{
zval retval = ZVAL_STATIC_INIT;
php_phongo_bulkwritecommand_t* intern = NULL;
*is_temp = 1;
intern = Z_OBJ_BULKWRITECOMMAND(object);
array_init(&retval);
if (intern->bypass != PHONGO_BULKWRITECOMMAND_BYPASS_UNSET) {
ADD_ASSOC_BOOL_EX(&retval, "bypassDocumentValidation", intern->bypass);
} else {
ADD_ASSOC_NULL_EX(&retval, "bypassDocumentValidation");
}
if (intern->comment) {
zval zv;
if (!phongo_bson_value_to_zval_legacy(intern->comment, &zv)) {
zval_ptr_dtor(&zv);
goto done;
}
ADD_ASSOC_ZVAL_EX(&retval, "comment", &zv);
}
if (intern->let) {
zval zv;
if (!php_phongo_bson_to_zval(intern->let, &zv)) {
zval_ptr_dtor(&zv);
goto done;
}
ADD_ASSOC_ZVAL_EX(&retval, "let", &zv);
}
ADD_ASSOC_BOOL_EX(&retval, "ordered", intern->ordered);
ADD_ASSOC_BOOL_EX(&retval, "verboseResults", intern->verbose);
if (!Z_ISUNDEF(intern->session)) {
ADD_ASSOC_ZVAL_EX(&retval, "session", &intern->session);
Z_ADDREF(intern->session);
} else {
ADD_ASSOC_NULL_EX(&retval, "session");
}
done:
return Z_ARRVAL(retval);
}
void php_phongo_bulkwritecommand_init_ce(INIT_FUNC_ARGS)
{
php_phongo_bulkwritecommand_ce = register_class_MongoDB_Driver_BulkWriteCommand(zend_ce_countable);
php_phongo_bulkwritecommand_ce->create_object = php_phongo_bulkwritecommand_create_object;
memcpy(&php_phongo_handler_bulkwritecommand, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_bulkwritecommand.get_debug_info = php_phongo_bulkwritecommand_get_debug_info;
php_phongo_handler_bulkwritecommand.free_obj = php_phongo_bulkwritecommand_free_object;
php_phongo_handler_bulkwritecommand.offset = XtOffsetOf(php_phongo_bulkwritecommand_t, std);
}
mongodb-2.1.0/src/MongoDB/BulkWriteCommand.h 0000644 0001751 0000166 00000001533 15014033047 015513 0 ustar /*
* Copyright 2024-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_BULKWRITECOMMAND_H
#define PHONGO_BULKWRITECOMMAND_H
#include "mongoc/mongoc.h"
#include "phongo_structs.h"
mongoc_bulkwriteopts_t* phongo_bwc_assemble_opts(php_phongo_bulkwritecommand_t* intern);
#endif /* PHONGO_BULKWRITECOMMAND_H */
mongodb-2.1.0/src/MongoDB/BulkWriteCommandResult.c 0000644 0001751 0000166 00000022517 15014033047 016712 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bson/bson.h"
#include "mongoc/mongoc.h"
#include
#include
#include
#include "php_array_api.h"
#include "php_phongo.h"
#include "phongo_error.h"
#include "BSON/Document.h"
#include "MongoDB/WriteConcernError.h"
#include "MongoDB/WriteError.h"
#include "BulkWriteCommandResult_arginfo.h"
#define PHONGO_BULKWRITECOMMANDRESULT_CHECK_ACKNOWLEDGED(method) \
if (!intern->is_acknowledged) { \
phongo_throw_exception(PHONGO_ERROR_LOGIC, "MongoDB\\Driver\\BulkWriteCommandResult::" method "() should not be called for an unacknowledged write result"); \
return; \
}
zend_class_entry* php_phongo_bulkwritecommandresult_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_BulkWriteCommandResult)
/* Returns the number of documents that were inserted */
static PHP_METHOD(MongoDB_Driver_BulkWriteCommandResult, getInsertedCount)
{
php_phongo_bulkwritecommandresult_t* intern;
intern = Z_BULKWRITECOMMANDRESULT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
PHONGO_BULKWRITECOMMANDRESULT_CHECK_ACKNOWLEDGED("getInsertedCount");
RETURN_LONG(intern->inserted_count);
}
/* Returns the number of documents that matched the update criteria */
static PHP_METHOD(MongoDB_Driver_BulkWriteCommandResult, getMatchedCount)
{
php_phongo_bulkwritecommandresult_t* intern;
intern = Z_BULKWRITECOMMANDRESULT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
PHONGO_BULKWRITECOMMANDRESULT_CHECK_ACKNOWLEDGED("getMatchedCount");
RETURN_LONG(intern->matched_count);
}
/* Returns the number of documents that were actually modified by an update */
static PHP_METHOD(MongoDB_Driver_BulkWriteCommandResult, getModifiedCount)
{
php_phongo_bulkwritecommandresult_t* intern;
intern = Z_BULKWRITECOMMANDRESULT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
PHONGO_BULKWRITECOMMANDRESULT_CHECK_ACKNOWLEDGED("getModifiedCount");
RETURN_LONG(intern->modified_count);
}
/* Returns the number of documents that were deleted */
static PHP_METHOD(MongoDB_Driver_BulkWriteCommandResult, getDeletedCount)
{
php_phongo_bulkwritecommandresult_t* intern;
intern = Z_BULKWRITECOMMANDRESULT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
PHONGO_BULKWRITECOMMANDRESULT_CHECK_ACKNOWLEDGED("getDeletedCount");
RETURN_LONG(intern->deleted_count);
}
/* Returns the number of documents that were upserted */
static PHP_METHOD(MongoDB_Driver_BulkWriteCommandResult, getUpsertedCount)
{
php_phongo_bulkwritecommandresult_t* intern;
intern = Z_BULKWRITECOMMANDRESULT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
PHONGO_BULKWRITECOMMANDRESULT_CHECK_ACKNOWLEDGED("getUpsertedCount");
RETURN_LONG(intern->upserted_count);
}
static PHP_METHOD(MongoDB_Driver_BulkWriteCommandResult, getInsertResults)
{
php_phongo_bulkwritecommandresult_t* intern;
intern = Z_BULKWRITECOMMANDRESULT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
PHONGO_BULKWRITECOMMANDRESULT_CHECK_ACKNOWLEDGED("getInsertResults");
if (intern->insert_results) {
phongo_document_new(return_value, intern->insert_results, true);
}
}
static PHP_METHOD(MongoDB_Driver_BulkWriteCommandResult, getUpdateResults)
{
php_phongo_bulkwritecommandresult_t* intern;
intern = Z_BULKWRITECOMMANDRESULT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
PHONGO_BULKWRITECOMMANDRESULT_CHECK_ACKNOWLEDGED("getUpdateResults");
if (intern->update_results) {
phongo_document_new(return_value, intern->update_results, true);
}
}
static PHP_METHOD(MongoDB_Driver_BulkWriteCommandResult, getDeleteResults)
{
php_phongo_bulkwritecommandresult_t* intern;
intern = Z_BULKWRITECOMMANDRESULT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
PHONGO_BULKWRITECOMMANDRESULT_CHECK_ACKNOWLEDGED("getDeleteResults");
if (intern->delete_results) {
phongo_document_new(return_value, intern->delete_results, true);
}
}
/* Returns whether the write operation was acknowledged (based on the write
concern). */
static PHP_METHOD(MongoDB_Driver_BulkWriteCommandResult, isAcknowledged)
{
php_phongo_bulkwritecommandresult_t* intern;
intern = Z_BULKWRITECOMMANDRESULT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_BOOL(intern->is_acknowledged);
}
/* MongoDB\Driver\BulkWriteCommandResult object handlers */
static zend_object_handlers php_phongo_handler_bulkwritecommandresult;
static void php_phongo_bulkwritecommandresult_free_object(zend_object* object)
{
php_phongo_bulkwritecommandresult_t* intern = Z_OBJ_BULKWRITECOMMANDRESULT(object);
zend_object_std_dtor(&intern->std);
bson_destroy(intern->insert_results);
bson_destroy(intern->update_results);
bson_destroy(intern->delete_results);
}
static zend_object* php_phongo_bulkwritecommandresult_create_object(zend_class_entry* class_type)
{
php_phongo_bulkwritecommandresult_t* intern = zend_object_alloc(sizeof(php_phongo_bulkwritecommandresult_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_bulkwritecommandresult;
return &intern->std;
}
static HashTable* php_phongo_bulkwritecommandresult_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_bulkwritecommandresult_t* intern;
zval retval = ZVAL_STATIC_INIT;
intern = Z_OBJ_BULKWRITECOMMANDRESULT(object);
*is_temp = 1;
array_init_size(&retval, 12);
ADD_ASSOC_BOOL_EX(&retval, "isAcknowledged", intern->is_acknowledged);
ADD_ASSOC_LONG_EX(&retval, "insertedCount", intern->inserted_count);
ADD_ASSOC_LONG_EX(&retval, "matchedCount", intern->matched_count);
ADD_ASSOC_LONG_EX(&retval, "modifiedCount", intern->modified_count);
ADD_ASSOC_LONG_EX(&retval, "upsertedCount", intern->upserted_count);
ADD_ASSOC_LONG_EX(&retval, "deletedCount", intern->deleted_count);
if (intern->insert_results) {
zval insert_results;
phongo_document_new(&insert_results, intern->insert_results, true);
ADD_ASSOC_ZVAL_EX(&retval, "insertResults", &insert_results);
} else {
ADD_ASSOC_NULL_EX(&retval, "insertResults");
}
if (intern->update_results) {
zval update_results;
phongo_document_new(&update_results, intern->update_results, true);
ADD_ASSOC_ZVAL_EX(&retval, "updateResults", &update_results);
} else {
ADD_ASSOC_NULL_EX(&retval, "updateResults");
}
if (intern->delete_results) {
zval delete_results;
phongo_document_new(&delete_results, intern->delete_results, true);
ADD_ASSOC_ZVAL_EX(&retval, "deleteResults", &delete_results);
} else {
ADD_ASSOC_NULL_EX(&retval, "deleteResults");
}
return Z_ARRVAL(retval);
}
void php_phongo_bulkwritecommandresult_init_ce(INIT_FUNC_ARGS)
{
php_phongo_bulkwritecommandresult_ce = register_class_MongoDB_Driver_BulkWriteCommandResult();
php_phongo_bulkwritecommandresult_ce->create_object = php_phongo_bulkwritecommandresult_create_object;
memcpy(&php_phongo_handler_bulkwritecommandresult, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_bulkwritecommandresult.get_debug_info = php_phongo_bulkwritecommandresult_get_debug_info;
php_phongo_handler_bulkwritecommandresult.free_obj = php_phongo_bulkwritecommandresult_free_object;
php_phongo_handler_bulkwritecommandresult.offset = XtOffsetOf(php_phongo_bulkwritecommandresult_t, std);
}
static inline bson_t* _bson_copy_or_null(const bson_t* bson)
{
return bson ? bson_copy(bson) : NULL;
}
php_phongo_bulkwritecommandresult_t* phongo_bulkwritecommandresult_init(zval* return_value, mongoc_bulkwriteresult_t* bw_res)
{
php_phongo_bulkwritecommandresult_t* intern;
object_init_ex(return_value, php_phongo_bulkwritecommandresult_ce);
intern = Z_BULKWRITECOMMANDRESULT_OBJ_P(return_value);
intern->is_acknowledged = (bw_res != NULL);
// Copy mongoc_bulkwriteresult_t fields
if (bw_res) {
intern->inserted_count = mongoc_bulkwriteresult_insertedcount(bw_res);
intern->upserted_count = mongoc_bulkwriteresult_upsertedcount(bw_res);
intern->matched_count = mongoc_bulkwriteresult_matchedcount(bw_res);
intern->modified_count = mongoc_bulkwriteresult_modifiedcount(bw_res);
intern->deleted_count = mongoc_bulkwriteresult_deletedcount(bw_res);
// Result documents will null if verboseResults=false
intern->insert_results = _bson_copy_or_null(mongoc_bulkwriteresult_insertresults(bw_res));
intern->update_results = _bson_copy_or_null(mongoc_bulkwriteresult_updateresults(bw_res));
intern->delete_results = _bson_copy_or_null(mongoc_bulkwriteresult_deleteresults(bw_res));
}
return intern;
}
mongodb-2.1.0/src/MongoDB/BulkWriteCommandResult.h 0000644 0001751 0000166 00000001645 15014033047 016716 0 ustar /*
* Copyright 2024-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_BULKWRITECOMMANDRESULT_H
#define PHONGO_BULKWRITECOMMANDRESULT_H
#include "mongoc/mongoc.h"
#include
#include "phongo_structs.h"
php_phongo_bulkwritecommandresult_t* phongo_bulkwritecommandresult_init(zval* return_value, mongoc_bulkwriteresult_t* bw_res);
#endif /* PHONGO_BULKWRITECOMMANDRESULT_H */
mongodb-2.1.0/src/MongoDB/BulkWriteCommandResult_arginfo.h 0000644 0001751 0000166 00000010641 15014033047 020417 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 042b10edec437daefeda4f0fc883dd25e240439f */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_BulkWriteCommandResult___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_BulkWriteCommandResult_getInsertedCount, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_BulkWriteCommandResult_getMatchedCount arginfo_class_MongoDB_Driver_BulkWriteCommandResult_getInsertedCount
#define arginfo_class_MongoDB_Driver_BulkWriteCommandResult_getModifiedCount arginfo_class_MongoDB_Driver_BulkWriteCommandResult_getInsertedCount
#define arginfo_class_MongoDB_Driver_BulkWriteCommandResult_getUpsertedCount arginfo_class_MongoDB_Driver_BulkWriteCommandResult_getInsertedCount
#define arginfo_class_MongoDB_Driver_BulkWriteCommandResult_getDeletedCount arginfo_class_MongoDB_Driver_BulkWriteCommandResult_getInsertedCount
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_BulkWriteCommandResult_getInsertResults, 0, 0, MongoDB\\BSON\\Document, 1)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_BulkWriteCommandResult_getUpdateResults arginfo_class_MongoDB_Driver_BulkWriteCommandResult_getInsertResults
#define arginfo_class_MongoDB_Driver_BulkWriteCommandResult_getDeleteResults arginfo_class_MongoDB_Driver_BulkWriteCommandResult_getInsertResults
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_BulkWriteCommandResult_isAcknowledged, 0, 0, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_BulkWriteCommandResult, __construct);
static ZEND_METHOD(MongoDB_Driver_BulkWriteCommandResult, getInsertedCount);
static ZEND_METHOD(MongoDB_Driver_BulkWriteCommandResult, getMatchedCount);
static ZEND_METHOD(MongoDB_Driver_BulkWriteCommandResult, getModifiedCount);
static ZEND_METHOD(MongoDB_Driver_BulkWriteCommandResult, getUpsertedCount);
static ZEND_METHOD(MongoDB_Driver_BulkWriteCommandResult, getDeletedCount);
static ZEND_METHOD(MongoDB_Driver_BulkWriteCommandResult, getInsertResults);
static ZEND_METHOD(MongoDB_Driver_BulkWriteCommandResult, getUpdateResults);
static ZEND_METHOD(MongoDB_Driver_BulkWriteCommandResult, getDeleteResults);
static ZEND_METHOD(MongoDB_Driver_BulkWriteCommandResult, isAcknowledged);
static const zend_function_entry class_MongoDB_Driver_BulkWriteCommandResult_methods[] = {
ZEND_ME(MongoDB_Driver_BulkWriteCommandResult, __construct, arginfo_class_MongoDB_Driver_BulkWriteCommandResult___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_BulkWriteCommandResult, getInsertedCount, arginfo_class_MongoDB_Driver_BulkWriteCommandResult_getInsertedCount, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_BulkWriteCommandResult, getMatchedCount, arginfo_class_MongoDB_Driver_BulkWriteCommandResult_getMatchedCount, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_BulkWriteCommandResult, getModifiedCount, arginfo_class_MongoDB_Driver_BulkWriteCommandResult_getModifiedCount, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_BulkWriteCommandResult, getUpsertedCount, arginfo_class_MongoDB_Driver_BulkWriteCommandResult_getUpsertedCount, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_BulkWriteCommandResult, getDeletedCount, arginfo_class_MongoDB_Driver_BulkWriteCommandResult_getDeletedCount, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_BulkWriteCommandResult, getInsertResults, arginfo_class_MongoDB_Driver_BulkWriteCommandResult_getInsertResults, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_BulkWriteCommandResult, getUpdateResults, arginfo_class_MongoDB_Driver_BulkWriteCommandResult_getUpdateResults, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_BulkWriteCommandResult, getDeleteResults, arginfo_class_MongoDB_Driver_BulkWriteCommandResult_getDeleteResults, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_BulkWriteCommandResult, isAcknowledged, arginfo_class_MongoDB_Driver_BulkWriteCommandResult_isAcknowledged, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_BulkWriteCommandResult(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "BulkWriteCommandResult", class_MongoDB_Driver_BulkWriteCommandResult_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
mongodb-2.1.0/src/MongoDB/BulkWriteCommand_arginfo.h 0000644 0001751 0000166 00000010233 15014033047 017215 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 2af15e87d1d8095137d315218e688221ac2b5983 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_BulkWriteCommand___construct, 0, 0, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_BulkWriteCommand_count, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_BulkWriteCommand_deleteOne, 0, 2, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, namespace, IS_STRING, 0)
ZEND_ARG_TYPE_MASK(0, filter, MAY_BE_ARRAY|MAY_BE_OBJECT, NULL)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_BulkWriteCommand_deleteMany arginfo_class_MongoDB_Driver_BulkWriteCommand_deleteOne
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_BulkWriteCommand_insertOne, 0, 2, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO(0, namespace, IS_STRING, 0)
ZEND_ARG_TYPE_MASK(0, document, MAY_BE_ARRAY|MAY_BE_OBJECT, NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_BulkWriteCommand_replaceOne, 0, 3, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, namespace, IS_STRING, 0)
ZEND_ARG_TYPE_MASK(0, filter, MAY_BE_ARRAY|MAY_BE_OBJECT, NULL)
ZEND_ARG_TYPE_MASK(0, replacement, MAY_BE_ARRAY|MAY_BE_OBJECT, NULL)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_BulkWriteCommand_updateOne, 0, 3, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, namespace, IS_STRING, 0)
ZEND_ARG_TYPE_MASK(0, filter, MAY_BE_ARRAY|MAY_BE_OBJECT, NULL)
ZEND_ARG_TYPE_MASK(0, update, MAY_BE_ARRAY|MAY_BE_OBJECT, NULL)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_BulkWriteCommand_updateMany arginfo_class_MongoDB_Driver_BulkWriteCommand_updateOne
static ZEND_METHOD(MongoDB_Driver_BulkWriteCommand, __construct);
static ZEND_METHOD(MongoDB_Driver_BulkWriteCommand, count);
static ZEND_METHOD(MongoDB_Driver_BulkWriteCommand, deleteOne);
static ZEND_METHOD(MongoDB_Driver_BulkWriteCommand, deleteMany);
static ZEND_METHOD(MongoDB_Driver_BulkWriteCommand, insertOne);
static ZEND_METHOD(MongoDB_Driver_BulkWriteCommand, replaceOne);
static ZEND_METHOD(MongoDB_Driver_BulkWriteCommand, updateOne);
static ZEND_METHOD(MongoDB_Driver_BulkWriteCommand, updateMany);
static const zend_function_entry class_MongoDB_Driver_BulkWriteCommand_methods[] = {
ZEND_ME(MongoDB_Driver_BulkWriteCommand, __construct, arginfo_class_MongoDB_Driver_BulkWriteCommand___construct, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_BulkWriteCommand, count, arginfo_class_MongoDB_Driver_BulkWriteCommand_count, ZEND_ACC_PUBLIC)
ZEND_ME(MongoDB_Driver_BulkWriteCommand, deleteOne, arginfo_class_MongoDB_Driver_BulkWriteCommand_deleteOne, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_BulkWriteCommand, deleteMany, arginfo_class_MongoDB_Driver_BulkWriteCommand_deleteMany, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_BulkWriteCommand, insertOne, arginfo_class_MongoDB_Driver_BulkWriteCommand_insertOne, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_BulkWriteCommand, replaceOne, arginfo_class_MongoDB_Driver_BulkWriteCommand_replaceOne, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_BulkWriteCommand, updateOne, arginfo_class_MongoDB_Driver_BulkWriteCommand_updateOne, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_BulkWriteCommand, updateMany, arginfo_class_MongoDB_Driver_BulkWriteCommand_updateMany, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_BulkWriteCommand(zend_class_entry *class_entry_Countable)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "BulkWriteCommand", class_MongoDB_Driver_BulkWriteCommand_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
zend_class_implements(class_entry, 1, class_entry_Countable);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/BulkWrite_arginfo.h 0000644 0001751 0000166 00000005076 15014033047 015727 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 1e91ce9db35aa0f3b77c3042099b02ac0fb381a9 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_BulkWrite___construct, 0, 0, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_BulkWrite_count, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_BulkWrite_delete, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_MASK(0, filter, MAY_BE_ARRAY|MAY_BE_OBJECT, NULL)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, deleteOptions, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_BulkWrite_insert, 0, 1, IS_MIXED, 0)
ZEND_ARG_TYPE_MASK(0, document, MAY_BE_ARRAY|MAY_BE_OBJECT, NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_BulkWrite_update, 0, 2, IS_VOID, 0)
ZEND_ARG_TYPE_MASK(0, filter, MAY_BE_ARRAY|MAY_BE_OBJECT, NULL)
ZEND_ARG_TYPE_MASK(0, newObj, MAY_BE_ARRAY|MAY_BE_OBJECT, NULL)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, updateOptions, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_BulkWrite, __construct);
static ZEND_METHOD(MongoDB_Driver_BulkWrite, count);
static ZEND_METHOD(MongoDB_Driver_BulkWrite, delete);
static ZEND_METHOD(MongoDB_Driver_BulkWrite, insert);
static ZEND_METHOD(MongoDB_Driver_BulkWrite, update);
static const zend_function_entry class_MongoDB_Driver_BulkWrite_methods[] = {
ZEND_ME(MongoDB_Driver_BulkWrite, __construct, arginfo_class_MongoDB_Driver_BulkWrite___construct, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_BulkWrite, count, arginfo_class_MongoDB_Driver_BulkWrite_count, ZEND_ACC_PUBLIC)
ZEND_ME(MongoDB_Driver_BulkWrite, delete, arginfo_class_MongoDB_Driver_BulkWrite_delete, ZEND_ACC_PUBLIC)
ZEND_ME(MongoDB_Driver_BulkWrite, insert, arginfo_class_MongoDB_Driver_BulkWrite_insert, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_BulkWrite, update, arginfo_class_MongoDB_Driver_BulkWrite_update, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_BulkWrite(zend_class_entry *class_entry_Countable)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "BulkWrite", class_MongoDB_Driver_BulkWrite_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
zend_class_implements(class_entry, 1, class_entry_Countable);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/ClientEncryption.c 0000644 0001751 0000166 00000107046 15014033047 015576 0 ustar /*
* Copyright 2019-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bson/bson.h"
#include "mongoc/mongoc.h"
#include
#include
#include "php_array_api.h"
#include "php_phongo.h"
#include "phongo_bson_encode.h"
#include "phongo_error.h"
#include "phongo_util.h"
#include "ClientEncryption_arginfo.h"
#include "BSON/Binary.h"
#include "MongoDB/ClientEncryption.h"
#include "MongoDB/Cursor.h"
#include "MongoDB/Query.h"
zend_class_entry* php_phongo_clientencryption_ce;
/* Forward declarations */
static void phongo_clientencryption_create_datakey(php_phongo_clientencryption_t* clientencryption, zval* return_value, char* kms_provider, zval* options);
static void phongo_clientencryption_encrypt(php_phongo_clientencryption_t* clientencryption, zval* zvalue, zval* zciphertext, zval* options);
static void phongo_clientencryption_encrypt_expression(php_phongo_clientencryption_t* clientencryption, zval* zexpr, zval* return_value, zval* options);
static void phongo_clientencryption_decrypt(php_phongo_clientencryption_t* clientencryption, zval* zciphertext, zval* zvalue);
#define RETVAL_BSON_T(reply) \
do { \
php_phongo_bson_state state; \
PHONGO_BSON_INIT_STATE(state); \
if (!php_phongo_bson_to_zval_ex(&(reply), &state)) { \
zval_ptr_dtor(&state.zchild); \
goto cleanup; \
} \
RETVAL_ZVAL(&state.zchild, 0, 1); \
} while (0)
#define RETVAL_OPTIONAL_BSON_T(reply) \
do { \
RETVAL_NULL(); \
if (!bson_empty(&(reply))) { \
RETVAL_BSON_T(reply); \
} \
} while (0)
/* Returns true if keyid is a UUID Binary value with an appropriate data length;
* otherwise, throws an exception and returns false. */
static bool validate_keyid(bson_value_t* keyid)
{
if (keyid->value_type != BSON_TYPE_BINARY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected keyid to have Binary BSON type, %s given", php_phongo_bson_type_to_string(keyid->value_type));
return false;
}
if (keyid->value.v_binary.subtype != BSON_SUBTYPE_UUID) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected keyid to have UUID Binary subtype (%d), %d given", BSON_SUBTYPE_UUID, keyid->value.v_binary.subtype);
return false;
}
/* php_phongo_binary_init already enforces the data length for Binary objects
* with UUID subtypes so we throw a different exception here. */
if (keyid->value.v_binary.data_len != PHONGO_BINARY_UUID_SIZE) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "Expected keyid to have data length of %d bytes, %d given", PHONGO_BINARY_UUID_SIZE, keyid->value.v_binary.data_len);
return false;
}
return true;
}
/* Constructs a new ClientEncryption */
static PHP_METHOD(MongoDB_Driver_ClientEncryption, __construct)
{
zval* options;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(options)
PHONGO_PARSE_PARAMETERS_END();
/* An exception will be thrown on error. */
phongo_clientencryption_init(Z_CLIENTENCRYPTION_OBJ_P(getThis()), options, NULL);
}
/* Adds a keyAltName to the keyAltNames array of the key document in the key
vault collection with the given UUID (BSON binary subtype 0x04). Returns the
previous version of the key document, or null if no document matched. */
static PHP_METHOD(MongoDB_Driver_ClientEncryption, addKeyAltName)
{
zval* zkeyid = NULL;
char* keyaltname = NULL;
size_t keyaltname_len = 0;
bson_value_t keyid = { 0 };
bson_t key_doc = BSON_INITIALIZER;
bson_error_t error = { 0 };
PHONGO_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_OBJECT_OF_CLASS(zkeyid, php_phongo_binary_ce)
Z_PARAM_STRING(keyaltname, keyaltname_len);
PHONGO_PARSE_PARAMETERS_END();
phongo_zval_to_bson_value(zkeyid, &keyid);
if (EG(exception)) {
goto cleanup;
}
if (!validate_keyid(&keyid)) {
/* Exception already thrown */
goto cleanup;
}
if (!mongoc_client_encryption_add_key_alt_name(Z_CLIENTENCRYPTION_OBJ_P(getThis())->client_encryption, &keyid, keyaltname, &key_doc, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
RETVAL_OPTIONAL_BSON_T(key_doc);
cleanup:
bson_value_destroy(&keyid);
bson_destroy(&key_doc);
}
/* Creates a new key document and inserts into the key vault collection and
returns its identifier (UUID as a BSON binary with subtype 0x04). */
static PHP_METHOD(MongoDB_Driver_ClientEncryption, createDataKey)
{
char* kms_provider = NULL;
size_t kms_provider_len = 0;
zval* options = NULL;
php_phongo_clientencryption_t* intern;
intern = Z_CLIENTENCRYPTION_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_STRING(kms_provider, kms_provider_len)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
phongo_clientencryption_create_datakey(intern, return_value, kms_provider, options);
}
/* Removes the key document with the given UUID (BSON binary subtype 0x04) from
the key vault collection. Returns the result of the internal deleteOne()
operation on the key vault collection. */
static PHP_METHOD(MongoDB_Driver_ClientEncryption, deleteKey)
{
zval* zkeyid = NULL;
bson_value_t keyid = { 0 };
bson_t reply = BSON_INITIALIZER;
bson_error_t error = { 0 };
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_OBJECT_OF_CLASS(zkeyid, php_phongo_binary_ce)
PHONGO_PARSE_PARAMETERS_END();
phongo_zval_to_bson_value(zkeyid, &keyid);
if (EG(exception)) {
goto cleanup;
}
if (!validate_keyid(&keyid)) {
/* Exception already thrown */
goto cleanup;
}
if (!mongoc_client_encryption_delete_key(Z_CLIENTENCRYPTION_OBJ_P(getThis())->client_encryption, &keyid, &reply, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
if (bson_empty(&reply)) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "mongoc_client_encryption_delete_key returned an empty document");
goto cleanup;
}
RETVAL_BSON_T(reply);
cleanup:
bson_value_destroy(&keyid);
bson_destroy(&reply);
}
/* Encrypts a value with a given key and algorithm */
static PHP_METHOD(MongoDB_Driver_ClientEncryption, encrypt)
{
zval* value = NULL;
zval* options = NULL;
php_phongo_clientencryption_t* intern;
intern = Z_CLIENTENCRYPTION_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_ZVAL(value)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
phongo_clientencryption_encrypt(intern, value, return_value, options);
}
/* Encrypts a value with a given key and algorithm */
static PHP_METHOD(MongoDB_Driver_ClientEncryption, encryptExpression)
{
zval* expr = NULL;
zval* options = NULL;
php_phongo_clientencryption_t* intern;
intern = Z_CLIENTENCRYPTION_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_ZVAL(expr)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
phongo_clientencryption_encrypt_expression(intern, expr, return_value, options);
}
/* Decrypts an encrypted value (BSON binary of subtype 6). Returns the original BSON value */
static PHP_METHOD(MongoDB_Driver_ClientEncryption, decrypt)
{
zval* ciphertext;
php_phongo_clientencryption_t* intern;
intern = Z_CLIENTENCRYPTION_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_OBJECT_OF_CLASS(ciphertext, php_phongo_binary_interface_ce)
PHONGO_PARSE_PARAMETERS_END();
phongo_clientencryption_decrypt(intern, ciphertext, return_value);
}
/* Finds a single key document with the given UUID (BSON binary subtype 0x04).
Returns the result of the internal find() operation on the key vault
collection, or null if no document matched. */
static PHP_METHOD(MongoDB_Driver_ClientEncryption, getKey)
{
zval* zkeyid = NULL;
bson_value_t keyid = { 0 };
bson_t key_doc = BSON_INITIALIZER;
bson_error_t error = { 0 };
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_OBJECT_OF_CLASS(zkeyid, php_phongo_binary_ce)
PHONGO_PARSE_PARAMETERS_END();
phongo_zval_to_bson_value(zkeyid, &keyid);
if (EG(exception)) {
goto cleanup;
}
if (!validate_keyid(&keyid)) {
/* Exception already thrown */
goto cleanup;
}
if (!mongoc_client_encryption_get_key(Z_CLIENTENCRYPTION_OBJ_P(getThis())->client_encryption, &keyid, &key_doc, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
RETVAL_OPTIONAL_BSON_T(key_doc);
cleanup:
bson_value_destroy(&keyid);
bson_destroy(&key_doc);
}
/* Returns a key document in the key vault collection with the given keyAltName,
or null if no document matched. */
static PHP_METHOD(MongoDB_Driver_ClientEncryption, getKeyByAltName)
{
char* keyaltname = NULL;
size_t keyaltname_len = 0;
bson_t key_doc = BSON_INITIALIZER;
bson_error_t error = { 0 };
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STRING(keyaltname, keyaltname_len);
PHONGO_PARSE_PARAMETERS_END();
if (!mongoc_client_encryption_get_key_by_alt_name(Z_CLIENTENCRYPTION_OBJ_P(getThis())->client_encryption, keyaltname, &key_doc, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
RETVAL_OPTIONAL_BSON_T(key_doc);
cleanup:
bson_destroy(&key_doc);
}
/* Finds all documents in the key vault collection. Returns the result of the
internal find() operation on the key vault collection as a cursor. */
static PHP_METHOD(MongoDB_Driver_ClientEncryption, getKeys)
{
mongoc_cursor_t* cursor;
bson_error_t error = { 0 };
php_phongo_clientencryption_t* intern;
zval query = ZVAL_STATIC_INIT;
intern = Z_CLIENTENCRYPTION_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
/* mongoc_client_encryption_get_keys executes a query against its internal
* key vault collection. The collection has a majority read concern, but the
* query itself specifies no filter or options. Create an empty query object
* and attach it to the cursor for the benefit of debugging. */
if (!phongo_query_init(&query, NULL, NULL)) {
/* Exception already thrown */
goto cleanup;
}
cursor = mongoc_client_encryption_get_keys(intern->client_encryption, &error);
if (!cursor) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
if (!phongo_cursor_init_for_query(return_value, &intern->key_vault_client_manager, cursor, intern->key_vault_namespace, &query, NULL, NULL)) {
/* Exception already thrown */
mongoc_cursor_destroy(cursor);
goto cleanup;
}
cleanup:
zval_ptr_dtor(&query);
}
/* Removes a keyAltName from the keyAltNames array of the key document in the
key vault collection with the given UUID (BSON binary subtype 0x04). Returns
the previous version of the key document, or null if no document matched. */
static PHP_METHOD(MongoDB_Driver_ClientEncryption, removeKeyAltName)
{
zval* zkeyid = NULL;
char* keyaltname = NULL;
size_t keyaltname_len = 0;
bson_value_t keyid = { 0 };
bson_t key_doc = BSON_INITIALIZER;
bson_error_t error = { 0 };
PHONGO_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_OBJECT_OF_CLASS(zkeyid, php_phongo_binary_ce)
Z_PARAM_STRING(keyaltname, keyaltname_len);
PHONGO_PARSE_PARAMETERS_END();
phongo_zval_to_bson_value(zkeyid, &keyid);
if (EG(exception)) {
goto cleanup;
}
if (!validate_keyid(&keyid)) {
/* Exception already thrown */
goto cleanup;
}
if (!mongoc_client_encryption_remove_key_alt_name(Z_CLIENTENCRYPTION_OBJ_P(getThis())->client_encryption, &keyid, keyaltname, &key_doc, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
RETVAL_OPTIONAL_BSON_T(key_doc);
cleanup:
bson_value_destroy(&keyid);
bson_destroy(&key_doc);
}
/* Decrypts multiple data keys and (re-)encrypts them with a new provider (and
masterKey if applicable), or with their current provider if a new one is not
given. Returns an object corresponding to the internal libmongoc result. */
static PHP_METHOD(MongoDB_Driver_ClientEncryption, rewrapManyDataKey)
{
zval* zfilter = NULL;
zval* options = NULL;
bson_t filter = BSON_INITIALIZER;
char* provider = NULL;
zend_bool free_provider = false;
bson_t* masterkey = NULL;
bson_error_t error = { 0 };
bson_t reply = BSON_INITIALIZER;
mongoc_client_encryption_rewrap_many_datakey_result_t* result = NULL;
const bson_t* bulk_write_result;
PHONGO_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_ARRAY_OR_OBJECT(zfilter)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_zval_to_bson(zfilter, PHONGO_BSON_NONE, &filter, NULL);
if (EG(exception)) {
goto cleanup;
}
if (options && php_array_existsc(options, "provider")) {
int provider_len;
provider = php_array_fetchc_string(options, "provider", &provider_len, &free_provider);
}
if (options && php_array_existsc(options, "masterKey")) {
zval* zmasterkey = php_array_fetchc_deref(options, "masterKey");
if (Z_TYPE_P(zmasterkey) != IS_OBJECT && Z_TYPE_P(zmasterkey) != IS_ARRAY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"masterKey\" option to be array or object, %s given", zend_zval_type_name(zmasterkey));
goto cleanup;
}
if (!provider) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "The \"masterKey\" option should not be specified without \"provider\"");
goto cleanup;
}
masterkey = bson_new();
php_phongo_zval_to_bson(zmasterkey, PHONGO_BSON_NONE, masterkey, NULL);
if (EG(exception)) {
goto cleanup;
}
}
result = mongoc_client_encryption_rewrap_many_datakey_result_new();
if (!mongoc_client_encryption_rewrap_many_datakey(Z_CLIENTENCRYPTION_OBJ_P(getThis())->client_encryption, &filter, provider, masterkey, result, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
bulk_write_result = mongoc_client_encryption_rewrap_many_datakey_result_get_bulk_write_result(result);
if (bson_empty0(bulk_write_result)) {
BSON_APPEND_NULL(&reply, "bulkWriteResult");
} else {
BSON_APPEND_DOCUMENT(&reply, "bulkWriteResult", bulk_write_result);
}
RETVAL_BSON_T(reply);
cleanup:
if (free_provider) {
efree(provider);
}
bson_destroy(&filter);
bson_destroy(masterkey);
mongoc_client_encryption_rewrap_many_datakey_result_destroy(result);
}
/* MongoDB\Driver\ClientEncryption object handlers */
static zend_object_handlers php_phongo_handler_clientencryption;
static void php_phongo_clientencryption_free_object(zend_object* object)
{
php_phongo_clientencryption_t* intern = Z_OBJ_CLIENTENCRYPTION(object);
zend_object_std_dtor(&intern->std);
if (intern->client_encryption) {
mongoc_client_encryption_destroy(intern->client_encryption);
}
/* Free the keyVaultClient last to ensure that a potential non-persistent
* client outlives the mongoc_client_encryption_t as needed */
if (!Z_ISUNDEF(intern->key_vault_client_manager)) {
zval_ptr_dtor(&intern->key_vault_client_manager);
}
if (intern->key_vault_namespace) {
efree(intern->key_vault_namespace);
}
}
static zend_object* php_phongo_clientencryption_create_object(zend_class_entry* class_type)
{
php_phongo_clientencryption_t* intern = zend_object_alloc(sizeof(php_phongo_clientencryption_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_clientencryption;
return &intern->std;
}
static HashTable* php_phongo_clientencryption_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_clientencryption_t* intern = NULL;
zval retval = ZVAL_STATIC_INIT;
*is_temp = 1;
intern = Z_OBJ_CLIENTENCRYPTION(object);
array_init(&retval);
return Z_ARRVAL(retval);
}
void php_phongo_clientencryption_init_ce(INIT_FUNC_ARGS)
{
php_phongo_clientencryption_ce = register_class_MongoDB_Driver_ClientEncryption();
php_phongo_clientencryption_ce->create_object = php_phongo_clientencryption_create_object;
memcpy(&php_phongo_handler_clientencryption, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_clientencryption.get_debug_info = php_phongo_clientencryption_get_debug_info;
php_phongo_handler_clientencryption.free_obj = php_phongo_clientencryption_free_object;
php_phongo_handler_clientencryption.offset = XtOffsetOf(php_phongo_clientencryption_t, std);
}
#ifdef MONGOC_ENABLE_CLIENT_SIDE_ENCRYPTION
/* key_vault_client_manager is an output parameter and will be assigned to the
* effective keyVaultClient. */
static mongoc_client_encryption_opts_t* phongo_clientencryption_opts_from_zval(zval* options, zval* default_key_vault_client_manager, zval** key_vault_client_manager)
{
mongoc_client_encryption_opts_t* opts = mongoc_client_encryption_opts_new();
*key_vault_client_manager = NULL;
if (!options || Z_TYPE_P(options) != IS_ARRAY) {
/* Returning opts as-is will defer to mongoc_client_encryption_new to
* raise an error for missing required options */
return opts;
}
if (php_array_existsc(options, "keyVaultClient")) {
zval* key_vault_client = php_array_fetchc_deref(options, "keyVaultClient");
if (Z_TYPE_P(key_vault_client) != IS_OBJECT || !instanceof_function(Z_OBJCE_P(key_vault_client), php_phongo_manager_ce)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"keyVaultClient\" option to be %s, %s given", ZSTR_VAL(php_phongo_manager_ce->name), zend_zval_type_name(key_vault_client));
goto cleanup;
}
mongoc_client_encryption_opts_set_keyvault_client(opts, Z_MANAGER_OBJ_P(key_vault_client)->client);
*key_vault_client_manager = key_vault_client;
} else if (default_key_vault_client_manager) {
mongoc_client_encryption_opts_set_keyvault_client(opts, Z_MANAGER_OBJ_P(default_key_vault_client_manager)->client);
*key_vault_client_manager = default_key_vault_client_manager;
} else {
/* If the ClientEncryption object is being constructed directly, the
* "keyVaultClient" option must be explicitly provided. */
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "The \"keyVaultClient\" option is required when constructing a ClientEncryption object directly");
goto cleanup;
}
if (php_array_existsc(options, "keyVaultNamespace")) {
char* key_vault_namespace;
char* db_name;
char* coll_name;
int plen;
zend_bool pfree;
key_vault_namespace = php_array_fetchc_string(options, "keyVaultNamespace", &plen, &pfree);
if (!phongo_split_namespace(key_vault_namespace, &db_name, &coll_name)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"keyVaultNamespace\" option to contain a full collection namespace");
if (pfree) {
efree(key_vault_namespace);
}
goto cleanup;
}
mongoc_client_encryption_opts_set_keyvault_namespace(opts, db_name, coll_name);
efree(db_name);
efree(coll_name);
if (pfree) {
efree(key_vault_namespace);
}
}
if (php_array_existsc(options, "kmsProviders")) {
zval* kms_providers = php_array_fetchc_deref(options, "kmsProviders");
bson_t bson_providers = BSON_INITIALIZER;
if (Z_TYPE_P(kms_providers) != IS_ARRAY && Z_TYPE_P(kms_providers) != IS_OBJECT) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"kmsProviders\" option to be an array or object, %s given", zend_zval_type_name(kms_providers));
goto cleanup;
}
php_phongo_zval_to_bson(kms_providers, PHONGO_BSON_NONE, &bson_providers, NULL);
if (EG(exception)) {
goto cleanup;
}
mongoc_client_encryption_opts_set_kms_providers(opts, &bson_providers);
bson_destroy(&bson_providers);
}
if (php_array_existsc(options, "tlsOptions")) {
zval* tls_options = php_array_fetchc_deref(options, "tlsOptions");
bson_t bson_options = BSON_INITIALIZER;
if (Z_TYPE_P(tls_options) != IS_ARRAY && Z_TYPE_P(tls_options) != IS_OBJECT) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"tlsOptions\" option to be an array or object, %s given", zend_zval_type_name(tls_options));
goto cleanup;
}
php_phongo_zval_to_bson(tls_options, PHONGO_BSON_NONE, &bson_options, NULL);
if (EG(exception)) {
goto cleanup;
}
mongoc_client_encryption_opts_set_tls_opts(opts, &bson_options);
bson_destroy(&bson_options);
}
return opts;
cleanup:
if (opts) {
mongoc_client_encryption_opts_destroy(opts);
}
return NULL;
}
void phongo_clientencryption_init(php_phongo_clientencryption_t* intern, zval* options, zval* default_key_vault_client_manager)
{
mongoc_client_encryption_t* client_encryption;
mongoc_client_encryption_opts_t* opts;
zval* key_vault_client_manager = NULL;
bson_error_t error = { 0 };
opts = phongo_clientencryption_opts_from_zval(options, default_key_vault_client_manager, &key_vault_client_manager);
if (!opts) {
/* Exception already thrown */
goto cleanup;
}
client_encryption = mongoc_client_encryption_new(opts, &error);
if (!client_encryption) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
intern->client_encryption = client_encryption;
/* Note: key_vault_client_manager should always be assigned if options were
* successfully parsed by phongo_clientencryption_opts_from_zval, but let's
* be defensive. */
if (key_vault_client_manager) {
ZVAL_ZVAL(&intern->key_vault_client_manager, key_vault_client_manager, 1, 0);
}
/* Copy the key vault namespace, since it may be referenced later by
* ClientEncryption::getKeys(). The namespace will already have been
* validated by phongo_clientencryption_opts_from_zval. */
if (php_array_existsc(options, "keyVaultNamespace")) {
char* key_vault_namespace;
int plen;
zend_bool pfree;
key_vault_namespace = php_array_fetchc_string(options, "keyVaultNamespace", &plen, &pfree);
intern->key_vault_namespace = estrdup(key_vault_namespace);
if (pfree) {
efree(key_vault_namespace);
}
}
cleanup:
if (opts) {
mongoc_client_encryption_opts_destroy(opts);
}
}
static mongoc_client_encryption_datakey_opts_t* phongo_clientencryption_datakey_opts_from_zval(zval* options)
{
mongoc_client_encryption_datakey_opts_t* opts;
opts = mongoc_client_encryption_datakey_opts_new();
if (!options || Z_TYPE_P(options) != IS_ARRAY) {
return opts;
}
if (php_array_existsc(options, "keyAltNames")) {
zval* zkeyaltnames = php_array_fetchc_deref(options, "keyAltNames");
HashTable* ht_data;
uint32_t keyaltnames_count;
char** keyaltnames;
uint32_t i = 0;
uint32_t j = 0;
bool failed = false;
if (!zkeyaltnames || Z_TYPE_P(zkeyaltnames) != IS_ARRAY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected keyAltNames to be array, %s given", zend_zval_type_name(zkeyaltnames));
goto cleanup;
}
ht_data = HASH_OF(zkeyaltnames);
keyaltnames_count = ht_data ? zend_hash_num_elements(ht_data) : 0;
keyaltnames = ecalloc(keyaltnames_count, sizeof(char*));
{
zend_string* string_key = NULL;
zend_ulong num_key = 0;
zval* keyaltname;
ZEND_HASH_FOREACH_KEY_VAL(ht_data, num_key, string_key, keyaltname)
{
if (i >= keyaltnames_count) {
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Iterating over too many keyAltNames. Please file a bug report");
failed = true;
break;
}
if (Z_TYPE_P(keyaltname) != IS_STRING) {
if (string_key) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected keyAltName with index \"%s\" to be string, %s given", ZSTR_VAL(string_key), zend_zval_type_name(keyaltname));
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected keyAltName with index \"%lu\" to be string, %s given", num_key, zend_zval_type_name(keyaltname));
}
failed = true;
break;
}
keyaltnames[i] = estrdup(Z_STRVAL_P(keyaltname));
i++;
}
ZEND_HASH_FOREACH_END();
}
if (!failed) {
mongoc_client_encryption_datakey_opts_set_keyaltnames(opts, keyaltnames, keyaltnames_count);
}
for (j = 0; j < i; j++) {
efree(keyaltnames[j]);
}
efree(keyaltnames);
if (failed) {
goto cleanup;
}
}
if (php_array_existsc(options, "keyMaterial")) {
zval* keyMaterial = php_array_fetchc_deref(options, "keyMaterial");
if (Z_TYPE_P(keyMaterial) != IS_OBJECT || !instanceof_function(Z_OBJCE_P(keyMaterial), php_phongo_binary_ce)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"keyMaterial\" option to be %s, %s given", ZSTR_VAL(php_phongo_binary_ce->name), zend_zval_type_name(keyMaterial));
goto cleanup;
}
mongoc_client_encryption_datakey_opts_set_keymaterial(opts, (uint8_t*) Z_BINARY_OBJ_P(keyMaterial)->data, Z_BINARY_OBJ_P(keyMaterial)->data_len);
}
if (php_array_existsc(options, "masterKey")) {
zval* zmasterkey = php_array_fetchc_deref(options, "masterKey");
bson_t masterkey = BSON_INITIALIZER;
if (Z_TYPE_P(zmasterkey) != IS_OBJECT && Z_TYPE_P(zmasterkey) != IS_ARRAY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"masterKey\" option to be array or object, %s given", zend_zval_type_name(zmasterkey));
goto cleanup;
}
php_phongo_zval_to_bson(zmasterkey, PHONGO_BSON_NONE, &masterkey, NULL);
if (EG(exception)) {
bson_destroy(&masterkey);
goto cleanup;
}
mongoc_client_encryption_datakey_opts_set_masterkey(opts, &masterkey);
bson_destroy(&masterkey);
}
return opts;
cleanup:
if (opts) {
mongoc_client_encryption_datakey_opts_destroy(opts);
}
return NULL;
}
static void phongo_clientencryption_create_datakey(php_phongo_clientencryption_t* clientencryption, zval* return_value, char* kms_provider, zval* options)
{
mongoc_client_encryption_datakey_opts_t* opts;
bson_value_t keyid = { 0 };
bson_error_t error = { 0 };
opts = phongo_clientencryption_datakey_opts_from_zval(options);
if (!opts) {
/* Exception already thrown */
goto cleanup;
}
if (!mongoc_client_encryption_create_datakey(clientencryption->client_encryption, kms_provider, opts, &keyid, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
if (!phongo_bson_value_to_zval(&keyid, return_value)) {
/* Exception already thrown */
goto cleanup;
}
cleanup:
if (opts) {
mongoc_client_encryption_datakey_opts_destroy(opts);
}
bson_value_destroy(&keyid);
}
static mongoc_client_encryption_encrypt_range_opts_t* phongo_clientencryption_encrypt_range_opts_from_zval(zval* options)
{
mongoc_client_encryption_encrypt_range_opts_t* opts;
opts = mongoc_client_encryption_encrypt_range_opts_new();
if (!options || Z_TYPE_P(options) != IS_ARRAY) {
return opts;
}
if (php_array_existsc(options, "trimFactor")) {
int64_t trimfactor = php_array_fetchc_long(options, "trimFactor");
if (trimfactor < 0 || trimfactor > INT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"trimFactor\" range option to be a positive 32-bit integer, %" PRId64 " given", trimfactor);
goto cleanup;
}
mongoc_client_encryption_encrypt_range_opts_set_trim_factor(opts, (int32_t) trimfactor);
}
if (php_array_existsc(options, "sparsity")) {
int64_t sparsity = php_array_fetchc_long(options, "sparsity");
if (sparsity < 0 || sparsity > INT64_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"sparsity\" range option to be a positive 64-bit integer, %" PRId64 " given", sparsity);
goto cleanup;
}
mongoc_client_encryption_encrypt_range_opts_set_sparsity(opts, sparsity);
}
if (php_array_existsc(options, "precision")) {
int64_t precision = php_array_fetchc_long(options, "precision");
if (precision < 0 || precision > INT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"precision\" range option to be a positive 32-bit integer, %" PRId64 " given", precision);
goto cleanup;
}
mongoc_client_encryption_encrypt_range_opts_set_precision(opts, (int32_t) precision);
}
if (php_array_existsc(options, "min")) {
bson_value_t min = { 0 };
phongo_zval_to_bson_value(php_array_fetchc(options, "min"), &min);
if (EG(exception)) {
bson_value_destroy(&min);
goto cleanup;
}
mongoc_client_encryption_encrypt_range_opts_set_min(opts, &min);
bson_value_destroy(&min);
}
if (php_array_existsc(options, "max")) {
bson_value_t max = { 0 };
phongo_zval_to_bson_value(php_array_fetchc(options, "max"), &max);
if (EG(exception)) {
bson_value_destroy(&max);
goto cleanup;
}
mongoc_client_encryption_encrypt_range_opts_set_max(opts, &max);
bson_value_destroy(&max);
}
return opts;
cleanup:
if (opts) {
mongoc_client_encryption_encrypt_range_opts_destroy(opts);
}
return NULL;
}
static mongoc_client_encryption_encrypt_opts_t* phongo_clientencryption_encrypt_opts_from_zval(zval* options)
{
mongoc_client_encryption_encrypt_opts_t* opts;
opts = mongoc_client_encryption_encrypt_opts_new();
if (!options || Z_TYPE_P(options) != IS_ARRAY) {
return opts;
}
if (php_array_existsc(options, "contentionFactor")) {
mongoc_client_encryption_encrypt_opts_set_contention_factor(opts, php_array_fetchc_long(options, "contentionFactor"));
}
if (php_array_existsc(options, "keyId")) {
bson_value_t keyid = { 0 };
phongo_zval_to_bson_value(php_array_fetchc(options, "keyId"), &keyid);
if (EG(exception)) {
bson_value_destroy(&keyid);
goto cleanup;
}
mongoc_client_encryption_encrypt_opts_set_keyid(opts, &keyid);
bson_value_destroy(&keyid);
}
if (php_array_existsc(options, "keyAltName")) {
char* keyaltname;
int plen;
zend_bool pfree;
keyaltname = php_array_fetchc_string(options, "keyAltName", &plen, &pfree);
mongoc_client_encryption_encrypt_opts_set_keyaltname(opts, keyaltname);
if (pfree) {
efree(keyaltname);
}
}
if (php_array_existsc(options, "algorithm")) {
char* algorithm;
int plen;
zend_bool pfree;
algorithm = php_array_fetchc_string(options, "algorithm", &plen, &pfree);
mongoc_client_encryption_encrypt_opts_set_algorithm(opts, algorithm);
if (pfree) {
efree(algorithm);
}
}
if (php_array_existsc(options, "queryType")) {
char* querytype;
int plen;
zend_bool pfree;
querytype = php_array_fetchc_string(options, "queryType", &plen, &pfree);
mongoc_client_encryption_encrypt_opts_set_query_type(opts, querytype);
if (pfree) {
efree(querytype);
}
}
if (php_array_existsc(options, "rangeOpts")) {
mongoc_client_encryption_encrypt_range_opts_t* range_opts;
range_opts = phongo_clientencryption_encrypt_range_opts_from_zval(php_array_fetchc_deref(options, "rangeOpts"));
if (!range_opts) {
/* Exception already thrown */
goto cleanup;
}
mongoc_client_encryption_encrypt_opts_set_range_opts(opts, range_opts);
mongoc_client_encryption_encrypt_range_opts_destroy(range_opts);
}
return opts;
cleanup:
if (opts) {
mongoc_client_encryption_encrypt_opts_destroy(opts);
}
return NULL;
}
static void phongo_clientencryption_encrypt(php_phongo_clientencryption_t* clientencryption, zval* zvalue, zval* zciphertext, zval* options)
{
mongoc_client_encryption_encrypt_opts_t* opts = NULL;
bson_value_t ciphertext = { 0 };
bson_value_t value = { 0 };
bson_error_t error = { 0 };
phongo_zval_to_bson_value(zvalue, &value);
if (EG(exception)) {
goto cleanup;
}
opts = phongo_clientencryption_encrypt_opts_from_zval(options);
if (!opts) {
/* Exception already thrown */
goto cleanup;
}
if (!mongoc_client_encryption_encrypt(clientencryption->client_encryption, &value, opts, &ciphertext, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
if (!phongo_bson_value_to_zval(&ciphertext, zciphertext)) {
/* Exception already thrown */
goto cleanup;
}
cleanup:
if (opts) {
mongoc_client_encryption_encrypt_opts_destroy(opts);
}
bson_value_destroy(&ciphertext);
bson_value_destroy(&value);
}
static void phongo_clientencryption_encrypt_expression(php_phongo_clientencryption_t* clientencryption, zval* zexpr, zval* return_value, zval* options)
{
mongoc_client_encryption_encrypt_opts_t* opts = NULL;
bson_t expr = BSON_INITIALIZER;
bson_t expr_encrypted = BSON_INITIALIZER;
bson_error_t error = { 0 };
php_phongo_zval_to_bson(zexpr, PHONGO_BSON_NONE, &expr, NULL);
if (EG(exception)) {
goto cleanup;
}
opts = phongo_clientencryption_encrypt_opts_from_zval(options);
if (!opts) {
/* Exception already thrown */
goto cleanup;
}
if (!mongoc_client_encryption_encrypt_expression(clientencryption->client_encryption, &expr, opts, &expr_encrypted, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
if (!php_phongo_bson_to_zval(&expr_encrypted, return_value)) {
/* Exception already thrown */
goto cleanup;
}
cleanup:
if (opts) {
mongoc_client_encryption_encrypt_opts_destroy(opts);
}
bson_destroy(&expr);
bson_destroy(&expr_encrypted);
}
static void phongo_clientencryption_decrypt(php_phongo_clientencryption_t* clientencryption, zval* zciphertext, zval* zvalue)
{
bson_value_t ciphertext = { 0 };
bson_value_t value = { 0 };
bson_error_t error = { 0 };
phongo_zval_to_bson_value(zciphertext, &ciphertext);
if (EG(exception)) {
goto cleanup;
}
if (!mongoc_client_encryption_decrypt(clientencryption->client_encryption, &ciphertext, &value, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
goto cleanup;
}
/** Use the legacy decoder to return PHP types instead of BSON types */
if (!phongo_bson_value_to_zval_legacy(&value, zvalue)) {
/* Exception already thrown */
goto cleanup;
}
cleanup:
bson_value_destroy(&ciphertext);
bson_value_destroy(&value);
}
#else /* MONGOC_ENABLE_CLIENT_SIDE_ENCRYPTION */
void phongo_clientencryption_init(php_phongo_clientencryption_t* intern, zval* options, zval* default_key_vault_client_manager)
{
phongo_throw_exception_no_cse(PHONGO_ERROR_RUNTIME, "Cannot configure clientEncryption object.");
}
static void phongo_clientencryption_create_datakey(php_phongo_clientencryption_t* clientencryption, zval* return_value, char* kms_provider, zval* options)
{
phongo_throw_exception_no_cse(PHONGO_ERROR_RUNTIME, "Cannot create encryption key.");
}
static void phongo_clientencryption_encrypt(php_phongo_clientencryption_t* clientencryption, zval* zvalue, zval* zciphertext, zval* options)
{
phongo_throw_exception_no_cse(PHONGO_ERROR_RUNTIME, "Cannot encrypt value.");
}
static void phongo_clientencryption_encrypt_expression(php_phongo_clientencryption_t* clientencryption, zval* zexpr, zval* return_value, zval* options)
{
phongo_throw_exception_no_cse(PHONGO_ERROR_RUNTIME, "Cannot encrypt expression.");
}
static void phongo_clientencryption_decrypt(php_phongo_clientencryption_t* clientencryption, zval* zciphertext, zval* zvalue)
{
phongo_throw_exception_no_cse(PHONGO_ERROR_RUNTIME, "Cannot decrypt value.");
}
#endif /* MONGOC_ENABLE_CLIENT_SIDE_ENCRYPTION */
mongodb-2.1.0/src/MongoDB/ClientEncryption.h 0000644 0001751 0000166 00000001534 15014033047 015576 0 ustar /*
* Copyright 2022-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_CLIENTENCRYPTION_H
#define PHONGO_CLIENTENCRYPTION_H
#include
void phongo_clientencryption_init(php_phongo_clientencryption_t* intern, zval* options, zval* default_key_vault_client_manager);
#endif /* PHONGO_CLIENTENCRYPTION_H */
mongodb-2.1.0/src/MongoDB/ClientEncryption_arginfo.h 0000644 0001751 0000166 00000024030 15014033047 017277 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: ea16be50be5151fdd45b9e1bc37856d94990725e */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_ClientEncryption___construct, 0, 0, 1)
ZEND_ARG_TYPE_INFO(0, options, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_ClientEncryption_addKeyAltName, 0, 2, IS_OBJECT, 1)
ZEND_ARG_OBJ_INFO(0, keyId, MongoDB\\BSON\\Binary, 0)
ZEND_ARG_TYPE_INFO(0, keyAltName, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_ClientEncryption_createDataKey, 0, 1, MongoDB\\BSON\\Binary, 0)
ZEND_ARG_TYPE_INFO(0, kmsProvider, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_ClientEncryption_decrypt, 0, 1, IS_MIXED, 0)
ZEND_ARG_OBJ_INFO(0, value, MongoDB\\BSON\\Binary, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_ClientEncryption_deleteKey, 0, 1, IS_OBJECT, 0)
ZEND_ARG_OBJ_INFO(0, keyId, MongoDB\\BSON\\Binary, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_ClientEncryption_encrypt, 0, 1, MongoDB\\BSON\\Binary, 0)
ZEND_ARG_TYPE_INFO(0, value, IS_MIXED, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_ClientEncryption_encryptExpression, 0, 1, IS_OBJECT, 0)
ZEND_ARG_TYPE_MASK(0, expr, MAY_BE_ARRAY|MAY_BE_OBJECT, NULL)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_ClientEncryption_getKey, 0, 1, IS_OBJECT, 1)
ZEND_ARG_OBJ_INFO(0, keyId, MongoDB\\BSON\\Binary, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_ClientEncryption_getKeyByAltName, 0, 1, IS_OBJECT, 1)
ZEND_ARG_TYPE_INFO(0, keyAltName, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_ClientEncryption_getKeys, 0, 0, MongoDB\\Driver\\Cursor, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_ClientEncryption_removeKeyAltName arginfo_class_MongoDB_Driver_ClientEncryption_addKeyAltName
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_ClientEncryption_rewrapManyDataKey, 0, 1, IS_OBJECT, 0)
ZEND_ARG_TYPE_MASK(0, filter, MAY_BE_ARRAY|MAY_BE_OBJECT, NULL)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_ClientEncryption, __construct);
static ZEND_METHOD(MongoDB_Driver_ClientEncryption, addKeyAltName);
static ZEND_METHOD(MongoDB_Driver_ClientEncryption, createDataKey);
static ZEND_METHOD(MongoDB_Driver_ClientEncryption, decrypt);
static ZEND_METHOD(MongoDB_Driver_ClientEncryption, deleteKey);
static ZEND_METHOD(MongoDB_Driver_ClientEncryption, encrypt);
static ZEND_METHOD(MongoDB_Driver_ClientEncryption, encryptExpression);
static ZEND_METHOD(MongoDB_Driver_ClientEncryption, getKey);
static ZEND_METHOD(MongoDB_Driver_ClientEncryption, getKeyByAltName);
static ZEND_METHOD(MongoDB_Driver_ClientEncryption, getKeys);
static ZEND_METHOD(MongoDB_Driver_ClientEncryption, removeKeyAltName);
static ZEND_METHOD(MongoDB_Driver_ClientEncryption, rewrapManyDataKey);
static const zend_function_entry class_MongoDB_Driver_ClientEncryption_methods[] = {
ZEND_ME(MongoDB_Driver_ClientEncryption, __construct, arginfo_class_MongoDB_Driver_ClientEncryption___construct, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ClientEncryption, addKeyAltName, arginfo_class_MongoDB_Driver_ClientEncryption_addKeyAltName, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ClientEncryption, createDataKey, arginfo_class_MongoDB_Driver_ClientEncryption_createDataKey, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ClientEncryption, decrypt, arginfo_class_MongoDB_Driver_ClientEncryption_decrypt, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ClientEncryption, deleteKey, arginfo_class_MongoDB_Driver_ClientEncryption_deleteKey, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ClientEncryption, encrypt, arginfo_class_MongoDB_Driver_ClientEncryption_encrypt, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ClientEncryption, encryptExpression, arginfo_class_MongoDB_Driver_ClientEncryption_encryptExpression, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ClientEncryption, getKey, arginfo_class_MongoDB_Driver_ClientEncryption_getKey, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ClientEncryption, getKeyByAltName, arginfo_class_MongoDB_Driver_ClientEncryption_getKeyByAltName, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ClientEncryption, getKeys, arginfo_class_MongoDB_Driver_ClientEncryption_getKeys, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ClientEncryption, removeKeyAltName, arginfo_class_MongoDB_Driver_ClientEncryption_removeKeyAltName, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ClientEncryption, rewrapManyDataKey, arginfo_class_MongoDB_Driver_ClientEncryption_rewrapManyDataKey, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_ClientEncryption(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "ClientEncryption", class_MongoDB_Driver_ClientEncryption_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
zval const_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC_value;
zend_string *const_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC_value_str = zend_string_init(MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC, strlen(MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC), 1);
ZVAL_STR(&const_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC_value, const_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC_value_str);
zend_string *const_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC_name = zend_string_init_interned("AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC", sizeof("AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC_name, &const_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_AEAD_AES_256_CBC_HMAC_SHA_512_DETERMINISTIC_name);
zval const_AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM_value;
zend_string *const_AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM_value_str = zend_string_init(MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM, strlen(MONGOC_AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM), 1);
ZVAL_STR(&const_AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM_value, const_AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM_value_str);
zend_string *const_AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM_name = zend_string_init_interned("AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM", sizeof("AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM_name, &const_AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_AEAD_AES_256_CBC_HMAC_SHA_512_RANDOM_name);
zval const_ALGORITHM_INDEXED_value;
zend_string *const_ALGORITHM_INDEXED_value_str = zend_string_init(MONGOC_ENCRYPT_ALGORITHM_INDEXED, strlen(MONGOC_ENCRYPT_ALGORITHM_INDEXED), 1);
ZVAL_STR(&const_ALGORITHM_INDEXED_value, const_ALGORITHM_INDEXED_value_str);
zend_string *const_ALGORITHM_INDEXED_name = zend_string_init_interned("ALGORITHM_INDEXED", sizeof("ALGORITHM_INDEXED") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_ALGORITHM_INDEXED_name, &const_ALGORITHM_INDEXED_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_ALGORITHM_INDEXED_name);
zval const_ALGORITHM_UNINDEXED_value;
zend_string *const_ALGORITHM_UNINDEXED_value_str = zend_string_init(MONGOC_ENCRYPT_ALGORITHM_UNINDEXED, strlen(MONGOC_ENCRYPT_ALGORITHM_UNINDEXED), 1);
ZVAL_STR(&const_ALGORITHM_UNINDEXED_value, const_ALGORITHM_UNINDEXED_value_str);
zend_string *const_ALGORITHM_UNINDEXED_name = zend_string_init_interned("ALGORITHM_UNINDEXED", sizeof("ALGORITHM_UNINDEXED") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_ALGORITHM_UNINDEXED_name, &const_ALGORITHM_UNINDEXED_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_ALGORITHM_UNINDEXED_name);
zval const_ALGORITHM_RANGE_value;
zend_string *const_ALGORITHM_RANGE_value_str = zend_string_init(MONGOC_ENCRYPT_ALGORITHM_RANGE, strlen(MONGOC_ENCRYPT_ALGORITHM_RANGE), 1);
ZVAL_STR(&const_ALGORITHM_RANGE_value, const_ALGORITHM_RANGE_value_str);
zend_string *const_ALGORITHM_RANGE_name = zend_string_init_interned("ALGORITHM_RANGE", sizeof("ALGORITHM_RANGE") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_ALGORITHM_RANGE_name, &const_ALGORITHM_RANGE_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_ALGORITHM_RANGE_name);
zval const_QUERY_TYPE_EQUALITY_value;
zend_string *const_QUERY_TYPE_EQUALITY_value_str = zend_string_init(MONGOC_ENCRYPT_QUERY_TYPE_EQUALITY, strlen(MONGOC_ENCRYPT_QUERY_TYPE_EQUALITY), 1);
ZVAL_STR(&const_QUERY_TYPE_EQUALITY_value, const_QUERY_TYPE_EQUALITY_value_str);
zend_string *const_QUERY_TYPE_EQUALITY_name = zend_string_init_interned("QUERY_TYPE_EQUALITY", sizeof("QUERY_TYPE_EQUALITY") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_QUERY_TYPE_EQUALITY_name, &const_QUERY_TYPE_EQUALITY_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_QUERY_TYPE_EQUALITY_name);
zval const_QUERY_TYPE_RANGE_value;
zend_string *const_QUERY_TYPE_RANGE_value_str = zend_string_init(MONGOC_ENCRYPT_QUERY_TYPE_RANGE, strlen(MONGOC_ENCRYPT_QUERY_TYPE_RANGE), 1);
ZVAL_STR(&const_QUERY_TYPE_RANGE_value, const_QUERY_TYPE_RANGE_value_str);
zend_string *const_QUERY_TYPE_RANGE_name = zend_string_init_interned("QUERY_TYPE_RANGE", sizeof("QUERY_TYPE_RANGE") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_QUERY_TYPE_RANGE_name, &const_QUERY_TYPE_RANGE_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_QUERY_TYPE_RANGE_name);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Command.c 0000644 0001751 0000166 00000012124 15014033047 013653 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bson/bson.h"
#include
#include
#include "php_array_api.h"
#include "php_phongo.h"
#include "phongo_bson_encode.h"
#include "phongo_error.h"
#include "Command_arginfo.h"
zend_class_entry* php_phongo_command_ce;
/* Initialize the "maxAwaitTimeMS" option. Returns true on success; otherwise,
* false is returned and an exception is thrown.
*
* The "maxAwaitTimeMS" option is assigned to the cursor after query execution
* via mongoc_cursor_set_max_await_time_ms(). */
static bool php_phongo_command_init_max_await_time_ms(php_phongo_command_t* intern, zval* options)
{
int64_t max_await_time_ms;
if (!php_array_existsc(options, "maxAwaitTimeMS")) {
return true;
}
max_await_time_ms = php_array_fetchc_long(options, "maxAwaitTimeMS");
if (max_await_time_ms < 0) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"maxAwaitTimeMS\" option to be >= 0, %" PRId64 " given", max_await_time_ms);
return false;
}
if (max_await_time_ms > UINT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"maxAwaitTimeMS\" option to be <= %" PRIu32 ", %" PRId64 " given", UINT32_MAX, max_await_time_ms);
return false;
}
intern->max_await_time_ms = (uint32_t) max_await_time_ms;
return true;
}
/* Initializes the php_phongo_command_init from options argument. This
* function will fall back to a modifier in the absence of a top-level option
* (where applicable). */
static bool php_phongo_command_init(php_phongo_command_t* intern, zval* filter, zval* options)
{
bson_iter_t iter;
bson_iter_t sub_iter;
intern->bson = bson_new();
intern->batch_size = 0;
intern->max_await_time_ms = 0;
php_phongo_zval_to_bson(filter, PHONGO_BSON_NONE, intern->bson, NULL);
/* Note: if any exceptions are thrown, we can simply return as PHP will
* invoke php_phongo_query_free_object to destruct the object. */
if (EG(exception)) {
return false;
}
if (bson_iter_init(&iter, intern->bson) && bson_iter_find_descendant(&iter, "cursor.batchSize", &sub_iter) && BSON_ITER_HOLDS_INT(&sub_iter)) {
int64_t batch_size = bson_iter_as_int64(&sub_iter);
if (batch_size >= 0 && batch_size <= UINT32_MAX) {
intern->batch_size = (uint32_t) batch_size;
}
}
if (!options) {
return true;
}
if (!php_phongo_command_init_max_await_time_ms(intern, options)) {
return false;
}
return true;
}
/* Constructs a new Command */
static PHP_METHOD(MongoDB_Driver_Command, __construct)
{
php_phongo_command_t* intern;
zval* document;
zval* options = NULL;
intern = Z_COMMAND_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_ARRAY_OR_OBJECT(document)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_command_init(intern, document, options);
}
/* MongoDB\Driver\Command object handlers */
static zend_object_handlers php_phongo_handler_command;
static void php_phongo_command_free_object(zend_object* object)
{
php_phongo_command_t* intern = Z_OBJ_COMMAND(object);
zend_object_std_dtor(&intern->std);
if (intern->bson) {
bson_clear(&intern->bson);
}
}
static zend_object* php_phongo_command_create_object(zend_class_entry* class_type)
{
php_phongo_command_t* intern = zend_object_alloc(sizeof(php_phongo_command_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_command;
return &intern->std;
}
static HashTable* php_phongo_command_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_command_t* intern;
zval retval = ZVAL_STATIC_INIT;
*is_temp = 1;
intern = Z_OBJ_COMMAND(object);
array_init_size(&retval, 1);
if (intern->bson) {
zval zv;
if (!php_phongo_bson_to_zval(intern->bson, &zv)) {
zval_ptr_dtor(&zv);
goto done;
}
ADD_ASSOC_ZVAL_EX(&retval, "command", &zv);
} else {
ADD_ASSOC_NULL_EX(&retval, "command");
}
done:
return Z_ARRVAL(retval);
}
void php_phongo_command_init_ce(INIT_FUNC_ARGS)
{
php_phongo_command_ce = register_class_MongoDB_Driver_Command();
php_phongo_command_ce->create_object = php_phongo_command_create_object;
memcpy(&php_phongo_handler_command, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_command.get_debug_info = php_phongo_command_get_debug_info;
php_phongo_handler_command.free_obj = php_phongo_command_free_object;
php_phongo_handler_command.offset = XtOffsetOf(php_phongo_command_t, std);
}
mongodb-2.1.0/src/MongoDB/Command_arginfo.h 0000644 0001751 0000166 00000001754 15014033047 015374 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: e613d505cab7a354e0e6b1e0395933169891021f */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_Command___construct, 0, 0, 1)
ZEND_ARG_TYPE_MASK(0, document, MAY_BE_ARRAY|MAY_BE_OBJECT, NULL)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, commandOptions, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_Command, __construct);
static const zend_function_entry class_MongoDB_Driver_Command_methods[] = {
ZEND_ME(MongoDB_Driver_Command, __construct, arginfo_class_MongoDB_Driver_Command___construct, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Command(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "Command", class_MongoDB_Driver_Command_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Cursor.c 0000644 0001751 0000166 00000034124 15014033047 013556 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include
#include "php_phongo.h"
#include "phongo_bson.h"
#include "phongo_client.h"
#include "phongo_error.h"
#include "phongo_util.h"
#include "MongoDB/Cursor.h"
#include "MongoDB/Server.h"
#include "Cursor_arginfo.h"
zend_class_entry* php_phongo_cursor_ce;
/* Check if the cursor is exhausted (i.e. ID is zero) and free any reference to
* the session. Calling this function during iteration will allow an implicit
* session to return to the pool immediately after a getMore indicates that the
* server has no more results to return. */
static void php_phongo_cursor_free_session_if_exhausted(php_phongo_cursor_t* cursor)
{
if (mongoc_cursor_get_id(cursor->cursor)) {
return;
}
if (!Z_ISUNDEF(cursor->session)) {
zval_ptr_dtor(&cursor->session);
ZVAL_UNDEF(&cursor->session);
}
}
static void php_phongo_cursor_free_current(php_phongo_cursor_t* cursor)
{
if (!Z_ISUNDEF(cursor->visitor_data.zchild)) {
zval_ptr_dtor(&cursor->visitor_data.zchild);
ZVAL_UNDEF(&cursor->visitor_data.zchild);
}
}
/* Sets a type map to use for BSON unserialization */
static PHP_METHOD(MongoDB_Driver_Cursor, setTypeMap)
{
php_phongo_cursor_t* intern;
php_phongo_bson_state state;
zval* typemap = NULL;
bool restore_current_element = false;
PHONGO_BSON_INIT_STATE(state);
intern = Z_CURSOR_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY_OR_NULL(typemap)
PHONGO_PARSE_PARAMETERS_END();
if (!php_phongo_bson_typemap_to_state(typemap, &state.map)) {
return;
}
/* Check if the existing element needs to be freed before we overwrite
* visitor_data, which contains the only reference to it. */
if (!Z_ISUNDEF(intern->visitor_data.zchild)) {
php_phongo_cursor_free_current(intern);
restore_current_element = true;
}
php_phongo_bson_typemap_dtor(&intern->visitor_data.map);
intern->visitor_data = state;
/* If the cursor has a current element, we just freed it and should restore
* it with a new type map applied. */
if (restore_current_element && mongoc_cursor_current(intern->cursor)) {
const bson_t* doc = mongoc_cursor_current(intern->cursor);
if (!php_phongo_bson_to_zval_ex(doc, &intern->visitor_data)) {
php_phongo_cursor_free_current(intern);
}
}
}
static int php_phongo_cursor_to_array_apply(zend_object_iterator* iter, void* puser)
{
zval* data;
zval* return_value = (zval*) puser;
data = iter->funcs->get_current_data(iter);
if (EG(exception)) {
return ZEND_HASH_APPLY_STOP;
}
if (Z_ISUNDEF_P(data)) {
return ZEND_HASH_APPLY_STOP;
}
Z_TRY_ADDREF_P(data);
add_next_index_zval(return_value, data);
return ZEND_HASH_APPLY_KEEP;
}
/* Returns an array of all result documents for this cursor */
static PHP_METHOD(MongoDB_Driver_Cursor, toArray)
{
PHONGO_PARSE_PARAMETERS_NONE();
array_init(return_value);
if (spl_iterator_apply(getThis(), php_phongo_cursor_to_array_apply, (void*) return_value) != SUCCESS) {
zval_dtor(return_value);
RETURN_NULL();
}
}
/* Returns the CursorId for this cursor */
static PHP_METHOD(MongoDB_Driver_Cursor, getId)
{
php_phongo_cursor_t* intern;
intern = Z_CURSOR_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
phongo_int64_new(return_value, mongoc_cursor_get_id(intern->cursor));
}
/* Returns the Server object to which this cursor is attached */
static PHP_METHOD(MongoDB_Driver_Cursor, getServer)
{
php_phongo_cursor_t* intern;
intern = Z_CURSOR_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
phongo_server_init(return_value, &intern->manager, intern->server_id);
}
/* Checks if a cursor is still alive */
static PHP_METHOD(MongoDB_Driver_Cursor, isDead)
{
php_phongo_cursor_t* intern;
intern = Z_CURSOR_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_BOOL(!mongoc_cursor_more(intern->cursor));
}
static PHP_METHOD(MongoDB_Driver_Cursor, current)
{
php_phongo_cursor_t* intern = Z_CURSOR_OBJ_P(getThis());
zval* data;
PHONGO_PARSE_PARAMETERS_NONE();
data = &intern->visitor_data.zchild;
if (Z_ISUNDEF_P(data)) {
RETURN_NULL();
} else {
ZVAL_COPY_DEREF(return_value, data);
}
}
static PHP_METHOD(MongoDB_Driver_Cursor, key)
{
php_phongo_cursor_t* intern = Z_CURSOR_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
if (Z_ISUNDEF(intern->visitor_data.zchild)) {
RETURN_NULL();
}
RETURN_LONG(intern->current);
}
static PHP_METHOD(MongoDB_Driver_Cursor, next)
{
php_phongo_cursor_t* intern = Z_CURSOR_OBJ_P(getThis());
const bson_t* doc;
PHONGO_PARSE_PARAMETERS_NONE();
php_phongo_cursor_free_current(intern);
/* If the intern has already advanced, increment its position. Otherwise,
* the first call to mongoc_cursor_next() will be made below and we should
* leave its position at zero. */
if (intern->advanced) {
intern->current++;
} else {
intern->advanced = true;
}
if (mongoc_cursor_next(intern->cursor, &doc)) {
if (!php_phongo_bson_to_zval_ex(doc, &intern->visitor_data)) {
/* Free invalid result, but don't return as we want to free the
* session if the intern is exhausted. */
php_phongo_cursor_free_current(intern);
}
} else {
bson_error_t error = { 0 };
const bson_t* doc = NULL;
if (mongoc_cursor_error_document(intern->cursor, &error, &doc)) {
/* Intentionally not destroying the intern as it will happen
* naturally now that there are no more results */
phongo_throw_exception_from_bson_error_t_and_reply(&error, doc);
}
}
php_phongo_cursor_free_session_if_exhausted(intern);
}
static PHP_METHOD(MongoDB_Driver_Cursor, valid)
{
php_phongo_cursor_t* intern = Z_CURSOR_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_BOOL(!Z_ISUNDEF(intern->visitor_data.zchild));
}
static PHP_METHOD(MongoDB_Driver_Cursor, rewind)
{
php_phongo_cursor_t* intern = Z_CURSOR_OBJ_P(getThis());
const bson_t* doc;
PHONGO_PARSE_PARAMETERS_NONE();
/* If the cursor was never advanced (e.g. command cursor), do so now */
if (!intern->advanced) {
intern->advanced = true;
if (!phongo_cursor_advance_and_check_for_error(intern->cursor)) {
/* Exception should already have been thrown */
return;
}
}
if (intern->current > 0) {
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Cursors cannot rewind after starting iteration");
return;
}
php_phongo_cursor_free_current(intern);
doc = mongoc_cursor_current(intern->cursor);
if (doc) {
if (!php_phongo_bson_to_zval_ex(doc, &intern->visitor_data)) {
/* Free invalid result, but don't return as we want to free the
* session if the intern is exhausted. */
php_phongo_cursor_free_current(intern);
}
}
php_phongo_cursor_free_session_if_exhausted(intern);
}
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Cursor)
/* MongoDB\Driver\Cursor object handlers */
static zend_object_handlers php_phongo_handler_cursor;
static void php_phongo_cursor_free_object(zend_object* object)
{
php_phongo_cursor_t* intern = Z_OBJ_CURSOR(object);
zend_object_std_dtor(&intern->std);
/* If this Cursor was created in a different process, reset the client so
* that mongoc_cursor_destroy does not issue a killCursors command for an
* active cursor owned by a parent process. */
PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern, Z_MANAGER_OBJ_P(&intern->manager));
if (intern->cursor) {
mongoc_cursor_destroy(intern->cursor);
}
if (intern->database) {
efree(intern->database);
}
if (intern->collection) {
efree(intern->collection);
}
if (!Z_ISUNDEF(intern->query)) {
zval_ptr_dtor(&intern->query);
}
if (!Z_ISUNDEF(intern->command)) {
zval_ptr_dtor(&intern->command);
}
if (!Z_ISUNDEF(intern->read_preference)) {
zval_ptr_dtor(&intern->read_preference);
}
if (!Z_ISUNDEF(intern->session)) {
zval_ptr_dtor(&intern->session);
}
if (!Z_ISUNDEF(intern->manager)) {
zval_ptr_dtor(&intern->manager);
}
php_phongo_bson_typemap_dtor(&intern->visitor_data.map);
php_phongo_cursor_free_current(intern);
}
static zend_object* php_phongo_cursor_create_object(zend_class_entry* class_type)
{
php_phongo_cursor_t* intern = zend_object_alloc(sizeof(php_phongo_cursor_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
PHONGO_SET_CREATED_BY_PID(intern);
intern->std.handlers = &php_phongo_handler_cursor;
return &intern->std;
}
static HashTable* php_phongo_cursor_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_cursor_t* intern;
zval retval = ZVAL_STATIC_INIT;
*is_temp = 1;
intern = Z_OBJ_CURSOR(object);
array_init_size(&retval, 10);
if (intern->database) {
ADD_ASSOC_STRING(&retval, "database", intern->database);
} else {
ADD_ASSOC_NULL_EX(&retval, "database");
}
if (intern->collection) {
ADD_ASSOC_STRING(&retval, "collection", intern->collection);
} else {
ADD_ASSOC_NULL_EX(&retval, "collection");
}
if (!Z_ISUNDEF(intern->query)) {
ADD_ASSOC_ZVAL_EX(&retval, "query", &intern->query);
Z_ADDREF(intern->query);
} else {
ADD_ASSOC_NULL_EX(&retval, "query");
}
if (!Z_ISUNDEF(intern->command)) {
ADD_ASSOC_ZVAL_EX(&retval, "command", &intern->command);
Z_ADDREF(intern->command);
} else {
ADD_ASSOC_NULL_EX(&retval, "command");
}
if (!Z_ISUNDEF(intern->read_preference)) {
ADD_ASSOC_ZVAL_EX(&retval, "readPreference", &intern->read_preference);
Z_ADDREF(intern->read_preference);
} else {
ADD_ASSOC_NULL_EX(&retval, "readPreference");
}
if (!Z_ISUNDEF(intern->session)) {
ADD_ASSOC_ZVAL_EX(&retval, "session", &intern->session);
Z_ADDREF(intern->session);
} else {
ADD_ASSOC_NULL_EX(&retval, "session");
}
ADD_ASSOC_BOOL_EX(&retval, "isDead", !mongoc_cursor_more(intern->cursor));
ADD_ASSOC_LONG_EX(&retval, "currentIndex", intern->current);
if (!Z_ISUNDEF(intern->visitor_data.zchild)) {
ADD_ASSOC_ZVAL_EX(&retval, "currentDocument", &intern->visitor_data.zchild);
Z_ADDREF(intern->visitor_data.zchild);
} else {
ADD_ASSOC_NULL_EX(&retval, "currentDocument");
}
{
zval server;
phongo_server_init(&server, &intern->manager, intern->server_id);
ADD_ASSOC_ZVAL_EX(&retval, "server", &server);
}
return Z_ARRVAL(retval);
}
void php_phongo_cursor_init_ce(INIT_FUNC_ARGS)
{
php_phongo_cursor_ce = register_class_MongoDB_Driver_Cursor(php_phongo_cursor_interface_ce);
php_phongo_cursor_ce->create_object = php_phongo_cursor_create_object;
memcpy(&php_phongo_handler_cursor, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_cursor.get_debug_info = php_phongo_cursor_get_debug_info;
php_phongo_handler_cursor.free_obj = php_phongo_cursor_free_object;
php_phongo_handler_cursor.offset = XtOffsetOf(php_phongo_cursor_t, std);
}
static void phongo_cursor_init(zval* return_value, zval* manager, mongoc_cursor_t* cursor, zval* readPreference, zval* session)
{
php_phongo_cursor_t* intern;
object_init_ex(return_value, php_phongo_cursor_ce);
intern = Z_CURSOR_OBJ_P(return_value);
intern->cursor = cursor;
intern->server_id = mongoc_cursor_get_server_id(cursor);
intern->advanced = false;
intern->current = 0;
ZVAL_ZVAL(&intern->manager, manager, 1, 0);
if (readPreference) {
ZVAL_ZVAL(&intern->read_preference, readPreference, 1, 0);
}
if (session) {
ZVAL_ZVAL(&intern->session, session, 1, 0);
}
}
/* Initialize the cursor for a query and return whether there is an error. This
* function always returns true. */
bool phongo_cursor_init_for_command(zval* return_value, zval* manager, mongoc_cursor_t* cursor, const char* db, zval* command, zval* readPreference, zval* session)
{
php_phongo_cursor_t* intern;
phongo_cursor_init(return_value, manager, cursor, readPreference, session);
intern = Z_CURSOR_OBJ_P(return_value);
intern->database = estrdup(db);
ZVAL_ZVAL(&intern->command, command, 1, 0);
return true;
}
/* Initialize the cursor for a query and return whether there is an error. The
* libmongoc cursor will be advanced once. On error, false is returned and an
* exception is thrown. */
bool phongo_cursor_init_for_query(zval* return_value, zval* manager, mongoc_cursor_t* cursor, const char* namespace, zval* query, zval* readPreference, zval* session)
{
php_phongo_cursor_t* intern;
/* Advancing the cursor before phongo_cursor_init ensures that a server
* stream is obtained before mongoc_cursor_get_server_id() is called. */
if (!phongo_cursor_advance_and_check_for_error(cursor)) {
/* Exception should already have been thrown */
return false;
}
phongo_cursor_init(return_value, manager, cursor, readPreference, session);
intern = Z_CURSOR_OBJ_P(return_value);
intern->advanced = true;
/* The namespace should already have been validated, but we'll still check
* for an error and throw accordingly. */
if (!phongo_split_namespace(namespace, &intern->database, &intern->collection)) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "Cannot initialize cursor with invalid namespace: %s", namespace);
zval_ptr_dtor(return_value);
return false;
}
ZVAL_ZVAL(&intern->query, query, 1, 0);
return true;
}
/* Advance the cursor and return whether there is an error. On error, false is
* returned and an exception is thrown. */
bool phongo_cursor_advance_and_check_for_error(mongoc_cursor_t* cursor)
{
const bson_t* doc = NULL;
if (!mongoc_cursor_next(cursor, &doc)) {
bson_error_t error = { 0 };
/* Check for connection related exceptions */
if (EG(exception)) {
return false;
}
/* Could simply be no docs, which is not an error */
if (mongoc_cursor_error_document(cursor, &error, &doc)) {
phongo_throw_exception_from_bson_error_t_and_reply(&error, doc);
return false;
}
}
return true;
}
mongodb-2.1.0/src/MongoDB/Cursor.h 0000644 0001751 0000166 00000002160 15014033047 013556 0 ustar /*
* Copyright 2022-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_CURSOR_H
#define PHONGO_CURSOR_H
#include "mongoc/mongoc.h"
#include
bool phongo_cursor_init_for_command(zval* return_value, zval* manager, mongoc_cursor_t* cursor, const char* db, zval* command, zval* readPreference, zval* session);
bool phongo_cursor_init_for_query(zval* return_value, zval* manager, mongoc_cursor_t* cursor, const char* namespace, zval* query, zval* readPreference, zval* session);
bool phongo_cursor_advance_and_check_for_error(mongoc_cursor_t* cursor);
#endif /* PHONGO_CURSOR_H */
mongodb-2.1.0/src/MongoDB/CursorInterface.c 0000644 0001751 0000166 00000001641 15014033047 015375 0 ustar /*
* Copyright 2018-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#include
#include "php_phongo.h"
#include "CursorInterface_arginfo.h"
zend_class_entry* php_phongo_cursor_interface_ce;
void php_phongo_cursor_interface_init_ce(INIT_FUNC_ARGS)
{
php_phongo_cursor_interface_ce = register_class_MongoDB_Driver_CursorInterface(zend_ce_iterator);
}
mongodb-2.1.0/src/MongoDB/CursorInterface_arginfo.h 0000644 0001751 0000166 00000005315 15014033047 017111 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 3e304bb86abaff66e9714a02e3a20ec994b444ed */
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_class_MongoDB_Driver_CursorInterface_current, 0, 0, MAY_BE_ARRAY|MAY_BE_OBJECT|MAY_BE_NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_CursorInterface_getId, 0, 0, MongoDB\\BSON\\Int64, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_CursorInterface_getServer, 0, 0, MongoDB\\Driver\\Server, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_CursorInterface_isDead, 0, 0, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_CursorInterface_key, 0, 0, IS_LONG, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_CursorInterface_setTypeMap, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, typemap, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_CursorInterface_toArray, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
static const zend_function_entry class_MongoDB_Driver_CursorInterface_methods[] = {
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_Driver_CursorInterface, current, arginfo_class_MongoDB_Driver_CursorInterface_current, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_Driver_CursorInterface, getId, arginfo_class_MongoDB_Driver_CursorInterface_getId, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_Driver_CursorInterface, getServer, arginfo_class_MongoDB_Driver_CursorInterface_getServer, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_Driver_CursorInterface, isDead, arginfo_class_MongoDB_Driver_CursorInterface_isDead, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_Driver_CursorInterface, key, arginfo_class_MongoDB_Driver_CursorInterface_key, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_Driver_CursorInterface, setTypeMap, arginfo_class_MongoDB_Driver_CursorInterface_setTypeMap, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_ABSTRACT_ME_WITH_FLAGS(MongoDB_Driver_CursorInterface, toArray, arginfo_class_MongoDB_Driver_CursorInterface_toArray, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_CursorInterface(zend_class_entry *class_entry_Iterator)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "CursorInterface", class_MongoDB_Driver_CursorInterface_methods);
class_entry = zend_register_internal_interface(&ce);
zend_class_implements(class_entry, 1, class_entry_Iterator);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Cursor_arginfo.h 0000644 0001751 0000166 00000007434 15014033047 015274 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: e598fccd4b9b82f6da64f43855fa7a302ac86ae8 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_Cursor___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_class_MongoDB_Driver_Cursor_current, 0, 0, MAY_BE_ARRAY|MAY_BE_OBJECT|MAY_BE_NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Cursor_getId, 0, 0, MongoDB\\BSON\\Int64, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Cursor_getServer, 0, 0, MongoDB\\Driver\\Server, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Cursor_isDead, 0, 0, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Cursor_key, 0, 0, IS_LONG, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Cursor_next, 0, 0, IS_VOID, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_Cursor_rewind arginfo_class_MongoDB_Driver_Cursor_next
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Cursor_setTypeMap, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, typemap, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Cursor_toArray, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_Cursor_valid arginfo_class_MongoDB_Driver_Cursor_isDead
static ZEND_METHOD(MongoDB_Driver_Cursor, __construct);
static ZEND_METHOD(MongoDB_Driver_Cursor, current);
static ZEND_METHOD(MongoDB_Driver_Cursor, getId);
static ZEND_METHOD(MongoDB_Driver_Cursor, getServer);
static ZEND_METHOD(MongoDB_Driver_Cursor, isDead);
static ZEND_METHOD(MongoDB_Driver_Cursor, key);
static ZEND_METHOD(MongoDB_Driver_Cursor, next);
static ZEND_METHOD(MongoDB_Driver_Cursor, rewind);
static ZEND_METHOD(MongoDB_Driver_Cursor, setTypeMap);
static ZEND_METHOD(MongoDB_Driver_Cursor, toArray);
static ZEND_METHOD(MongoDB_Driver_Cursor, valid);
static const zend_function_entry class_MongoDB_Driver_Cursor_methods[] = {
ZEND_ME(MongoDB_Driver_Cursor, __construct, arginfo_class_MongoDB_Driver_Cursor___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Cursor, current, arginfo_class_MongoDB_Driver_Cursor_current, ZEND_ACC_PUBLIC)
ZEND_ME(MongoDB_Driver_Cursor, getId, arginfo_class_MongoDB_Driver_Cursor_getId, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Cursor, getServer, arginfo_class_MongoDB_Driver_Cursor_getServer, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Cursor, isDead, arginfo_class_MongoDB_Driver_Cursor_isDead, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Cursor, key, arginfo_class_MongoDB_Driver_Cursor_key, ZEND_ACC_PUBLIC)
ZEND_ME(MongoDB_Driver_Cursor, next, arginfo_class_MongoDB_Driver_Cursor_next, ZEND_ACC_PUBLIC)
ZEND_ME(MongoDB_Driver_Cursor, rewind, arginfo_class_MongoDB_Driver_Cursor_rewind, ZEND_ACC_PUBLIC)
ZEND_ME(MongoDB_Driver_Cursor, setTypeMap, arginfo_class_MongoDB_Driver_Cursor_setTypeMap, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Cursor, toArray, arginfo_class_MongoDB_Driver_Cursor_toArray, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Cursor, valid, arginfo_class_MongoDB_Driver_Cursor_valid, ZEND_ACC_PUBLIC)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Cursor(zend_class_entry *class_entry_MongoDB_Driver_CursorInterface)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "Cursor", class_MongoDB_Driver_Cursor_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
zend_class_implements(class_entry, 1, class_entry_MongoDB_Driver_CursorInterface);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Manager.c 0000644 0001751 0000166 00000065030 15014033047 013653 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bson/bson.h"
#include "mongoc/mongoc.h"
#include
#include
#include
#include "php_array_api.h"
#include "php_phongo.h"
#include "phongo_apm.h"
#include "phongo_client.h"
#include "phongo_error.h"
#include "phongo_execute.h"
#include "phongo_util.h"
#include "MongoDB/ClientEncryption.h"
#include "MongoDB/ReadConcern.h"
#include "MongoDB/ReadPreference.h"
#include "MongoDB/Server.h"
#include "MongoDB/Session.h"
#include "MongoDB/WriteConcern.h"
#include "Manager_arginfo.h"
#define PHONGO_MANAGER_URI_DEFAULT "mongodb://127.0.0.1/"
/**
* Manager abstracts a cluster of Server objects (i.e. socket connections).
*
* Typically, users will connect to a cluster using a URI, and the Manager will
* perform tasks such as replica set discovery and create the necessary Server
* objects. That said, it is also possible to create a Manager with an arbitrary
* collection of Server objects using the static factory method (this can be
* useful for testing or administration).
*
* Operation methods do not take socket-level options (e.g. socketTimeoutMS).
* Those options should be specified during construction.
*/
zend_class_entry* php_phongo_manager_ce;
/* Prepare authMechanismProperties for BSON encoding by converting a boolean
* value for the "CANONICALIZE_HOST_NAME" option to a string.
*
* Note: URI options are case-insensitive, so we must iterate through the
* HashTable in order to detect options. */
static void php_phongo_manager_prep_authmechanismproperties(zval* properties)
{
HashTable* ht_data;
if (Z_TYPE_P(properties) != IS_ARRAY && Z_TYPE_P(properties) != IS_OBJECT) {
return;
}
ht_data = HASH_OF(properties);
{
zend_string* string_key = NULL;
zend_ulong num_key = 0;
zval* property;
ZEND_HASH_FOREACH_KEY_VAL_IND(ht_data, num_key, string_key, property)
{
if (!string_key) {
continue;
}
/* URI options are case-insensitive */
if (!strcasecmp(ZSTR_VAL(string_key), "CANONICALIZE_HOST_NAME")) {
ZVAL_DEREF(property);
if (Z_TYPE_P(property) != IS_STRING && zend_is_true(property)) {
SEPARATE_ZVAL_NOREF(property);
ZVAL_NEW_STR(property, zend_string_init(ZEND_STRL("true"), 0));
}
}
}
ZEND_HASH_FOREACH_END();
}
}
/* Prepare URI options for BSON encoding.
*
* Read preference tag sets must be an array of documents. In order to ensure
* that empty arrays serialize as empty documents, array elements will be
* converted to objects. php_phongo_read_preference_tags_are_valid() handles
* actual validation of the tag set structure.
*
* Auth mechanism properties must have string values, so a boolean true value
* for the "CANONICALIZE_HOST_NAME" property will be converted to "true".
*
* Note: URI options are case-insensitive, so we must iterate through the
* HashTable in order to detect options. */
static void php_phongo_manager_prep_uri_options(zval* options)
{
HashTable* ht_data;
if (Z_TYPE_P(options) != IS_ARRAY) {
return;
}
ht_data = HASH_OF(options);
{
zend_string* string_key = NULL;
zend_ulong num_key = 0;
zval* option;
ZEND_HASH_FOREACH_KEY_VAL_IND(ht_data, num_key, string_key, option)
{
if (!string_key) {
continue;
}
if (!strcasecmp(ZSTR_VAL(string_key), MONGOC_URI_READPREFERENCETAGS)) {
ZVAL_DEREF(option);
SEPARATE_ZVAL_NOREF(option);
php_phongo_read_preference_prep_tagsets(option);
continue;
}
if (!strcasecmp(ZSTR_VAL(string_key), MONGOC_URI_AUTHMECHANISMPROPERTIES)) {
ZVAL_DEREF(option);
SEPARATE_ZVAL_NOREF(option);
php_phongo_manager_prep_authmechanismproperties(option);
continue;
}
}
ZEND_HASH_FOREACH_END();
}
}
/* Selects a server for an execute method. If "for_writes" is true, a primary
* will be selected. Otherwise, a read preference will be used to select the
* server. If zreadPreference is NULL, the client's read preference will be
* used. If zsession is a session object in a sharded transaction, the session
* will be checked whether it is pinned to a server. If so, that server will be
* selected. Otherwise, server selection
*
* On success, server_id will be set and the function will return true;
* otherwise, false is returned and an exception is thrown. */
static bool php_phongo_manager_select_server(bool for_writes, bool inherit_read_preference, zval* zreadPreference, zval* zsession, mongoc_client_t* client, uint32_t* server_id)
{
mongoc_server_description_t* selected_server;
const mongoc_read_prefs_t* read_preference = NULL;
bson_error_t error = { 0 };
if (zsession) {
const mongoc_client_session_t* session = Z_SESSION_OBJ_P(zsession)->client_session;
/* Attempt to fetch server pinned to session */
if (mongoc_client_session_get_server_id(session) > 0) {
*server_id = mongoc_client_session_get_server_id(session);
return true;
}
}
if (!for_writes) {
if (zreadPreference) {
read_preference = phongo_read_preference_from_zval(zreadPreference);
} else if (inherit_read_preference) {
read_preference = mongoc_client_get_read_prefs(client);
}
}
selected_server = mongoc_client_select_server(client, for_writes, read_preference, &error);
if (selected_server) {
*server_id = mongoc_server_description_id(selected_server);
mongoc_server_description_destroy(selected_server);
return true;
}
/* Check for connection related exceptions */
if (!EG(exception)) {
phongo_throw_exception_from_bson_error_t(&error);
}
return false;
}
/* Constructs a new Manager */
static PHP_METHOD(MongoDB_Driver_Manager, __construct)
{
php_phongo_manager_t* intern;
char* uri_string = NULL;
size_t uri_string_len = 0;
zval* options = NULL;
zval* driverOptions = NULL;
intern = Z_MANAGER_OBJ_P(getThis());
/* Separate the options zval, since it may be modified in
* php_phongo_manager_prep_uri_options(). Also separate driverOptions, since
* it may be modified in php_phongo_manager_prepare_manager_for_hash(). */
PHONGO_PARSE_PARAMETERS_START(0, 3)
Z_PARAM_OPTIONAL
Z_PARAM_STRING_OR_NULL(uri_string, uri_string_len)
Z_PARAM_ARRAY_EX(options, 1, 1)
Z_PARAM_ARRAY_EX(driverOptions, 1, 1)
PHONGO_PARSE_PARAMETERS_END();
if (options) {
php_phongo_manager_prep_uri_options(options);
}
phongo_manager_init(intern, uri_string ? uri_string : PHONGO_MANAGER_URI_DEFAULT, options, driverOptions);
if (EG(exception)) {
return;
}
/* Update the request-scoped Manager registry */
if (!php_phongo_manager_register(intern)) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "Failed to add Manager to internal registry");
}
}
/* Registers an event subscriber for this Manager */
static PHP_METHOD(MongoDB_Driver_Manager, addSubscriber)
{
php_phongo_manager_t* intern;
zval* subscriber;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_OBJECT_OF_CLASS(subscriber, php_phongo_subscriber_ce)
PHONGO_PARSE_PARAMETERS_END();
if (instanceof_function(Z_OBJCE_P(subscriber), php_phongo_logsubscriber_ce)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "LogSubscriber instances cannot be registered with a Manager");
}
intern = Z_MANAGER_OBJ_P(getThis());
/* Lazily initialize the subscriber HashTable */
if (!intern->subscribers) {
ALLOC_HASHTABLE(intern->subscribers);
zend_hash_init(intern->subscribers, 0, NULL, ZVAL_PTR_DTOR, 0);
}
phongo_apm_add_subscriber(intern->subscribers, subscriber);
}
/* Return a ClientEncryption instance */
static PHP_METHOD(MongoDB_Driver_Manager, createClientEncryption)
{
zval* options;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(options)
PHONGO_PARSE_PARAMETERS_END();
object_init_ex(return_value, php_phongo_clientencryption_ce);
/* An exception will be thrown on error. */
phongo_clientencryption_init(Z_CLIENTENCRYPTION_OBJ_P(return_value), options, getThis());
}
/* Execute a Command */
static PHP_METHOD(MongoDB_Driver_Manager, executeCommand)
{
php_phongo_manager_t* intern;
char* db;
size_t db_len;
zval* command;
zval* options = NULL;
zval* zreadPreference = NULL;
zval* zsession = NULL;
uint32_t server_id = 0;
PHONGO_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STRING_OR_NULL(db, db_len)
Z_PARAM_OBJECT_OF_CLASS(command, php_phongo_command_ce)
Z_PARAM_OPTIONAL
Z_PARAM_ZVAL_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
intern = Z_MANAGER_OBJ_P(getThis());
if (!phongo_parse_session(options, intern->client, NULL, &zsession)) {
/* Exception should already have been thrown */
return;
}
if (!phongo_parse_read_preference(options, &zreadPreference)) {
/* Exception should already have been thrown */
return;
}
if (!php_phongo_manager_select_server(false, false, zreadPreference, zsession, intern->client, &server_id)) {
/* Exception should already have been thrown */
return;
}
/* If the Manager was created in a different process, reset the client so
* that cursors created by this process can be differentiated and its
* session pool is cleared. */
PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern, intern);
phongo_execute_command(getThis(), PHONGO_COMMAND_RAW, db, command, options, server_id, return_value);
}
/* Execute a ReadCommand */
static PHP_METHOD(MongoDB_Driver_Manager, executeReadCommand)
{
php_phongo_manager_t* intern;
char* db;
size_t db_len;
zval* command;
zval* options = NULL;
zval* zreadPreference = NULL;
uint32_t server_id = 0;
zval* zsession = NULL;
PHONGO_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STRING_OR_NULL(db, db_len)
Z_PARAM_OBJECT_OF_CLASS(command, php_phongo_command_ce)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
intern = Z_MANAGER_OBJ_P(getThis());
if (!phongo_parse_session(options, intern->client, NULL, &zsession)) {
/* Exception should already have been thrown */
return;
}
if (!phongo_parse_read_preference(options, &zreadPreference)) {
/* Exception should already have been thrown */
return;
}
if (!php_phongo_manager_select_server(false, true, zreadPreference, zsession, intern->client, &server_id)) {
/* Exception should already have been thrown */
return;
}
/* If the Manager was created in a different process, reset the client so
* that cursors created by this process can be differentiated and its
* session pool is cleared. */
PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern, intern);
phongo_execute_command(getThis(), PHONGO_COMMAND_READ, db, command, options, server_id, return_value);
}
/* Execute a WriteCommand */
static PHP_METHOD(MongoDB_Driver_Manager, executeWriteCommand)
{
php_phongo_manager_t* intern;
char* db;
size_t db_len;
zval* command;
zval* options = NULL;
uint32_t server_id = 0;
zval* zsession = NULL;
PHONGO_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STRING_OR_NULL(db, db_len)
Z_PARAM_OBJECT_OF_CLASS(command, php_phongo_command_ce)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
intern = Z_MANAGER_OBJ_P(getThis());
if (!phongo_parse_session(options, intern->client, NULL, &zsession)) {
/* Exception should already have been thrown */
return;
}
if (!php_phongo_manager_select_server(true, false, NULL, zsession, intern->client, &server_id)) {
/* Exception should already have been thrown */
return;
}
/* If the Manager was created in a different process, reset the client so
* that cursors created by this process can be differentiated and its
* session pool is cleared. */
PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern, intern);
phongo_execute_command(getThis(), PHONGO_COMMAND_WRITE, db, command, options, server_id, return_value);
}
/* Execute a ReadWriteCommand */
static PHP_METHOD(MongoDB_Driver_Manager, executeReadWriteCommand)
{
php_phongo_manager_t* intern;
char* db;
size_t db_len;
zval* command;
zval* options = NULL;
uint32_t server_id = 0;
zval* zsession = NULL;
PHONGO_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STRING_OR_NULL(db, db_len)
Z_PARAM_OBJECT_OF_CLASS(command, php_phongo_command_ce)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
intern = Z_MANAGER_OBJ_P(getThis());
if (!phongo_parse_session(options, intern->client, NULL, &zsession)) {
/* Exception should already have been thrown */
return;
}
if (!php_phongo_manager_select_server(true, false, NULL, zsession, intern->client, &server_id)) {
/* Exception should already have been thrown */
return;
}
/* If the Manager was created in a different process, reset the client so
* that cursors created by this process can be differentiated and its
* session pool is cleared. */
PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern, intern);
phongo_execute_command(getThis(), PHONGO_COMMAND_READ_WRITE, db, command, options, server_id, return_value);
}
/* Execute a Query */
static PHP_METHOD(MongoDB_Driver_Manager, executeQuery)
{
php_phongo_manager_t* intern;
char* namespace;
size_t namespace_len;
zval* query;
zval* options = NULL;
zval* zreadPreference = NULL;
uint32_t server_id = 0;
zval* zsession = NULL;
PHONGO_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STRING_OR_NULL(namespace, namespace_len)
Z_PARAM_OBJECT_OF_CLASS(query, php_phongo_query_ce)
Z_PARAM_OPTIONAL
Z_PARAM_ZVAL_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
intern = Z_MANAGER_OBJ_P(getThis());
if (!phongo_parse_session(options, intern->client, NULL, &zsession)) {
/* Exception should already have been thrown */
return;
}
if (!phongo_parse_read_preference(options, &zreadPreference)) {
/* Exception should already have been thrown */
return;
}
if (!php_phongo_manager_select_server(false, true, zreadPreference, zsession, intern->client, &server_id)) {
/* Exception should already have been thrown */
return;
}
/* If the Manager was created in a different process, reset the client so
* that cursors created by this process can be differentiated and its
* session pool is cleared. */
PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern, intern);
phongo_execute_query(getThis(), namespace, query, options, server_id, return_value);
}
/* Executes a BulkWrite (i.e. any number of insert, update, and delete ops) */
static PHP_METHOD(MongoDB_Driver_Manager, executeBulkWrite)
{
php_phongo_manager_t* intern;
char* namespace;
size_t namespace_len;
zval* zbulk;
php_phongo_bulkwrite_t* bulk;
zval* options = NULL;
uint32_t server_id = 0;
zval* zsession = NULL;
PHONGO_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STRING_OR_NULL(namespace, namespace_len)
Z_PARAM_OBJECT_OF_CLASS(zbulk, php_phongo_bulkwrite_ce)
Z_PARAM_OPTIONAL
Z_PARAM_ZVAL_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
intern = Z_MANAGER_OBJ_P(getThis());
bulk = Z_BULKWRITE_OBJ_P(zbulk);
if (!phongo_parse_session(options, intern->client, NULL, &zsession)) {
/* Exception should already have been thrown */
return;
}
if (!php_phongo_manager_select_server(true, false, NULL, zsession, intern->client, &server_id)) {
/* Exception should already have been thrown */
return;
}
/* If the Server was created in a different process, reset the client so
* that its session pool is cleared. */
PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern, intern);
phongo_execute_bulk_write(getThis(), namespace, bulk, options, server_id, return_value);
}
/* Executes a BulkWriteCommand (i.e. bulkWrite command for MongoDB 8.0+) */
static PHP_METHOD(MongoDB_Driver_Manager, executeBulkWriteCommand)
{
php_phongo_manager_t* intern;
zval* zbwc;
php_phongo_bulkwritecommand_t* bwc;
zval* zoptions = NULL;
uint32_t server_id = 0;
zval* zsession = NULL;
PHONGO_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_OBJECT_OF_CLASS(zbwc, php_phongo_bulkwritecommand_ce)
Z_PARAM_OPTIONAL
Z_PARAM_ZVAL_OR_NULL(zoptions)
PHONGO_PARSE_PARAMETERS_END();
intern = Z_MANAGER_OBJ_P(getThis());
bwc = Z_BULKWRITECOMMAND_OBJ_P(zbwc);
if (!phongo_parse_session(zoptions, intern->client, NULL, &zsession)) {
/* Exception should already have been thrown */
return;
}
if (!php_phongo_manager_select_server(true, false, NULL, zsession, intern->client, &server_id)) {
/* Exception should already have been thrown */
return;
}
/* If the Server was created in a different process, reset the client so
* that its session pool is cleared. */
PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern, intern);
phongo_execute_bulkwritecommand(getThis(), bwc, zoptions, server_id, return_value);
}
/* Returns the autoEncryption.encryptedFieldsMap driver option */
static PHP_METHOD(MongoDB_Driver_Manager, getEncryptedFieldsMap)
{
php_phongo_manager_t* intern;
intern = Z_MANAGER_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
if (!Z_ISUNDEF(intern->enc_fields_map)) {
RETURN_ZVAL(&intern->enc_fields_map, 1, 0);
}
}
/* Returns the ReadConcern associated with this Manager */
static PHP_METHOD(MongoDB_Driver_Manager, getReadConcern)
{
php_phongo_manager_t* intern;
intern = Z_MANAGER_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
phongo_readconcern_init(return_value, mongoc_client_get_read_concern(intern->client));
}
/* Returns the ReadPreference associated with this Manager */
static PHP_METHOD(MongoDB_Driver_Manager, getReadPreference)
{
php_phongo_manager_t* intern;
intern = Z_MANAGER_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
phongo_readpreference_init(return_value, mongoc_client_get_read_prefs(intern->client));
}
/* Returns the Servers associated with this Manager */
static PHP_METHOD(MongoDB_Driver_Manager, getServers)
{
php_phongo_manager_t* intern;
mongoc_server_description_t** sds;
size_t i, n = 0;
intern = Z_MANAGER_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
sds = mongoc_client_get_server_descriptions(intern->client, &n);
array_init_size(return_value, n);
for (i = 0; i < n; i++) {
zval obj;
phongo_server_init(&obj, getThis(), mongoc_server_description_id(sds[i]));
add_next_index_zval(return_value, &obj);
}
mongoc_server_descriptions_destroy_all(sds, n);
}
/* Returns the WriteConcern associated with this Manager */
static PHP_METHOD(MongoDB_Driver_Manager, getWriteConcern)
{
php_phongo_manager_t* intern;
intern = Z_MANAGER_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
phongo_writeconcern_init(return_value, mongoc_client_get_write_concern(intern->client));
}
/* Unregisters an event subscriber for this Manager */
static PHP_METHOD(MongoDB_Driver_Manager, removeSubscriber)
{
php_phongo_manager_t* intern;
zval* subscriber;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_OBJECT_OF_CLASS(subscriber, php_phongo_subscriber_ce)
PHONGO_PARSE_PARAMETERS_END();
intern = Z_MANAGER_OBJ_P(getThis());
/* NOP if subscribers HashTable was never initialized by addSubscriber */
if (!intern->subscribers) {
return;
}
phongo_apm_remove_subscriber(intern->subscribers, subscriber);
}
/* Selects a Server for the given ReadPreference (default: primary). */
static PHP_METHOD(MongoDB_Driver_Manager, selectServer)
{
php_phongo_manager_t* intern;
zval* zreadPreference = NULL;
uint32_t server_id = 0;
PHONGO_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_OBJECT_OF_CLASS_OR_NULL(zreadPreference, php_phongo_readpreference_ce)
PHONGO_PARSE_PARAMETERS_END();
intern = Z_MANAGER_OBJ_P(getThis());
if (!php_phongo_manager_select_server(false, false, zreadPreference, NULL, intern->client, &server_id)) {
/* Exception should already have been thrown */
return;
}
phongo_server_init(return_value, getThis(), server_id);
}
/* Returns a new client session */
static PHP_METHOD(MongoDB_Driver_Manager, startSession)
{
php_phongo_manager_t* intern;
zval* options = NULL;
mongoc_session_opt_t* cs_opts = NULL;
mongoc_client_session_t* cs;
bson_error_t error = { 0 };
mongoc_transaction_opt_t* txn_opts = NULL;
intern = Z_MANAGER_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
if (options && php_array_existsc(options, "causalConsistency")) {
cs_opts = mongoc_session_opts_new();
mongoc_session_opts_set_causal_consistency(cs_opts, php_array_fetchc_bool(options, "causalConsistency"));
}
if (options && php_array_existsc(options, "defaultTransactionOptions")) {
zval* txn_options = php_array_fetchc_deref(options, "defaultTransactionOptions");
/* Thrown exception and return if the defaultTransactionOptions is not an array */
if (Z_TYPE_P(txn_options) != IS_ARRAY) {
phongo_throw_exception(
PHONGO_ERROR_INVALID_ARGUMENT,
"Expected \"defaultTransactionOptions\" option to be an array, %s given",
zend_zval_type_name(txn_options));
goto cleanup;
}
/* Parse transaction options */
txn_opts = php_mongodb_session_parse_transaction_options(txn_options);
/* If an exception is thrown while parsing, the txn_opts struct is also
* NULL, so no need to free it here */
if (EG(exception)) {
goto cleanup;
}
/* If the options are non-empty, add them to the client session opts struct */
if (txn_opts) {
if (!cs_opts) {
cs_opts = mongoc_session_opts_new();
}
mongoc_session_opts_set_default_transaction_opts(cs_opts, txn_opts);
mongoc_transaction_opts_destroy(txn_opts);
}
}
if (options && php_array_existsc(options, "snapshot")) {
if (!cs_opts) {
cs_opts = mongoc_session_opts_new();
}
mongoc_session_opts_set_snapshot(cs_opts, php_array_fetchc_bool(options, "snapshot"));
}
if (cs_opts && mongoc_session_opts_get_causal_consistency(cs_opts) && mongoc_session_opts_get_snapshot(cs_opts)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Only one of \"causalConsistency\" and \"snapshot\" can be enabled");
goto cleanup;
}
/* If the Manager was created in a different process, reset the client so
* that its session pool is cleared. This will ensure that we do not re-use
* a server session (i.e. LSID) created by a parent process. */
PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern, intern);
cs = mongoc_client_start_session(intern->client, cs_opts, &error);
if (cs) {
phongo_session_init(return_value, getThis(), cs);
} else {
phongo_throw_exception_from_bson_error_t(&error);
}
cleanup:
if (cs_opts) {
mongoc_session_opts_destroy(cs_opts);
}
}
/* MongoDB\Driver\Manager object handlers */
static zend_object_handlers php_phongo_handler_manager;
static void php_phongo_manager_free_object(zend_object* object)
{
php_phongo_manager_t* intern = Z_OBJ_MANAGER(object);
zend_object_std_dtor(&intern->std);
if (intern->client) {
/* Request-scoped clients will be removed from the registry and
* destroyed. This is a NOP for persistent clients. The return value is
* ignored because we can't reasonably report an error here. On the off
* chance any request-scoped clients are missed, they will ultimately be
* destroyed in RSHUTDOWN along with the registry HashTable. */
php_phongo_client_unregister(intern);
}
/* Update the request-scoped Manager registry. The return value is ignored
* because it's possible that the Manager was never registered due to a
* constructor exception.
*
* Note: this is done after unregistering a request-scoped client to ensure
* APM events can be observed by per-client subscribers, which are collected
* in phongo_apm_get_subscribers_to_notify. */
php_phongo_manager_unregister(intern);
if (intern->client_hash) {
efree(intern->client_hash);
}
if (!Z_ISUNDEF(intern->enc_fields_map)) {
zval_ptr_dtor(&intern->enc_fields_map);
}
/* Free the keyVaultClient last to ensure that potential non-persistent
* clients are destroyed in the correct order */
if (!Z_ISUNDEF(intern->key_vault_client_manager)) {
zval_ptr_dtor(&intern->key_vault_client_manager);
}
if (intern->subscribers) {
zend_hash_destroy(intern->subscribers);
FREE_HASHTABLE(intern->subscribers);
}
}
static zend_object* php_phongo_manager_create_object(zend_class_entry* class_type)
{
php_phongo_manager_t* intern = zend_object_alloc(sizeof(php_phongo_manager_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
PHONGO_SET_CREATED_BY_PID(intern);
intern->std.handlers = &php_phongo_handler_manager;
return &intern->std;
}
static HashTable* php_phongo_manager_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_manager_t* intern;
mongoc_server_description_t** sds;
size_t i, n = 0;
zval retval = ZVAL_STATIC_INIT;
zval cluster;
*is_temp = 1;
intern = Z_OBJ_MANAGER(object);
array_init_size(&retval, 2);
ADD_ASSOC_STRING(&retval, "uri", mongoc_uri_get_string(mongoc_client_get_uri(intern->client)));
sds = mongoc_client_get_server_descriptions(intern->client, &n);
array_init_size(&cluster, n);
for (i = 0; i < n; i++) {
zval obj;
if (!php_phongo_server_to_zval(&obj, intern->client, sds[i])) {
/* Exception already thrown */
zval_ptr_dtor(&obj);
zval_ptr_dtor(&cluster);
goto done;
}
add_next_index_zval(&cluster, &obj);
}
ADD_ASSOC_ZVAL_EX(&retval, "cluster", &cluster);
done:
mongoc_server_descriptions_destroy_all(sds, n);
return Z_ARRVAL(retval);
}
void php_phongo_manager_init_ce(INIT_FUNC_ARGS)
{
php_phongo_manager_ce = register_class_MongoDB_Driver_Manager();
php_phongo_manager_ce->create_object = php_phongo_manager_create_object;
memcpy(&php_phongo_handler_manager, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_manager.get_debug_info = php_phongo_manager_get_debug_info;
php_phongo_handler_manager.free_obj = php_phongo_manager_free_object;
php_phongo_handler_manager.offset = XtOffsetOf(php_phongo_manager_t, std);
}
mongodb-2.1.0/src/MongoDB/Manager_arginfo.h 0000644 0001751 0000166 00000017363 15014033047 015373 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 94e08d9aa9d6b2f361f14207a86881c54ee3ff67 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_Manager___construct, 0, 0, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, uri, IS_STRING, 1, "null")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, uriOptions, IS_ARRAY, 1, "null")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, driverOptions, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Manager_addSubscriber, 0, 1, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, subscriber, MongoDB\\Driver\\Monitoring\\Subscriber, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Manager_createClientEncryption, 0, 1, MongoDB\\Driver\\ClientEncryption, 0)
ZEND_ARG_TYPE_INFO(0, options, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Manager_executeBulkWrite, 0, 2, MongoDB\\Driver\\WriteResult, 0)
ZEND_ARG_TYPE_INFO(0, namespace, IS_STRING, 0)
ZEND_ARG_OBJ_INFO(0, bulk, MongoDB\\Driver\\BulkWrite, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Manager_executeBulkWriteCommand, 0, 1, MongoDB\\Driver\\BulkWriteCommandResult, 0)
ZEND_ARG_OBJ_INFO(0, bulkWriteCommand, MongoDB\\Driver\\BulkWriteCommand, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Manager_executeCommand, 0, 2, MongoDB\\Driver\\CursorInterface, 0)
ZEND_ARG_TYPE_INFO(0, db, IS_STRING, 0)
ZEND_ARG_OBJ_INFO(0, command, MongoDB\\Driver\\Command, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Manager_executeQuery, 0, 2, MongoDB\\Driver\\CursorInterface, 0)
ZEND_ARG_TYPE_INFO(0, namespace, IS_STRING, 0)
ZEND_ARG_OBJ_INFO(0, query, MongoDB\\Driver\\Query, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_Manager_executeReadCommand arginfo_class_MongoDB_Driver_Manager_executeCommand
#define arginfo_class_MongoDB_Driver_Manager_executeReadWriteCommand arginfo_class_MongoDB_Driver_Manager_executeCommand
#define arginfo_class_MongoDB_Driver_Manager_executeWriteCommand arginfo_class_MongoDB_Driver_Manager_executeCommand
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_class_MongoDB_Driver_Manager_getEncryptedFieldsMap, 0, 0, MAY_BE_ARRAY|MAY_BE_OBJECT|MAY_BE_NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Manager_getReadConcern, 0, 0, MongoDB\\Driver\\ReadConcern, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Manager_getReadPreference, 0, 0, MongoDB\\Driver\\ReadPreference, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Manager_getServers, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Manager_getWriteConcern, 0, 0, MongoDB\\Driver\\WriteConcern, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_Manager_removeSubscriber arginfo_class_MongoDB_Driver_Manager_addSubscriber
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Manager_selectServer, 0, 0, MongoDB\\Driver\\Server, 0)
ZEND_ARG_OBJ_INFO_WITH_DEFAULT_VALUE(0, readPreference, MongoDB\\Driver\\ReadPreference, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Manager_startSession, 0, 0, MongoDB\\Driver\\Session, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_Manager, __construct);
static ZEND_METHOD(MongoDB_Driver_Manager, addSubscriber);
static ZEND_METHOD(MongoDB_Driver_Manager, createClientEncryption);
static ZEND_METHOD(MongoDB_Driver_Manager, executeBulkWrite);
static ZEND_METHOD(MongoDB_Driver_Manager, executeBulkWriteCommand);
static ZEND_METHOD(MongoDB_Driver_Manager, executeCommand);
static ZEND_METHOD(MongoDB_Driver_Manager, executeQuery);
static ZEND_METHOD(MongoDB_Driver_Manager, executeReadCommand);
static ZEND_METHOD(MongoDB_Driver_Manager, executeReadWriteCommand);
static ZEND_METHOD(MongoDB_Driver_Manager, executeWriteCommand);
static ZEND_METHOD(MongoDB_Driver_Manager, getEncryptedFieldsMap);
static ZEND_METHOD(MongoDB_Driver_Manager, getReadConcern);
static ZEND_METHOD(MongoDB_Driver_Manager, getReadPreference);
static ZEND_METHOD(MongoDB_Driver_Manager, getServers);
static ZEND_METHOD(MongoDB_Driver_Manager, getWriteConcern);
static ZEND_METHOD(MongoDB_Driver_Manager, removeSubscriber);
static ZEND_METHOD(MongoDB_Driver_Manager, selectServer);
static ZEND_METHOD(MongoDB_Driver_Manager, startSession);
static const zend_function_entry class_MongoDB_Driver_Manager_methods[] = {
ZEND_ME(MongoDB_Driver_Manager, __construct, arginfo_class_MongoDB_Driver_Manager___construct, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Manager, addSubscriber, arginfo_class_MongoDB_Driver_Manager_addSubscriber, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Manager, createClientEncryption, arginfo_class_MongoDB_Driver_Manager_createClientEncryption, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Manager, executeBulkWrite, arginfo_class_MongoDB_Driver_Manager_executeBulkWrite, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Manager, executeBulkWriteCommand, arginfo_class_MongoDB_Driver_Manager_executeBulkWriteCommand, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Manager, executeCommand, arginfo_class_MongoDB_Driver_Manager_executeCommand, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Manager, executeQuery, arginfo_class_MongoDB_Driver_Manager_executeQuery, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Manager, executeReadCommand, arginfo_class_MongoDB_Driver_Manager_executeReadCommand, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Manager, executeReadWriteCommand, arginfo_class_MongoDB_Driver_Manager_executeReadWriteCommand, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Manager, executeWriteCommand, arginfo_class_MongoDB_Driver_Manager_executeWriteCommand, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Manager, getEncryptedFieldsMap, arginfo_class_MongoDB_Driver_Manager_getEncryptedFieldsMap, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Manager, getReadConcern, arginfo_class_MongoDB_Driver_Manager_getReadConcern, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Manager, getReadPreference, arginfo_class_MongoDB_Driver_Manager_getReadPreference, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Manager, getServers, arginfo_class_MongoDB_Driver_Manager_getServers, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Manager, getWriteConcern, arginfo_class_MongoDB_Driver_Manager_getWriteConcern, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Manager, removeSubscriber, arginfo_class_MongoDB_Driver_Manager_removeSubscriber, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Manager, selectServer, arginfo_class_MongoDB_Driver_Manager_selectServer, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Manager, startSession, arginfo_class_MongoDB_Driver_Manager_startSession, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Manager(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "Manager", class_MongoDB_Driver_Manager_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Query.c 0000644 0001751 0000166 00000034761 15014033047 013415 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bson/bson.h"
#include "mongoc/mongoc.h"
#include
#include
#include "php_array_api.h"
#include "php_phongo.h"
#include "phongo_bson_encode.h"
#include "phongo_error.h"
#include "MongoDB/Query.h"
#include "MongoDB/ReadConcern.h"
#include "Query_arginfo.h"
zend_class_entry* php_phongo_query_ce;
/* Appends a string field into the BSON options. Returns true on success;
* otherwise, false is returned and an exception is thrown. */
static bool php_phongo_query_opts_append_string(bson_t* opts, const char* opts_key, zval* zarr, const char* zarr_key)
{
zval* value = php_array_fetch_deref(zarr, zarr_key);
if (Z_TYPE_P(value) != IS_STRING) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"%s\" option to be string, %s given", zarr_key, zend_zval_type_name(value));
return false;
}
if (!bson_append_utf8(opts, opts_key, strlen(opts_key), Z_STRVAL_P(value), Z_STRLEN_P(value))) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Error appending \"%s\" option", opts_key);
return false;
}
return true;
}
/* Appends a document field for the given opts document and key. Returns true on
* success; otherwise, false is returned and an exception is thrown. */
static bool php_phongo_query_opts_append_document(bson_t* opts, const char* opts_key, zval* zarr, const char* zarr_key)
{
zval* value = php_array_fetch_deref(zarr, zarr_key);
bson_t b = BSON_INITIALIZER;
if (Z_TYPE_P(value) != IS_OBJECT && Z_TYPE_P(value) != IS_ARRAY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"%s\" option to be array or object, %s given", zarr_key, zend_zval_type_name(value));
return false;
}
php_phongo_zval_to_bson(value, PHONGO_BSON_NONE, &b, NULL);
if (EG(exception)) {
bson_destroy(&b);
return false;
}
if (!bson_validate(&b, BSON_VALIDATE_EMPTY_KEYS, NULL)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Cannot use empty keys in \"%s\" option", zarr_key);
bson_destroy(&b);
return false;
}
if (!BSON_APPEND_DOCUMENT(opts, opts_key, &b)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Error appending \"%s\" option", opts_key);
bson_destroy(&b);
return false;
}
bson_destroy(&b);
return true;
}
/* Appends an arbitrary BSON value for the given opts document and key. Returns
* true on success; otherwise, false is returned and an exception is thrown. */
static bool php_phongo_query_opts_append_value(bson_t* opts, const char* opts_key, zval* zarr, const char* zarr_key)
{
bson_value_t value = { 0 };
phongo_zval_to_bson_value(php_array_fetch(zarr, zarr_key), &value);
if (EG(exception)) {
/* Exception should already have been thrown */
bson_value_destroy(&value);
return false;
}
if (!BSON_APPEND_VALUE(opts, opts_key, &value)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Error appending \"%s\" option", opts_key);
bson_value_destroy(&value);
return false;
}
bson_value_destroy(&value);
return true;
}
#define PHONGO_QUERY_OPT_BOOL(opt, zarr, key) \
if ((zarr) && php_array_existsc((zarr), (key))) { \
if (!BSON_APPEND_BOOL(intern->opts, (opt), php_array_fetchc_bool((zarr), (key)))) { \
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Error appending \"%s\" option", (opt)); \
return false; \
} \
}
#define PHONGO_QUERY_OPT_BSON_VALUE(opt, zarr, key) \
if ((zarr) && php_array_existsc((zarr), (key))) { \
if (!php_phongo_query_opts_append_value(intern->opts, (opt), (zarr), (key))) { \
return false; \
} \
}
#define PHONGO_QUERY_OPT_DOCUMENT(opt, zarr, key) \
if ((zarr) && php_array_existsc((zarr), (key))) { \
if (!php_phongo_query_opts_append_document(intern->opts, (opt), (zarr), (key))) { \
return false; \
} \
}
/* Note: handling of integer options will depend on SIZEOF_ZEND_LONG and we
* are not converting strings to 64-bit integers for 32-bit platforms. */
#define PHONGO_QUERY_OPT_INT64(opt, zarr, key) \
if ((zarr) && php_array_existsc((zarr), (key))) { \
if (!BSON_APPEND_INT64(intern->opts, (opt), php_array_fetchc_long((zarr), (key)))) { \
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Error appending \"%s\" option", (opt)); \
return false; \
} \
}
#define PHONGO_QUERY_OPT_STRING(opt, zarr, key) \
if ((zarr) && php_array_existsc((zarr), (key))) { \
if (!php_phongo_query_opts_append_string(intern->opts, (opt), (zarr), (key))) { \
return false; \
} \
}
/* Initialize the "hint" option. Returns true on success; otherwise, false is
* returned and an exception is thrown.
*
* The "hint" option must be a string or document. Check for both types and
* merge into BSON options accordingly. */
static bool php_phongo_query_init_hint(php_phongo_query_t* intern, zval* options)
{
if (php_array_existsc(options, "hint")) {
zend_uchar type = Z_TYPE_P(php_array_fetchc_deref(options, "hint"));
if (type == IS_STRING) {
PHONGO_QUERY_OPT_STRING("hint", options, "hint");
} else if (type == IS_OBJECT || type == IS_ARRAY) {
PHONGO_QUERY_OPT_DOCUMENT("hint", options, "hint");
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"hint\" option to be string, array, or object, %s given", zend_get_type_by_const(type));
return false;
}
}
return true;
}
/* Initialize the "readConcern" option. Returns true on success; otherwise,
* false is returned and an exception is thrown.
*
* The "readConcern" option should be a MongoDB\Driver\ReadConcern instance,
* which must be converted to a mongoc_read_concern_t. */
static bool php_phongo_query_init_readconcern(php_phongo_query_t* intern, zval* options)
{
zval* read_concern;
if (!php_array_existsc(options, "readConcern")) {
return true;
}
read_concern = php_array_fetchc_deref(options, "readConcern");
if (Z_TYPE_P(read_concern) != IS_OBJECT || !instanceof_function(Z_OBJCE_P(read_concern), php_phongo_readconcern_ce)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"readConcern\" option to be %s, %s given", ZSTR_VAL(php_phongo_readconcern_ce->name), zend_zval_type_name(read_concern));
return false;
}
intern->read_concern = mongoc_read_concern_copy(phongo_read_concern_from_zval(read_concern));
return true;
}
/* Initialize the "maxAwaitTimeMS" option. Returns true on success; otherwise,
* false is returned and an exception is thrown.
*
* The "maxAwaitTimeMS" option is assigned to the cursor after query execution
* via mongoc_cursor_set_max_await_time_ms(). */
static bool php_phongo_query_init_max_await_time_ms(php_phongo_query_t* intern, zval* options)
{
int64_t max_await_time_ms;
if (!php_array_existsc(options, "maxAwaitTimeMS")) {
return true;
}
max_await_time_ms = php_array_fetchc_long(options, "maxAwaitTimeMS");
if (max_await_time_ms < 0) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"maxAwaitTimeMS\" option to be >= 0, %" PRId64 " given", max_await_time_ms);
return false;
}
if (max_await_time_ms > UINT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"maxAwaitTimeMS\" option to be <= %" PRIu32 ", %" PRId64 " given", UINT32_MAX, max_await_time_ms);
return false;
}
intern->max_await_time_ms = (uint32_t) max_await_time_ms;
return true;
}
/* Initializes the query from filter and options arguments and returns whether
* an error occurred. If query is undefined, it will be initialized. */
bool phongo_query_init(zval* return_value, zval* filter, zval* options)
{
php_phongo_query_t* intern;
if (Z_ISUNDEF_P(return_value)) {
object_init_ex(return_value, php_phongo_query_ce);
}
if (Z_TYPE_P(return_value) != IS_OBJECT || !instanceof_function(Z_OBJCE_P(return_value), php_phongo_query_ce)) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "Expected initialization object to be %s, %s given", ZSTR_VAL(php_phongo_query_ce->name), zend_zval_type_name(return_value));
return false;
}
intern = Z_QUERY_OBJ_P(return_value);
intern->filter = bson_new();
intern->opts = bson_new();
intern->max_await_time_ms = 0;
if (filter) {
php_phongo_zval_to_bson(filter, PHONGO_BSON_NONE, intern->filter, NULL);
}
/* Note: if any exceptions are thrown, we can simply return as PHP will
* invoke php_phongo_query_free_object to destruct the object. */
if (EG(exception)) {
return false;
}
if (!bson_validate(intern->filter, BSON_VALIDATE_EMPTY_KEYS, NULL)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Cannot use empty keys in filter document");
return false;
}
if (!options) {
return true;
}
PHONGO_QUERY_OPT_BOOL("allowDiskUse", options, "allowDiskUse");
PHONGO_QUERY_OPT_BOOL("allowPartialResults", options, "allowPartialResults");
PHONGO_QUERY_OPT_BOOL("awaitData", options, "awaitData");
PHONGO_QUERY_OPT_INT64("batchSize", options, "batchSize");
PHONGO_QUERY_OPT_DOCUMENT("collation", options, "collation");
PHONGO_QUERY_OPT_BSON_VALUE("comment", options, "comment");
PHONGO_QUERY_OPT_BOOL("exhaust", options, "exhaust");
PHONGO_QUERY_OPT_DOCUMENT("let", options, "let");
PHONGO_QUERY_OPT_INT64("limit", options, "limit");
PHONGO_QUERY_OPT_DOCUMENT("max", options, "max");
PHONGO_QUERY_OPT_INT64("maxTimeMS", options, "maxTimeMS");
PHONGO_QUERY_OPT_DOCUMENT("min", options, "min");
PHONGO_QUERY_OPT_BOOL("noCursorTimeout", options, "noCursorTimeout");
PHONGO_QUERY_OPT_DOCUMENT("projection", options, "projection");
PHONGO_QUERY_OPT_BOOL("returnKey", options, "returnKey");
PHONGO_QUERY_OPT_BOOL("showRecordId", options, "showRecordId");
PHONGO_QUERY_OPT_BOOL("singleBatch", options, "singleBatch");
PHONGO_QUERY_OPT_INT64("skip", options, "skip");
PHONGO_QUERY_OPT_DOCUMENT("sort", options, "sort");
PHONGO_QUERY_OPT_BOOL("tailable", options, "tailable");
if (!php_phongo_query_init_hint(intern, options)) {
return false;
}
if (!php_phongo_query_init_readconcern(intern, options)) {
return false;
}
if (!php_phongo_query_init_max_await_time_ms(intern, options)) {
return false;
}
return true;
}
#undef PHONGO_QUERY_OPT_BOOL
#undef PHONGO_QUERY_OPT_BSON_VALUE
#undef PHONGO_QUERY_OPT_DOCUMENT
#undef PHONGO_QUERY_OPT_INT64
#undef PHONGO_QUERY_OPT_STRING
/* Constructs a new Query */
static PHP_METHOD(MongoDB_Driver_Query, __construct)
{
zval* filter;
zval* options = NULL;
PHONGO_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_ARRAY_OR_OBJECT(filter)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
phongo_query_init(getThis(), filter, options);
}
/* MongoDB\Driver\Query object handlers */
static zend_object_handlers php_phongo_handler_query;
static void php_phongo_query_free_object(zend_object* object)
{
php_phongo_query_t* intern = Z_OBJ_QUERY(object);
zend_object_std_dtor(&intern->std);
if (intern->filter) {
bson_clear(&intern->filter);
}
if (intern->opts) {
bson_clear(&intern->opts);
}
if (intern->read_concern) {
mongoc_read_concern_destroy(intern->read_concern);
}
}
static zend_object* php_phongo_query_create_object(zend_class_entry* class_type)
{
php_phongo_query_t* intern = zend_object_alloc(sizeof(php_phongo_query_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_query;
return &intern->std;
}
static HashTable* php_phongo_query_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_query_t* intern;
zval retval = ZVAL_STATIC_INIT;
*is_temp = 1;
intern = Z_OBJ_QUERY(object);
array_init_size(&retval, 3);
/* Avoid using PHONGO_TYPEMAP_NATIVE_ARRAY for decoding filter and opts
* documents so that users can differentiate BSON arrays and documents. */
if (intern->filter) {
zval zv;
if (!php_phongo_bson_to_zval(intern->filter, &zv)) {
zval_ptr_dtor(&zv);
goto done;
}
ADD_ASSOC_ZVAL_EX(&retval, "filter", &zv);
} else {
ADD_ASSOC_NULL_EX(&retval, "filter");
}
if (intern->opts) {
zval zv;
if (!php_phongo_bson_to_zval(intern->opts, &zv)) {
zval_ptr_dtor(&zv);
goto done;
}
ADD_ASSOC_ZVAL_EX(&retval, "options", &zv);
} else {
ADD_ASSOC_NULL_EX(&retval, "options");
}
if (intern->read_concern) {
zval read_concern;
php_phongo_read_concern_to_zval(&read_concern, intern->read_concern);
ADD_ASSOC_ZVAL_EX(&retval, "readConcern", &read_concern);
} else {
ADD_ASSOC_NULL_EX(&retval, "readConcern");
}
done:
return Z_ARRVAL(retval);
}
void php_phongo_query_init_ce(INIT_FUNC_ARGS)
{
php_phongo_query_ce = register_class_MongoDB_Driver_Query();
php_phongo_query_ce->create_object = php_phongo_query_create_object;
memcpy(&php_phongo_handler_query, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_query.get_debug_info = php_phongo_query_get_debug_info;
php_phongo_handler_query.free_obj = php_phongo_query_free_object;
php_phongo_handler_query.offset = XtOffsetOf(php_phongo_query_t, std);
}
mongodb-2.1.0/src/MongoDB/Query.h 0000644 0001751 0000166 00000001403 15014033047 013405 0 ustar /*
* Copyright 2022-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_QUERY_H
#define PHONGO_QUERY_H
#include
bool phongo_query_init(zval* return_value, zval* filter, zval* options);
#endif /* PHONGO_QUERY_H */
mongodb-2.1.0/src/MongoDB/Query_arginfo.h 0000644 0001751 0000166 00000001730 15014033047 015115 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 819affbb75a46cb68d88b46e0c7137590408b010 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_Query___construct, 0, 0, 1)
ZEND_ARG_TYPE_MASK(0, filter, MAY_BE_ARRAY|MAY_BE_OBJECT, NULL)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, queryOptions, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_Query, __construct);
static const zend_function_entry class_MongoDB_Driver_Query_methods[] = {
ZEND_ME(MongoDB_Driver_Query, __construct, arginfo_class_MongoDB_Driver_Query___construct, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Query(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "Query", class_MongoDB_Driver_Query_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
mongodb-2.1.0/src/MongoDB/ReadConcern.c 0000644 0001751 0000166 00000016230 15014033047 014462 0 ustar /*
* Copyright 2015-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mongoc/mongoc.h"
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "ReadConcern_arginfo.h"
zend_class_entry* php_phongo_readconcern_ce;
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_readconcern_init_from_hash(php_phongo_readconcern_t* intern, HashTable* props)
{
zval* level;
intern->read_concern = mongoc_read_concern_new();
if ((level = zend_hash_str_find(props, "level", sizeof("level") - 1))) {
if (Z_TYPE_P(level) == IS_STRING) {
mongoc_read_concern_set_level(intern->read_concern, Z_STRVAL_P(level));
return true;
}
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"level\" string field", ZSTR_VAL(php_phongo_readconcern_ce->name));
goto failure;
}
return true;
failure:
mongoc_read_concern_destroy(intern->read_concern);
intern->read_concern = NULL;
return false;
}
/* Constructs a new ReadConcern */
static PHP_METHOD(MongoDB_Driver_ReadConcern, __construct)
{
php_phongo_readconcern_t* intern;
char* level = NULL;
size_t level_len = 0;
intern = Z_READCONCERN_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_STRING_OR_NULL(level, level_len)
PHONGO_PARSE_PARAMETERS_END();
intern->read_concern = mongoc_read_concern_new();
if (level) {
mongoc_read_concern_set_level(intern->read_concern, level);
}
}
static PHP_METHOD(MongoDB_Driver_ReadConcern, __set_state)
{
php_phongo_readconcern_t* intern;
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
object_init_ex(return_value, php_phongo_readconcern_ce);
intern = Z_READCONCERN_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_readconcern_init_from_hash(intern, props);
}
/* Returns the ReadConcern "level" option */
static PHP_METHOD(MongoDB_Driver_ReadConcern, getLevel)
{
php_phongo_readconcern_t* intern;
const char* level;
intern = Z_READCONCERN_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
level = mongoc_read_concern_get_level(intern->read_concern);
if (level) {
RETURN_STRING(level);
}
RETURN_NULL();
}
/* Returns whether the read concern has not been modified (i.e. constructed
without a level or from a Manager with no read concern URI options). */
static PHP_METHOD(MongoDB_Driver_ReadConcern, isDefault)
{
php_phongo_readconcern_t* intern;
intern = Z_READCONCERN_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_BOOL(mongoc_read_concern_is_default(intern->read_concern));
}
static HashTable* php_phongo_readconcern_get_properties_hash(zend_object* object, bool is_temp)
{
php_phongo_readconcern_t* intern;
HashTable* props;
const char* level;
intern = Z_OBJ_READCONCERN(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_temp, intern, props, 1);
if (!intern->read_concern) {
return props;
}
level = mongoc_read_concern_get_level(intern->read_concern);
if (level) {
zval z_level;
ZVAL_STRING(&z_level, level);
zend_hash_str_update(props, "level", sizeof("level") - 1, &z_level);
}
return props;
}
static PHP_METHOD(MongoDB_Driver_ReadConcern, bsonSerialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
ZVAL_ARR(return_value, php_phongo_readconcern_get_properties_hash(Z_OBJ_P(getThis()), true));
convert_to_object(return_value);
}
static PHP_METHOD(MongoDB_Driver_ReadConcern, __serialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_ARR(php_phongo_readconcern_get_properties_hash(Z_OBJ_P(getThis()), true));
}
static PHP_METHOD(MongoDB_Driver_ReadConcern, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_readconcern_init_from_hash(Z_READCONCERN_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\Driver\ReadConcern object handlers */
static zend_object_handlers php_phongo_handler_readconcern;
static void php_phongo_readconcern_free_object(zend_object* object)
{
php_phongo_readconcern_t* intern = Z_OBJ_READCONCERN(object);
zend_object_std_dtor(&intern->std);
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
if (intern->read_concern) {
mongoc_read_concern_destroy(intern->read_concern);
}
}
static zend_object* php_phongo_readconcern_create_object(zend_class_entry* class_type)
{
php_phongo_readconcern_t* intern = zend_object_alloc(sizeof(php_phongo_readconcern_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_readconcern;
return &intern->std;
}
static HashTable* php_phongo_readconcern_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return php_phongo_readconcern_get_properties_hash(object, true);
}
static HashTable* php_phongo_readconcern_get_properties(zend_object* object)
{
return php_phongo_readconcern_get_properties_hash(object, false);
}
void php_phongo_readconcern_init_ce(INIT_FUNC_ARGS)
{
php_phongo_readconcern_ce = register_class_MongoDB_Driver_ReadConcern(php_phongo_serializable_ce);
php_phongo_readconcern_ce->create_object = php_phongo_readconcern_create_object;
memcpy(&php_phongo_handler_readconcern, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_readconcern.get_debug_info = php_phongo_readconcern_get_debug_info;
php_phongo_handler_readconcern.get_properties = php_phongo_readconcern_get_properties;
php_phongo_handler_readconcern.free_obj = php_phongo_readconcern_free_object;
php_phongo_handler_readconcern.offset = XtOffsetOf(php_phongo_readconcern_t, std);
}
void phongo_readconcern_init(zval* return_value, const mongoc_read_concern_t* read_concern)
{
php_phongo_readconcern_t* intern;
object_init_ex(return_value, php_phongo_readconcern_ce);
intern = Z_READCONCERN_OBJ_P(return_value);
intern->read_concern = mongoc_read_concern_copy(read_concern);
}
const mongoc_read_concern_t* phongo_read_concern_from_zval(zval* zread_concern)
{
if (zread_concern) {
php_phongo_readconcern_t* intern = Z_READCONCERN_OBJ_P(zread_concern);
if (intern) {
return intern->read_concern;
}
}
return NULL;
}
void php_phongo_read_concern_to_zval(zval* retval, const mongoc_read_concern_t* read_concern)
{
const char* level = mongoc_read_concern_get_level(read_concern);
array_init_size(retval, 1);
if (level) {
ADD_ASSOC_STRING(retval, "level", level);
}
}
mongodb-2.1.0/src/MongoDB/ReadConcern.h 0000644 0001751 0000166 00000001767 15014033047 014500 0 ustar /*
* Copyright 2022-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_READCONCERN_H
#define PHONGO_READCONCERN_H
#include "mongoc/mongoc.h"
#include
void phongo_readconcern_init(zval* return_value, const mongoc_read_concern_t* read_concern);
const mongoc_read_concern_t* phongo_read_concern_from_zval(zval* zread_concern);
void php_phongo_read_concern_to_zval(zval* retval, const mongoc_read_concern_t* read_concern);
#endif /* PHONGO_READCONCERN_H */
mongodb-2.1.0/src/MongoDB/ReadConcern_arginfo.h 0000644 0001751 0000166 00000013010 15014033047 016165 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 2eb20e3e6be24e99cbbfe9d7888d5b8b99fc609f */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_ReadConcern___construct, 0, 0, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, level, IS_STRING, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_ReadConcern_getLevel, 0, 0, IS_STRING, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_ReadConcern_isDefault, 0, 0, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_ReadConcern___set_state, 0, 1, MongoDB\\Driver\\ReadConcern, 0)
ZEND_ARG_TYPE_INFO(0, properties, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_ReadConcern_bsonSerialize, 0, 0, stdClass, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_ReadConcern___unserialize, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_ReadConcern___serialize, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_ReadConcern, __construct);
static ZEND_METHOD(MongoDB_Driver_ReadConcern, getLevel);
static ZEND_METHOD(MongoDB_Driver_ReadConcern, isDefault);
static ZEND_METHOD(MongoDB_Driver_ReadConcern, __set_state);
static ZEND_METHOD(MongoDB_Driver_ReadConcern, bsonSerialize);
static ZEND_METHOD(MongoDB_Driver_ReadConcern, __unserialize);
static ZEND_METHOD(MongoDB_Driver_ReadConcern, __serialize);
static const zend_function_entry class_MongoDB_Driver_ReadConcern_methods[] = {
ZEND_ME(MongoDB_Driver_ReadConcern, __construct, arginfo_class_MongoDB_Driver_ReadConcern___construct, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ReadConcern, getLevel, arginfo_class_MongoDB_Driver_ReadConcern_getLevel, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ReadConcern, isDefault, arginfo_class_MongoDB_Driver_ReadConcern_isDefault, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ReadConcern, __set_state, arginfo_class_MongoDB_Driver_ReadConcern___set_state, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ReadConcern, bsonSerialize, arginfo_class_MongoDB_Driver_ReadConcern_bsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ReadConcern, __unserialize, arginfo_class_MongoDB_Driver_ReadConcern___unserialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ReadConcern, __serialize, arginfo_class_MongoDB_Driver_ReadConcern___serialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_ReadConcern(zend_class_entry *class_entry_MongoDB_BSON_Serializable)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "ReadConcern", class_MongoDB_Driver_ReadConcern_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
zend_class_implements(class_entry, 1, class_entry_MongoDB_BSON_Serializable);
zval const_LINEARIZABLE_value;
zend_string *const_LINEARIZABLE_value_str = zend_string_init(MONGOC_READ_CONCERN_LEVEL_LINEARIZABLE, strlen(MONGOC_READ_CONCERN_LEVEL_LINEARIZABLE), 1);
ZVAL_STR(&const_LINEARIZABLE_value, const_LINEARIZABLE_value_str);
zend_string *const_LINEARIZABLE_name = zend_string_init_interned("LINEARIZABLE", sizeof("LINEARIZABLE") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_LINEARIZABLE_name, &const_LINEARIZABLE_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_LINEARIZABLE_name);
zval const_LOCAL_value;
zend_string *const_LOCAL_value_str = zend_string_init(MONGOC_READ_CONCERN_LEVEL_LOCAL, strlen(MONGOC_READ_CONCERN_LEVEL_LOCAL), 1);
ZVAL_STR(&const_LOCAL_value, const_LOCAL_value_str);
zend_string *const_LOCAL_name = zend_string_init_interned("LOCAL", sizeof("LOCAL") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_LOCAL_name, &const_LOCAL_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_LOCAL_name);
zval const_MAJORITY_value;
zend_string *const_MAJORITY_value_str = zend_string_init(MONGOC_READ_CONCERN_LEVEL_MAJORITY, strlen(MONGOC_READ_CONCERN_LEVEL_MAJORITY), 1);
ZVAL_STR(&const_MAJORITY_value, const_MAJORITY_value_str);
zend_string *const_MAJORITY_name = zend_string_init_interned("MAJORITY", sizeof("MAJORITY") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_MAJORITY_name, &const_MAJORITY_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_MAJORITY_name);
zval const_AVAILABLE_value;
zend_string *const_AVAILABLE_value_str = zend_string_init(MONGOC_READ_CONCERN_LEVEL_AVAILABLE, strlen(MONGOC_READ_CONCERN_LEVEL_AVAILABLE), 1);
ZVAL_STR(&const_AVAILABLE_value, const_AVAILABLE_value_str);
zend_string *const_AVAILABLE_name = zend_string_init_interned("AVAILABLE", sizeof("AVAILABLE") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_AVAILABLE_name, &const_AVAILABLE_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_AVAILABLE_name);
zval const_SNAPSHOT_value;
zend_string *const_SNAPSHOT_value_str = zend_string_init(MONGOC_READ_CONCERN_LEVEL_SNAPSHOT, strlen(MONGOC_READ_CONCERN_LEVEL_SNAPSHOT), 1);
ZVAL_STR(&const_SNAPSHOT_value, const_SNAPSHOT_value_str);
zend_string *const_SNAPSHOT_name = zend_string_init_interned("SNAPSHOT", sizeof("SNAPSHOT") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_SNAPSHOT_name, &const_SNAPSHOT_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_SNAPSHOT_name);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/ReadPreference.c 0000644 0001751 0000166 00000047525 15014033047 015164 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bson/bson.h"
#include "mongoc/mongoc.h"
#include
#include
#include "php_array_api.h"
#include "php_phongo.h"
#include "phongo_bson_encode.h"
#include "phongo_error.h"
#include "MongoDB/ReadPreference.h"
#include "ReadPreference_arginfo.h"
zend_class_entry* php_phongo_readpreference_ce;
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_readpreference_init_from_hash(php_phongo_readpreference_t* intern, HashTable* props)
{
zval *mode, *tagSets, *maxStalenessSeconds, *hedge;
if ((mode = zend_hash_str_find(props, "mode", sizeof("mode") - 1)) && Z_TYPE_P(mode) == IS_STRING) {
if (strcasecmp(Z_STRVAL_P(mode), PHONGO_READ_PRIMARY) == 0) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_PRIMARY);
} else if (strcasecmp(Z_STRVAL_P(mode), PHONGO_READ_PRIMARY_PREFERRED) == 0) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_PRIMARY_PREFERRED);
} else if (strcasecmp(Z_STRVAL_P(mode), PHONGO_READ_SECONDARY) == 0) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_SECONDARY);
} else if (strcasecmp(Z_STRVAL_P(mode), PHONGO_READ_SECONDARY_PREFERRED) == 0) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_SECONDARY_PREFERRED);
} else if (strcasecmp(Z_STRVAL_P(mode), PHONGO_READ_NEAREST) == 0) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_NEAREST);
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires specific values for \"mode\" string field", ZSTR_VAL(php_phongo_readpreference_ce->name));
return false;
}
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"mode\" field to be string", ZSTR_VAL(php_phongo_readpreference_ce->name));
return false;
}
if ((tagSets = zend_hash_str_find(props, "tags", sizeof("tags") - 1))) {
ZVAL_DEREF(tagSets);
if (Z_TYPE_P(tagSets) == IS_ARRAY) {
bson_t* tags = bson_new();
/* Separate tagSets as php_phongo_read_preference_prep_tagsets may
* modify these tags. */
SEPARATE_ZVAL_NOREF(tagSets);
php_phongo_read_preference_prep_tagsets(tagSets);
php_phongo_zval_to_bson(tagSets, PHONGO_BSON_NONE, (bson_t*) tags, NULL);
if (!php_phongo_read_preference_tags_are_valid(tags)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"tags\" array field to have zero or more documents", ZSTR_VAL(php_phongo_readpreference_ce->name));
bson_destroy(tags);
goto failure;
}
if (!bson_empty(tags) && (mongoc_read_prefs_get_mode(intern->read_preference) == MONGOC_READ_PRIMARY)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"tags\" array field to not be present with \"primary\" mode", ZSTR_VAL(php_phongo_readpreference_ce->name));
bson_destroy(tags);
goto failure;
}
mongoc_read_prefs_set_tags(intern->read_preference, tags);
bson_destroy(tags);
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"tags\" field to be array", ZSTR_VAL(php_phongo_readpreference_ce->name));
goto failure;
}
}
if ((maxStalenessSeconds = zend_hash_str_find(props, "maxStalenessSeconds", sizeof("maxStalenessSeconds") - 1))) {
if (Z_TYPE_P(maxStalenessSeconds) == IS_LONG) {
if (Z_LVAL_P(maxStalenessSeconds) != MONGOC_NO_MAX_STALENESS) {
if (mongoc_read_prefs_get_mode(intern->read_preference) == MONGOC_READ_PRIMARY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"maxStalenessSeconds\" field to not be present with \"primary\" mode", ZSTR_VAL(php_phongo_readpreference_ce->name));
goto failure;
}
if (Z_LVAL_P(maxStalenessSeconds) < MONGOC_SMALLEST_MAX_STALENESS_SECONDS) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"maxStalenessSeconds\" integer field to be >= %d", ZSTR_VAL(php_phongo_readpreference_ce->name), MONGOC_SMALLEST_MAX_STALENESS_SECONDS);
goto failure;
}
if (Z_LVAL_P(maxStalenessSeconds) > INT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"maxStalenessSeconds\" integer field to be <= %" PRId32, ZSTR_VAL(php_phongo_readpreference_ce->name), INT32_MAX);
goto failure;
}
}
mongoc_read_prefs_set_max_staleness_seconds(intern->read_preference, Z_LVAL_P(maxStalenessSeconds));
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"maxStalenessSeconds\" field to be integer", ZSTR_VAL(php_phongo_readpreference_ce->name));
goto failure;
}
}
if ((hedge = zend_hash_str_find(props, "hedge", sizeof("hedge") - 1))) {
if (Z_TYPE_P(hedge) == IS_ARRAY || Z_TYPE_P(hedge) == IS_OBJECT) {
bson_t* hedge_doc = bson_new();
if (mongoc_read_prefs_get_mode(intern->read_preference) == MONGOC_READ_PRIMARY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"hedge\" field to not be present with \"primary\" mode", ZSTR_VAL(php_phongo_readpreference_ce->name));
bson_destroy(hedge_doc);
goto failure;
}
php_phongo_zval_to_bson(hedge, PHONGO_BSON_NONE, hedge_doc, NULL);
if (EG(exception)) {
bson_destroy(hedge_doc);
goto failure;
}
mongoc_read_prefs_set_hedge(intern->read_preference, hedge_doc);
bson_destroy(hedge_doc);
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"hedge\" field to be an array or object", ZSTR_VAL(php_phongo_readpreference_ce->name));
goto failure;
}
}
if (!mongoc_read_prefs_is_valid(intern->read_preference)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Read preference is not valid");
goto failure;
}
return true;
failure:
mongoc_read_prefs_destroy(intern->read_preference);
intern->read_preference = NULL;
return false;
}
static const char* php_phongo_readpreference_get_mode_string(const mongoc_read_prefs_t* read_prefs)
{
switch (mongoc_read_prefs_get_mode(read_prefs)) {
case MONGOC_READ_PRIMARY:
return PHONGO_READ_PRIMARY;
case MONGOC_READ_PRIMARY_PREFERRED:
return PHONGO_READ_PRIMARY_PREFERRED;
case MONGOC_READ_SECONDARY:
return PHONGO_READ_SECONDARY;
case MONGOC_READ_SECONDARY_PREFERRED:
return PHONGO_READ_SECONDARY_PREFERRED;
case MONGOC_READ_NEAREST:
return PHONGO_READ_NEAREST;
default:
return "";
}
}
/* Constructs a new ReadPreference */
static PHP_METHOD(MongoDB_Driver_ReadPreference, __construct)
{
php_phongo_readpreference_t* intern;
zend_string* mode;
zval* tagSets = NULL;
zval* options = NULL;
intern = Z_READPREFERENCE_OBJ_P(getThis());
/* Separate the tagSets zval, since we may end up modifying it in
* php_phongo_read_preference_prep_tagsets() below. */
PHONGO_PARSE_PARAMETERS_START(1, 3)
Z_PARAM_STR(mode)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_EX(tagSets, 1, 1)
Z_PARAM_ARRAY_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
if (zend_string_equals_literal_ci(mode, PHONGO_READ_PRIMARY)) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_PRIMARY);
} else if (zend_string_equals_literal_ci(mode, PHONGO_READ_PRIMARY_PREFERRED)) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_PRIMARY_PREFERRED);
} else if (zend_string_equals_literal_ci(mode, PHONGO_READ_SECONDARY)) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_SECONDARY);
} else if (zend_string_equals_literal_ci(mode, PHONGO_READ_SECONDARY_PREFERRED)) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_SECONDARY_PREFERRED);
} else if (zend_string_equals_literal_ci(mode, PHONGO_READ_NEAREST)) {
intern->read_preference = mongoc_read_prefs_new(MONGOC_READ_NEAREST);
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Invalid mode: '%s'", ZSTR_VAL(mode));
return;
}
if (tagSets) {
bson_t* tags = bson_new();
php_phongo_read_preference_prep_tagsets(tagSets);
php_phongo_zval_to_bson(tagSets, PHONGO_BSON_NONE, (bson_t*) tags, NULL);
if (!php_phongo_read_preference_tags_are_valid(tags)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "tagSets must be an array of zero or more documents");
bson_destroy(tags);
return;
}
if (!bson_empty(tags) && (mongoc_read_prefs_get_mode(intern->read_preference) == MONGOC_READ_PRIMARY)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "tagSets may not be used with primary mode");
bson_destroy(tags);
return;
}
mongoc_read_prefs_set_tags(intern->read_preference, tags);
bson_destroy(tags);
}
if (options && php_array_exists(options, "maxStalenessSeconds")) {
zend_long maxStalenessSeconds = php_array_fetchc_long(options, "maxStalenessSeconds");
if (maxStalenessSeconds != MONGOC_NO_MAX_STALENESS) {
if (maxStalenessSeconds < MONGOC_SMALLEST_MAX_STALENESS_SECONDS) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected maxStalenessSeconds to be >= %d, %" PHONGO_LONG_FORMAT " given", MONGOC_SMALLEST_MAX_STALENESS_SECONDS, maxStalenessSeconds);
return;
}
if (maxStalenessSeconds > INT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected maxStalenessSeconds to be <= %" PRId32 ", %" PHONGO_LONG_FORMAT " given", INT32_MAX, maxStalenessSeconds);
return;
}
if (mongoc_read_prefs_get_mode(intern->read_preference) == MONGOC_READ_PRIMARY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "maxStalenessSeconds may not be used with primary mode");
return;
}
}
mongoc_read_prefs_set_max_staleness_seconds(intern->read_preference, maxStalenessSeconds);
}
if (options && php_array_exists(options, "hedge")) {
zval* hedge = php_array_fetchc_deref(options, "hedge");
if (Z_TYPE_P(hedge) == IS_ARRAY || Z_TYPE_P(hedge) == IS_OBJECT) {
bson_t* hedge_doc = bson_new();
if (mongoc_read_prefs_get_mode(intern->read_preference) == MONGOC_READ_PRIMARY) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "hedge may not be used with primary mode");
bson_destroy(hedge_doc);
return;
}
php_phongo_zval_to_bson(hedge, PHONGO_BSON_NONE, hedge_doc, NULL);
if (EG(exception)) {
bson_destroy(hedge_doc);
return;
}
mongoc_read_prefs_set_hedge(intern->read_preference, hedge_doc);
bson_destroy(hedge_doc);
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"hedge\" field to be an array or object", ZSTR_VAL(php_phongo_readpreference_ce->name));
return;
}
}
if (!mongoc_read_prefs_is_valid(intern->read_preference)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Read preference is not valid");
return;
}
}
static PHP_METHOD(MongoDB_Driver_ReadPreference, __set_state)
{
php_phongo_readpreference_t* intern;
HashTable* props;
zval* array;
/* Separate the zval, since we may end up modifying the "tags" element in
* php_phongo_read_preference_prep_tagsets(), which is called from
* php_phongo_readpreference_init_from_hash. */
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY_EX(array, 0, 1)
PHONGO_PARSE_PARAMETERS_END();
object_init_ex(return_value, php_phongo_readpreference_ce);
intern = Z_READPREFERENCE_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_readpreference_init_from_hash(intern, props);
}
/* Returns the ReadPreference hedge document */
static PHP_METHOD(MongoDB_Driver_ReadPreference, getHedge)
{
php_phongo_readpreference_t* intern;
const bson_t* hedge;
intern = Z_READPREFERENCE_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
hedge = mongoc_read_prefs_get_hedge(intern->read_preference);
if (!bson_empty0(hedge)) {
php_phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
if (!php_phongo_bson_to_zval_ex(hedge, &state)) {
zval_ptr_dtor(&state.zchild);
return;
}
RETURN_ZVAL(&state.zchild, 0, 1);
} else {
RETURN_NULL();
}
}
/* Returns the ReadPreference maxStalenessSeconds value */
static PHP_METHOD(MongoDB_Driver_ReadPreference, getMaxStalenessSeconds)
{
php_phongo_readpreference_t* intern;
intern = Z_READPREFERENCE_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_LONG(mongoc_read_prefs_get_max_staleness_seconds(intern->read_preference));
}
/* Returns the ReadPreference mode as string */
static PHP_METHOD(MongoDB_Driver_ReadPreference, getModeString)
{
php_phongo_readpreference_t* intern;
intern = Z_READPREFERENCE_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_STRING(php_phongo_readpreference_get_mode_string(intern->read_preference));
}
/* Returns the ReadPreference tag sets */
static PHP_METHOD(MongoDB_Driver_ReadPreference, getTagSets)
{
php_phongo_readpreference_t* intern;
const bson_t* tags;
intern = Z_READPREFERENCE_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
tags = mongoc_read_prefs_get_tags(intern->read_preference);
if (tags->len) {
php_phongo_bson_state state;
PHONGO_BSON_INIT_DEBUG_STATE(state);
if (!php_phongo_bson_to_zval_ex(tags, &state)) {
zval_ptr_dtor(&state.zchild);
return;
}
RETURN_ZVAL(&state.zchild, 0, 1);
} else {
RETURN_NULL();
}
}
static HashTable* php_phongo_readpreference_get_properties_hash(zend_object* object, bool is_temp)
{
php_phongo_readpreference_t* intern;
HashTable* props;
const bson_t* tags;
const bson_t* hedge;
intern = Z_OBJ_READPREFERENCE(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_temp, intern, props, 4);
if (!intern->read_preference) {
return props;
}
tags = mongoc_read_prefs_get_tags(intern->read_preference);
hedge = mongoc_read_prefs_get_hedge(intern->read_preference);
{
zval z_mode;
ZVAL_STRING(&z_mode, php_phongo_readpreference_get_mode_string(intern->read_preference));
zend_hash_str_update(props, "mode", sizeof("mode") - 1, &z_mode);
}
if (!bson_empty0(tags)) {
php_phongo_bson_state state;
/* Use PHONGO_TYPEMAP_NATIVE_ARRAY for the root type since tags is an
* array; however, inner documents and arrays can use the default. */
PHONGO_BSON_INIT_STATE(state);
state.map.root.type = PHONGO_TYPEMAP_NATIVE_ARRAY;
if (!php_phongo_bson_to_zval_ex(tags, &state)) {
zval_ptr_dtor(&state.zchild);
goto done;
}
zend_hash_str_update(props, "tags", sizeof("tags") - 1, &state.zchild);
}
if (mongoc_read_prefs_get_max_staleness_seconds(intern->read_preference) != MONGOC_NO_MAX_STALENESS) {
/* Note: valid values for maxStalesnessSeconds will not exceed the range
* of 32-bit signed integers, so conditional encoding is not necessary. */
long maxStalenessSeconds = mongoc_read_prefs_get_max_staleness_seconds(intern->read_preference);
zval z_max_ss;
ZVAL_LONG(&z_max_ss, maxStalenessSeconds);
zend_hash_str_update(props, "maxStalenessSeconds", sizeof("maxStalenessSeconds") - 1, &z_max_ss);
}
if (!bson_empty0(hedge)) {
php_phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
if (!php_phongo_bson_to_zval_ex(hedge, &state)) {
zval_ptr_dtor(&state.zchild);
goto done;
}
zend_hash_str_update(props, "hedge", sizeof("hedge") - 1, &state.zchild);
}
done:
return props;
}
static PHP_METHOD(MongoDB_Driver_ReadPreference, bsonSerialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
ZVAL_ARR(return_value, php_phongo_readpreference_get_properties_hash(Z_OBJ_P(getThis()), true));
convert_to_object(return_value);
}
static PHP_METHOD(MongoDB_Driver_ReadPreference, __serialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_ARR(php_phongo_readpreference_get_properties_hash(Z_OBJ_P(getThis()), true));
}
static PHP_METHOD(MongoDB_Driver_ReadPreference, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_readpreference_init_from_hash(Z_READPREFERENCE_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\Driver\ReadPreference object handlers */
static zend_object_handlers php_phongo_handler_readpreference;
static void php_phongo_readpreference_free_object(zend_object* object)
{
php_phongo_readpreference_t* intern = Z_OBJ_READPREFERENCE(object);
zend_object_std_dtor(&intern->std);
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
if (intern->read_preference) {
mongoc_read_prefs_destroy(intern->read_preference);
}
}
static zend_object* php_phongo_readpreference_create_object(zend_class_entry* class_type)
{
php_phongo_readpreference_t* intern = zend_object_alloc(sizeof(php_phongo_readpreference_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_readpreference;
return &intern->std;
}
static HashTable* php_phongo_readpreference_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return php_phongo_readpreference_get_properties_hash(object, true);
}
static HashTable* php_phongo_readpreference_get_properties(zend_object* object)
{
return php_phongo_readpreference_get_properties_hash(object, false);
}
void php_phongo_readpreference_init_ce(INIT_FUNC_ARGS)
{
php_phongo_readpreference_ce = register_class_MongoDB_Driver_ReadPreference(php_phongo_serializable_ce);
php_phongo_readpreference_ce->create_object = php_phongo_readpreference_create_object;
memcpy(&php_phongo_handler_readpreference, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_readpreference.get_debug_info = php_phongo_readpreference_get_debug_info;
php_phongo_handler_readpreference.get_properties = php_phongo_readpreference_get_properties;
php_phongo_handler_readpreference.free_obj = php_phongo_readpreference_free_object;
php_phongo_handler_readpreference.offset = XtOffsetOf(php_phongo_readpreference_t, std);
}
void phongo_readpreference_init(zval* return_value, const mongoc_read_prefs_t* read_prefs)
{
php_phongo_readpreference_t* intern;
object_init_ex(return_value, php_phongo_readpreference_ce);
intern = Z_READPREFERENCE_OBJ_P(return_value);
intern->read_preference = mongoc_read_prefs_copy(read_prefs);
}
const mongoc_read_prefs_t* phongo_read_preference_from_zval(zval* zread_preference)
{
if (zread_preference) {
php_phongo_readpreference_t* intern = Z_READPREFERENCE_OBJ_P(zread_preference);
if (intern) {
return intern->read_preference;
}
}
return NULL;
}
/* Prepare tagSets for BSON encoding by converting each array in the set to an
* object. This ensures that empty arrays will serialize as empty documents.
*
* php_phongo_read_preference_tags_are_valid() handles actual validation of the
* tag set structure. */
void php_phongo_read_preference_prep_tagsets(zval* tagSets)
{
HashTable* ht_data;
zval* tagSet;
if (Z_TYPE_P(tagSets) != IS_ARRAY) {
return;
}
ht_data = HASH_OF(tagSets);
ZEND_HASH_FOREACH_VAL_IND(ht_data, tagSet)
{
ZVAL_DEREF(tagSet);
if (Z_TYPE_P(tagSet) == IS_ARRAY) {
SEPARATE_ZVAL_NOREF(tagSet);
convert_to_object(tagSet);
}
}
ZEND_HASH_FOREACH_END();
}
/* Checks if tags is valid to set on a mongoc_read_prefs_t. It may be null or an
* array of one or more documents. */
bool php_phongo_read_preference_tags_are_valid(const bson_t* tags)
{
bson_iter_t iter;
if (bson_empty0(tags)) {
return true;
}
if (!bson_iter_init(&iter, tags)) {
return false;
}
while (bson_iter_next(&iter)) {
if (!BSON_ITER_HOLDS_DOCUMENT(&iter)) {
return false;
}
}
return true;
}
mongodb-2.1.0/src/MongoDB/ReadPreference.h 0000644 0001751 0000166 00000002451 15014033047 015156 0 ustar /*
* Copyright 2022-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_READPREFERENCE_H
#define PHONGO_READPREFERENCE_H
#include "bson/bson.h"
#include "mongoc/mongoc.h"
#include
#define PHONGO_READ_PRIMARY "primary"
#define PHONGO_READ_PRIMARY_PREFERRED "primaryPreferred"
#define PHONGO_READ_SECONDARY "secondary"
#define PHONGO_READ_SECONDARY_PREFERRED "secondaryPreferred"
#define PHONGO_READ_NEAREST "nearest"
void phongo_readpreference_init(zval* return_value, const mongoc_read_prefs_t* read_prefs);
const mongoc_read_prefs_t* phongo_read_preference_from_zval(zval* zread_preference);
void php_phongo_read_preference_prep_tagsets(zval* tagSets);
bool php_phongo_read_preference_tags_are_valid(const bson_t* tags);
#endif /* PHONGO_READPREFERENCE_H */
mongodb-2.1.0/src/MongoDB/ReadPreference_arginfo.h 0000644 0001751 0000166 00000016650 15014033047 016671 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 27261ceb122b2783b1fba08be5c17b4f48ab8523 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_ReadPreference___construct, 0, 0, 1)
ZEND_ARG_TYPE_INFO(0, mode, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, tagSets, IS_ARRAY, 1, "null")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_ReadPreference_getHedge, 0, 0, IS_OBJECT, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_ReadPreference_getMaxStalenessSeconds, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_ReadPreference_getModeString, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_ReadPreference_getTagSets, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_ReadPreference___set_state, 0, 1, MongoDB\\Driver\\ReadPreference, 0)
ZEND_ARG_TYPE_INFO(0, properties, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_ReadPreference_bsonSerialize, 0, 0, stdClass, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_ReadPreference___unserialize, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_ReadPreference___serialize arginfo_class_MongoDB_Driver_ReadPreference_getTagSets
static ZEND_METHOD(MongoDB_Driver_ReadPreference, __construct);
static ZEND_METHOD(MongoDB_Driver_ReadPreference, getHedge);
static ZEND_METHOD(MongoDB_Driver_ReadPreference, getMaxStalenessSeconds);
static ZEND_METHOD(MongoDB_Driver_ReadPreference, getModeString);
static ZEND_METHOD(MongoDB_Driver_ReadPreference, getTagSets);
static ZEND_METHOD(MongoDB_Driver_ReadPreference, __set_state);
static ZEND_METHOD(MongoDB_Driver_ReadPreference, bsonSerialize);
static ZEND_METHOD(MongoDB_Driver_ReadPreference, __unserialize);
static ZEND_METHOD(MongoDB_Driver_ReadPreference, __serialize);
static const zend_function_entry class_MongoDB_Driver_ReadPreference_methods[] = {
ZEND_ME(MongoDB_Driver_ReadPreference, __construct, arginfo_class_MongoDB_Driver_ReadPreference___construct, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ReadPreference, getHedge, arginfo_class_MongoDB_Driver_ReadPreference_getHedge, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ReadPreference, getMaxStalenessSeconds, arginfo_class_MongoDB_Driver_ReadPreference_getMaxStalenessSeconds, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ReadPreference, getModeString, arginfo_class_MongoDB_Driver_ReadPreference_getModeString, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ReadPreference, getTagSets, arginfo_class_MongoDB_Driver_ReadPreference_getTagSets, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ReadPreference, __set_state, arginfo_class_MongoDB_Driver_ReadPreference___set_state, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ReadPreference, bsonSerialize, arginfo_class_MongoDB_Driver_ReadPreference_bsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ReadPreference, __unserialize, arginfo_class_MongoDB_Driver_ReadPreference___unserialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ReadPreference, __serialize, arginfo_class_MongoDB_Driver_ReadPreference___serialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_ReadPreference(zend_class_entry *class_entry_MongoDB_BSON_Serializable)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "ReadPreference", class_MongoDB_Driver_ReadPreference_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
zend_class_implements(class_entry, 1, class_entry_MongoDB_BSON_Serializable);
zval const_PRIMARY_value;
zend_string *const_PRIMARY_value_str = zend_string_init(PHONGO_READ_PRIMARY, strlen(PHONGO_READ_PRIMARY), 1);
ZVAL_STR(&const_PRIMARY_value, const_PRIMARY_value_str);
zend_string *const_PRIMARY_name = zend_string_init_interned("PRIMARY", sizeof("PRIMARY") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_PRIMARY_name, &const_PRIMARY_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_PRIMARY_name);
zval const_PRIMARY_PREFERRED_value;
zend_string *const_PRIMARY_PREFERRED_value_str = zend_string_init(PHONGO_READ_PRIMARY_PREFERRED, strlen(PHONGO_READ_PRIMARY_PREFERRED), 1);
ZVAL_STR(&const_PRIMARY_PREFERRED_value, const_PRIMARY_PREFERRED_value_str);
zend_string *const_PRIMARY_PREFERRED_name = zend_string_init_interned("PRIMARY_PREFERRED", sizeof("PRIMARY_PREFERRED") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_PRIMARY_PREFERRED_name, &const_PRIMARY_PREFERRED_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_PRIMARY_PREFERRED_name);
zval const_SECONDARY_value;
zend_string *const_SECONDARY_value_str = zend_string_init(PHONGO_READ_SECONDARY, strlen(PHONGO_READ_SECONDARY), 1);
ZVAL_STR(&const_SECONDARY_value, const_SECONDARY_value_str);
zend_string *const_SECONDARY_name = zend_string_init_interned("SECONDARY", sizeof("SECONDARY") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_SECONDARY_name, &const_SECONDARY_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_SECONDARY_name);
zval const_SECONDARY_PREFERRED_value;
zend_string *const_SECONDARY_PREFERRED_value_str = zend_string_init(PHONGO_READ_SECONDARY_PREFERRED, strlen(PHONGO_READ_SECONDARY_PREFERRED), 1);
ZVAL_STR(&const_SECONDARY_PREFERRED_value, const_SECONDARY_PREFERRED_value_str);
zend_string *const_SECONDARY_PREFERRED_name = zend_string_init_interned("SECONDARY_PREFERRED", sizeof("SECONDARY_PREFERRED") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_SECONDARY_PREFERRED_name, &const_SECONDARY_PREFERRED_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_SECONDARY_PREFERRED_name);
zval const_NEAREST_value;
zend_string *const_NEAREST_value_str = zend_string_init(PHONGO_READ_NEAREST, strlen(PHONGO_READ_NEAREST), 1);
ZVAL_STR(&const_NEAREST_value, const_NEAREST_value_str);
zend_string *const_NEAREST_name = zend_string_init_interned("NEAREST", sizeof("NEAREST") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_NEAREST_name, &const_NEAREST_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_NEAREST_name);
zval const_NO_MAX_STALENESS_value;
ZVAL_LONG(&const_NO_MAX_STALENESS_value, MONGOC_NO_MAX_STALENESS);
zend_string *const_NO_MAX_STALENESS_name = zend_string_init_interned("NO_MAX_STALENESS", sizeof("NO_MAX_STALENESS") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_NO_MAX_STALENESS_name, &const_NO_MAX_STALENESS_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_NO_MAX_STALENESS_name);
zval const_SMALLEST_MAX_STALENESS_SECONDS_value;
ZVAL_LONG(&const_SMALLEST_MAX_STALENESS_SECONDS_value, MONGOC_SMALLEST_MAX_STALENESS_SECONDS);
zend_string *const_SMALLEST_MAX_STALENESS_SECONDS_name = zend_string_init_interned("SMALLEST_MAX_STALENESS_SECONDS", sizeof("SMALLEST_MAX_STALENESS_SECONDS") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_SMALLEST_MAX_STALENESS_SECONDS_name, &const_SMALLEST_MAX_STALENESS_SECONDS_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_SMALLEST_MAX_STALENESS_SECONDS_name);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Server.c 0000644 0001751 0000166 00000055521 15014033047 013553 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bson/bson.h"
#include "mongoc/mongoc.h"
#include
#include
#include "php_phongo.h"
#include "phongo_bson_encode.h"
#include "phongo_client.h"
#include "phongo_error.h"
#include "phongo_execute.h"
#include "phongo_util.h"
#include "MongoDB/Server.h"
#include "MongoDB/ServerDescription.h"
#include "Server_arginfo.h"
zend_class_entry* php_phongo_server_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Server)
/* Executes a Command on this Server */
static PHP_METHOD(MongoDB_Driver_Server, executeCommand)
{
php_phongo_server_t* intern;
char* db;
size_t db_len;
zval* command;
zval* options = NULL;
intern = Z_SERVER_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STRING(db, db_len)
Z_PARAM_OBJECT_OF_CLASS(command, php_phongo_command_ce)
Z_PARAM_OPTIONAL
Z_PARAM_ZVAL_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
/* If the Server was created in a different process, reset the client so
* that cursors created by this process can be differentiated and its
* session pool is cleared. */
PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern, Z_MANAGER_OBJ_P(&intern->manager));
phongo_execute_command(&intern->manager, PHONGO_COMMAND_RAW, db, command, options, intern->server_id, return_value);
}
/* Executes a ReadCommand on this Server */
static PHP_METHOD(MongoDB_Driver_Server, executeReadCommand)
{
php_phongo_server_t* intern;
char* db;
size_t db_len;
zval* command;
zval* options = NULL;
intern = Z_SERVER_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STRING(db, db_len)
Z_PARAM_OBJECT_OF_CLASS(command, php_phongo_command_ce)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
/* If the Server was created in a different process, reset the client so
* that cursors created by this process can be differentiated and its
* session pool is cleared. */
PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern, Z_MANAGER_OBJ_P(&intern->manager));
phongo_execute_command(&intern->manager, PHONGO_COMMAND_READ, db, command, options, intern->server_id, return_value);
}
/* Executes a WriteCommand on this Server */
static PHP_METHOD(MongoDB_Driver_Server, executeWriteCommand)
{
php_phongo_server_t* intern;
char* db;
size_t db_len;
zval* command;
zval* options = NULL;
intern = Z_SERVER_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STRING(db, db_len)
Z_PARAM_OBJECT_OF_CLASS(command, php_phongo_command_ce)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
/* If the Server was created in a different process, reset the client so
* that cursors created by this process can be differentiated. and its
* session pool is cleared. */
PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern, Z_MANAGER_OBJ_P(&intern->manager));
phongo_execute_command(&intern->manager, PHONGO_COMMAND_WRITE, db, command, options, intern->server_id, return_value);
}
/* Executes a ReadWriteCommand on this Server */
static PHP_METHOD(MongoDB_Driver_Server, executeReadWriteCommand)
{
php_phongo_server_t* intern;
char* db;
size_t db_len;
zval* command;
zval* options = NULL;
intern = Z_SERVER_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STRING(db, db_len)
Z_PARAM_OBJECT_OF_CLASS(command, php_phongo_command_ce)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
/* If the Server was created in a different process, reset the client so
* that cursors created by this process can be differentiated and its
* session pool is cleared. */
PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern, Z_MANAGER_OBJ_P(&intern->manager));
phongo_execute_command(&intern->manager, PHONGO_COMMAND_READ_WRITE, db, command, options, intern->server_id, return_value);
}
/* Executes a Query on this Server */
static PHP_METHOD(MongoDB_Driver_Server, executeQuery)
{
php_phongo_server_t* intern;
char* namespace;
size_t namespace_len;
zval* query;
zval* options = NULL;
intern = Z_SERVER_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STRING(namespace, namespace_len)
Z_PARAM_OBJECT_OF_CLASS(query, php_phongo_query_ce)
Z_PARAM_OPTIONAL
Z_PARAM_ZVAL_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
/* If the Server was created in a different process, reset the client so
* that cursors created by this process can be differentiated and its
* session pool is cleared. */
PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern, Z_MANAGER_OBJ_P(&intern->manager));
phongo_execute_query(&intern->manager, namespace, query, options, intern->server_id, return_value);
}
/* Executes a BulkWrite (i.e. any number of insert, update, and delete ops) on
this Server */
static PHP_METHOD(MongoDB_Driver_Server, executeBulkWrite)
{
php_phongo_server_t* intern;
char* namespace;
size_t namespace_len;
zval* zbulk;
php_phongo_bulkwrite_t* bulk;
zval* options = NULL;
intern = Z_SERVER_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STRING(namespace, namespace_len)
Z_PARAM_OBJECT_OF_CLASS(zbulk, php_phongo_bulkwrite_ce)
Z_PARAM_OPTIONAL
Z_PARAM_ZVAL_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
bulk = Z_BULKWRITE_OBJ_P(zbulk);
/* If the Server was created in a different process, reset the client so
* that its session pool is cleared. */
PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern, Z_MANAGER_OBJ_P(&intern->manager));
phongo_execute_bulk_write(&intern->manager, namespace, bulk, options, intern->server_id, return_value);
}
/* Executes a BulkWriteCommand (i.e. bulkWrite command for MongoDB 8.0+) */
static PHP_METHOD(MongoDB_Driver_Server, executeBulkWriteCommand)
{
php_phongo_server_t* intern;
zval* zbwc;
php_phongo_bulkwritecommand_t* bwc;
zval* zoptions = NULL;
PHONGO_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_OBJECT_OF_CLASS(zbwc, php_phongo_bulkwritecommand_ce)
Z_PARAM_OPTIONAL
Z_PARAM_ZVAL_OR_NULL(zoptions)
PHONGO_PARSE_PARAMETERS_END();
intern = Z_SERVER_OBJ_P(getThis());
bwc = Z_BULKWRITECOMMAND_OBJ_P(zbwc);
/* If the Server was created in a different process, reset the client so
* that its session pool is cleared. */
PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern, Z_MANAGER_OBJ_P(&intern->manager));
phongo_execute_bulkwritecommand(&intern->manager, bwc, zoptions, intern->server_id, return_value);
}
/* Returns the hostname for this Server */
static PHP_METHOD(MongoDB_Driver_Server, getHost)
{
php_phongo_server_t* intern;
mongoc_server_description_t* sd;
intern = Z_SERVER_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
if ((sd = mongoc_client_get_server_description(Z_MANAGER_OBJ_P(&intern->manager)->client, intern->server_id))) {
RETVAL_STRING(mongoc_server_description_host(sd)->host);
mongoc_server_description_destroy(sd);
return;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Failed to get server description");
}
/* Returns the currently configured tags for this Server */
static PHP_METHOD(MongoDB_Driver_Server, getTags)
{
php_phongo_server_t* intern;
mongoc_server_description_t* sd;
intern = Z_SERVER_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
if ((sd = mongoc_client_get_server_description(Z_MANAGER_OBJ_P(&intern->manager)->client, intern->server_id))) {
const bson_t* hello_response = mongoc_server_description_hello_response(sd);
bson_iter_t iter;
if (bson_iter_init_find(&iter, hello_response, "tags") && BSON_ITER_HOLDS_DOCUMENT(&iter)) {
const uint8_t* bytes;
uint32_t len;
php_phongo_bson_state state;
PHONGO_BSON_INIT_DEBUG_STATE(state);
bson_iter_document(&iter, &len, &bytes);
if (!php_phongo_bson_data_to_zval_ex(bytes, len, &state)) {
/* Exception should already have been thrown */
zval_ptr_dtor(&state.zchild);
mongoc_server_description_destroy(sd);
return;
}
mongoc_server_description_destroy(sd);
RETURN_ZVAL(&state.zchild, 0, 1);
}
array_init(return_value);
mongoc_server_description_destroy(sd);
return;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Failed to get server description");
}
/* Returns the last hello response for this Server or, in the case of a load
balancer, the initial handshake response. */
static PHP_METHOD(MongoDB_Driver_Server, getInfo)
{
php_phongo_server_t* intern;
mongoc_client_t* client;
mongoc_server_description_t* sd;
mongoc_server_description_t* handshake_sd = NULL;
const bson_t* hello_response;
php_phongo_bson_state state;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_SERVER_OBJ_P(getThis());
client = Z_MANAGER_OBJ_P(&intern->manager)->client;
if (!(sd = mongoc_client_get_server_description(client, intern->server_id))) {
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Failed to get server description");
return;
}
hello_response = mongoc_server_description_hello_response(sd);
/* If the server description is a load balancer, its hello_response will be
* empty. Instead, report the hello_response from the handshake description
* (i.e. backing server). */
if (!strcmp(mongoc_server_description_type(sd), php_phongo_server_description_type_map[PHONGO_SERVER_LOAD_BALANCER].name)) {
bson_error_t error = { 0 };
if (!(handshake_sd = mongoc_client_get_handshake_description(client, intern->server_id, NULL, &error))) {
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Failed to get handshake server description: %s", error.message);
goto cleanup;
}
hello_response = mongoc_server_description_hello_response(handshake_sd);
}
PHONGO_BSON_INIT_DEBUG_STATE(state);
if (!php_phongo_bson_to_zval_ex(hello_response, &state)) {
/* Exception should already have been thrown */
zval_ptr_dtor(&state.zchild);
goto cleanup;
}
RETVAL_ZVAL(&state.zchild, 0, 1);
cleanup:
if (handshake_sd) {
mongoc_server_description_destroy(handshake_sd);
}
mongoc_server_description_destroy(sd);
}
/* Returns the measured latency (i.e. round trip time in milliseconds) for
this Server, or null if unset. */
static PHP_METHOD(MongoDB_Driver_Server, getLatency)
{
php_phongo_server_t* intern;
mongoc_server_description_t* sd;
PHONGO_PARSE_PARAMETERS_NONE();
intern = Z_SERVER_OBJ_P(getThis());
if (!(sd = mongoc_client_get_server_description(Z_MANAGER_OBJ_P(&intern->manager)->client, intern->server_id))) {
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Failed to get server description");
return;
}
/* TODO: Use MONGOC_RTT_UNSET once it is added to libmongoc's public API (CDRIVER-4176) */
if (mongoc_server_description_round_trip_time(sd) == -1) {
RETVAL_NULL();
} else {
RETVAL_LONG(mongoc_server_description_round_trip_time(sd));
}
mongoc_server_description_destroy(sd);
}
/* Returns the port for this Server */
static PHP_METHOD(MongoDB_Driver_Server, getPort)
{
php_phongo_server_t* intern;
mongoc_server_description_t* sd;
intern = Z_SERVER_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
if ((sd = mongoc_client_get_server_description(Z_MANAGER_OBJ_P(&intern->manager)->client, intern->server_id))) {
RETVAL_LONG(mongoc_server_description_host(sd)->port);
mongoc_server_description_destroy(sd);
return;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Failed to get server description");
}
/* Returns the server description for this Server */
static PHP_METHOD(MongoDB_Driver_Server, getServerDescription)
{
mongoc_server_description_t* server_description;
php_phongo_server_t* intern = Z_SERVER_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
server_description = mongoc_client_get_server_description(Z_MANAGER_OBJ_P(&intern->manager)->client, intern->server_id);
/* Avoid making another copy in phongo_serverdescription_init */
phongo_serverdescription_init_ex(return_value, server_description, false);
}
/* Returns the node type of this Server */
static PHP_METHOD(MongoDB_Driver_Server, getType)
{
php_phongo_server_t* intern;
mongoc_server_description_t* sd;
intern = Z_SERVER_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
if ((sd = mongoc_client_get_server_description(Z_MANAGER_OBJ_P(&intern->manager)->client, intern->server_id))) {
RETVAL_LONG(php_phongo_server_description_type(sd));
mongoc_server_description_destroy(sd);
return;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Failed to get server description");
}
/* Returns whether this Server is a primary member of a replica set */
static PHP_METHOD(MongoDB_Driver_Server, isPrimary)
{
php_phongo_server_t* intern;
mongoc_server_description_t* sd;
intern = Z_SERVER_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
if ((sd = mongoc_client_get_server_description(Z_MANAGER_OBJ_P(&intern->manager)->client, intern->server_id))) {
RETVAL_BOOL(!strcmp(mongoc_server_description_type(sd), php_phongo_server_description_type_map[PHONGO_SERVER_RS_PRIMARY].name));
mongoc_server_description_destroy(sd);
return;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Failed to get server description");
}
/* Returns whether this Server is a secondary member of a replica set */
static PHP_METHOD(MongoDB_Driver_Server, isSecondary)
{
php_phongo_server_t* intern;
mongoc_server_description_t* sd;
intern = Z_SERVER_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
if ((sd = mongoc_client_get_server_description(Z_MANAGER_OBJ_P(&intern->manager)->client, intern->server_id))) {
RETVAL_BOOL(!strcmp(mongoc_server_description_type(sd), php_phongo_server_description_type_map[PHONGO_SERVER_RS_SECONDARY].name));
mongoc_server_description_destroy(sd);
return;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Failed to get server description");
}
/* Returns whether this Server is an arbiter member of a replica set */
static PHP_METHOD(MongoDB_Driver_Server, isArbiter)
{
php_phongo_server_t* intern;
mongoc_server_description_t* sd;
intern = Z_SERVER_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
if ((sd = mongoc_client_get_server_description(Z_MANAGER_OBJ_P(&intern->manager)->client, intern->server_id))) {
RETVAL_BOOL(!strcmp(mongoc_server_description_type(sd), php_phongo_server_description_type_map[PHONGO_SERVER_RS_ARBITER].name));
mongoc_server_description_destroy(sd);
return;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Failed to get server description");
}
/* Returns whether this Server is a hidden member of a replica set */
static PHP_METHOD(MongoDB_Driver_Server, isHidden)
{
php_phongo_server_t* intern;
mongoc_server_description_t* sd;
intern = Z_SERVER_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
if ((sd = mongoc_client_get_server_description(Z_MANAGER_OBJ_P(&intern->manager)->client, intern->server_id))) {
bson_iter_t iter;
RETVAL_BOOL(bson_iter_init_find_case(&iter, mongoc_server_description_hello_response(sd), "hidden") && bson_iter_as_bool(&iter));
mongoc_server_description_destroy(sd);
return;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Failed to get server description");
}
/* Returns whether this Server is a passive member of a replica set */
static PHP_METHOD(MongoDB_Driver_Server, isPassive)
{
php_phongo_server_t* intern;
mongoc_server_description_t* sd;
intern = Z_SERVER_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
if ((sd = mongoc_client_get_server_description(Z_MANAGER_OBJ_P(&intern->manager)->client, intern->server_id))) {
bson_iter_t iter;
RETVAL_BOOL(bson_iter_init_find_case(&iter, mongoc_server_description_hello_response(sd), "passive") && bson_iter_as_bool(&iter));
mongoc_server_description_destroy(sd);
return;
}
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Failed to get server description");
}
/* MongoDB\Driver\Server object handlers */
static zend_object_handlers php_phongo_handler_server;
static int php_phongo_server_compare_objects(zval* o1, zval* o2)
{
php_phongo_server_t* intern1;
php_phongo_server_t* intern2;
mongoc_server_description_t *sd1, *sd2;
int retval = 0;
ZEND_COMPARE_OBJECTS_FALLBACK(o1, o2);
intern1 = Z_SERVER_OBJ_P(o1);
intern2 = Z_SERVER_OBJ_P(o2);
sd1 = mongoc_client_get_server_description(Z_MANAGER_OBJ_P(&intern1->manager)->client, intern1->server_id);
sd2 = mongoc_client_get_server_description(Z_MANAGER_OBJ_P(&intern2->manager)->client, intern2->server_id);
if (sd1 && sd2) {
retval = strcasecmp(mongoc_server_description_host(sd1)->host_and_port, mongoc_server_description_host(sd2)->host_and_port);
} else {
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Failed to get server description(s)");
}
if (sd1) {
mongoc_server_description_destroy(sd1);
}
if (sd2) {
mongoc_server_description_destroy(sd2);
}
return retval;
}
static void php_phongo_server_free_object(zend_object* object)
{
php_phongo_server_t* intern = Z_OBJ_SERVER(object);
zend_object_std_dtor(&intern->std);
if (!Z_ISUNDEF(intern->manager)) {
zval_ptr_dtor(&intern->manager);
}
}
static zend_object* php_phongo_server_create_object(zend_class_entry* class_type)
{
php_phongo_server_t* intern = zend_object_alloc(sizeof(php_phongo_server_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
PHONGO_SET_CREATED_BY_PID(intern);
intern->std.handlers = &php_phongo_handler_server;
return &intern->std;
}
static HashTable* php_phongo_server_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_server_t* intern = NULL;
zval retval = ZVAL_STATIC_INIT;
mongoc_client_t* client;
mongoc_server_description_t* sd;
*is_temp = 1;
intern = Z_OBJ_SERVER(object);
client = Z_MANAGER_OBJ_P(&intern->manager)->client;
if (!(sd = mongoc_client_get_server_description(client, intern->server_id))) {
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Failed to get server description");
return NULL;
}
php_phongo_server_to_zval(&retval, client, sd);
mongoc_server_description_destroy(sd);
return Z_ARRVAL(retval);
}
void php_phongo_server_init_ce(INIT_FUNC_ARGS)
{
php_phongo_server_ce = register_class_MongoDB_Driver_Server();
php_phongo_server_ce->create_object = php_phongo_server_create_object;
memcpy(&php_phongo_handler_server, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_server.compare = php_phongo_server_compare_objects;
php_phongo_handler_server.get_debug_info = php_phongo_server_get_debug_info;
php_phongo_handler_server.free_obj = php_phongo_server_free_object;
php_phongo_handler_server.offset = XtOffsetOf(php_phongo_server_t, std);
}
void phongo_server_init(zval* return_value, zval* manager, uint32_t server_id)
{
php_phongo_server_t* server;
object_init_ex(return_value, php_phongo_server_ce);
server = Z_SERVER_OBJ_P(return_value);
server->server_id = server_id;
ZVAL_ZVAL(&server->manager, manager, 1, 0);
}
bool php_phongo_server_to_zval(zval* retval, mongoc_client_t* client, mongoc_server_description_t* sd)
{
mongoc_host_list_t* host = mongoc_server_description_host(sd);
const bson_t* hello_response = mongoc_server_description_hello_response(sd);
bson_iter_t iter;
array_init(retval);
ADD_ASSOC_STRING(retval, "host", host->host);
ADD_ASSOC_LONG_EX(retval, "port", host->port);
ADD_ASSOC_LONG_EX(retval, "type", php_phongo_server_description_type(sd));
ADD_ASSOC_BOOL_EX(retval, "is_primary", !strcmp(mongoc_server_description_type(sd), php_phongo_server_description_type_map[PHONGO_SERVER_RS_PRIMARY].name));
ADD_ASSOC_BOOL_EX(retval, "is_secondary", !strcmp(mongoc_server_description_type(sd), php_phongo_server_description_type_map[PHONGO_SERVER_RS_SECONDARY].name));
ADD_ASSOC_BOOL_EX(retval, "is_arbiter", !strcmp(mongoc_server_description_type(sd), php_phongo_server_description_type_map[PHONGO_SERVER_RS_ARBITER].name));
ADD_ASSOC_BOOL_EX(retval, "is_hidden", bson_iter_init_find_case(&iter, hello_response, "hidden") && bson_iter_as_bool(&iter));
ADD_ASSOC_BOOL_EX(retval, "is_passive", bson_iter_init_find_case(&iter, hello_response, "passive") && bson_iter_as_bool(&iter));
if (bson_iter_init_find(&iter, hello_response, "tags") && BSON_ITER_HOLDS_DOCUMENT(&iter)) {
const uint8_t* bytes;
uint32_t len;
php_phongo_bson_state state;
PHONGO_BSON_INIT_DEBUG_STATE(state);
bson_iter_document(&iter, &len, &bytes);
if (!php_phongo_bson_data_to_zval_ex(bytes, len, &state)) {
/* Exception already thrown */
zval_ptr_dtor(&state.zchild);
return false;
}
ADD_ASSOC_ZVAL_EX(retval, "tags", &state.zchild);
}
/* If the server description is a load balancer, its hello_response will be
* empty. Instead, report the hello_response from the handshake description
* (i.e. backing server). */
if (!strcmp(mongoc_server_description_type(sd), php_phongo_server_description_type_map[PHONGO_SERVER_LOAD_BALANCER].name)) {
const bson_t* handshake_response;
mongoc_server_description_t* handshake_sd;
bson_error_t error = { 0 };
php_phongo_bson_state state;
if (!(handshake_sd = mongoc_client_get_handshake_description(client, mongoc_server_description_id(sd), NULL, &error))) {
phongo_throw_exception(PHONGO_ERROR_RUNTIME, "Failed to get handshake server description: %s", error.message);
return false;
}
PHONGO_BSON_INIT_DEBUG_STATE(state);
handshake_response = mongoc_server_description_hello_response(handshake_sd);
if (!php_phongo_bson_to_zval_ex(handshake_response, &state)) {
/* Exception already thrown */
mongoc_server_description_destroy(handshake_sd);
zval_ptr_dtor(&state.zchild);
return false;
}
ADD_ASSOC_ZVAL_EX(retval, "last_hello_response", &state.zchild);
mongoc_server_description_destroy(handshake_sd);
} else {
php_phongo_bson_state state;
PHONGO_BSON_INIT_DEBUG_STATE(state);
if (!php_phongo_bson_to_zval_ex(hello_response, &state)) {
/* Exception already thrown */
zval_ptr_dtor(&state.zchild);
return false;
}
ADD_ASSOC_ZVAL_EX(retval, "last_hello_response", &state.zchild);
}
/* TODO: Use MONGOC_RTT_UNSET once it is added to libmongoc's public API (CDRIVER-4176) */
if (mongoc_server_description_round_trip_time(sd) == -1) {
ADD_ASSOC_NULL_EX(retval, "round_trip_time");
} else {
ADD_ASSOC_LONG_EX(retval, "round_trip_time", mongoc_server_description_round_trip_time(sd));
}
return true;
}
mongodb-2.1.0/src/MongoDB/Server.h 0000644 0001751 0000166 00000001622 15014033047 013551 0 ustar /*
* Copyright 2022-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_SERVER_H
#define PHONGO_SERVER_H
#include "mongoc/mongoc.h"
#include
void phongo_server_init(zval* return_value, zval* manager, uint32_t server_id);
bool php_phongo_server_to_zval(zval* retval, mongoc_client_t* client, mongoc_server_description_t* sd);
#endif /* PHONGO_SERVER_H */
mongodb-2.1.0/src/MongoDB/ServerApi.c 0000644 0001751 0000166 00000020526 15014033047 014202 0 ustar /*
* Copyright 2021-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mongoc/mongoc.h"
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "ServerApi_arginfo.h"
zend_class_entry* php_phongo_serverapi_ce;
static bool php_phongo_serverapi_create_libmongoc_object(mongoc_server_api_t** server_api, zend_string* version, bool strict_set, bool strict, bool deprecation_errors_set, bool deprecation_errors)
{
mongoc_server_api_version_t server_api_version;
if (!mongoc_server_api_version_from_string(ZSTR_VAL(version), &server_api_version)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Server API version \"%s\" is not supported in this driver version", ZSTR_VAL(version));
return false;
}
if (*server_api) {
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Server API object already initialized. Please file a bug report as this should not happen.");
return false;
}
*server_api = mongoc_server_api_new(server_api_version);
if (strict_set) {
mongoc_server_api_strict(*server_api, strict);
}
if (deprecation_errors_set) {
mongoc_server_api_deprecation_errors(*server_api, deprecation_errors);
}
return true;
}
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_serverapi_init_from_hash(php_phongo_serverapi_t* intern, HashTable* props)
{
zval* version;
zval* strict;
zval* deprecation_errors;
version = zend_hash_str_find(props, ZEND_STRL("version"));
if (!version || Z_TYPE_P(version) != IS_STRING) {
// Exception
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"version\" field to be string", ZSTR_VAL(php_phongo_serverapi_ce->name));
return false;
}
if ((strict = zend_hash_str_find(props, ZEND_STRL("strict"))) && !ZVAL_IS_NULL(strict)) {
if (Z_TYPE_P(strict) != IS_TRUE && Z_TYPE_P(strict) != IS_FALSE) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"strict\" field to be bool or null", ZSTR_VAL(php_phongo_serverapi_ce->name));
return false;
}
}
if ((deprecation_errors = zend_hash_str_find(props, ZEND_STRL("deprecationErrors"))) && !ZVAL_IS_NULL(deprecation_errors)) {
if (Z_TYPE_P(deprecation_errors) != IS_TRUE && Z_TYPE_P(deprecation_errors) != IS_FALSE) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"deprecationErrors\" field to be bool or null", ZSTR_VAL(php_phongo_serverapi_ce->name));
return false;
}
}
return php_phongo_serverapi_create_libmongoc_object(
&intern->server_api,
Z_STR_P(version),
strict && !ZVAL_IS_NULL(strict),
strict && zval_is_true(strict),
deprecation_errors && !ZVAL_IS_NULL(deprecation_errors),
deprecation_errors && zval_is_true(deprecation_errors));
}
/* Constructs a new ServerApi object */
static PHP_METHOD(MongoDB_Driver_ServerApi, __construct)
{
php_phongo_serverapi_t* intern;
zend_string* version;
zend_bool strict = 0;
zend_bool strict_null = 1;
zend_bool deprecation_errors = 0;
zend_bool deprecation_errors_null = 1;
intern = Z_SERVERAPI_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(1, 3)
Z_PARAM_STR(version)
Z_PARAM_OPTIONAL
Z_PARAM_BOOL_EX(strict, strict_null, 1, 0)
Z_PARAM_BOOL_EX(deprecation_errors, deprecation_errors_null, 1, 0)
PHONGO_PARSE_PARAMETERS_END();
// Will throw on failure
php_phongo_serverapi_create_libmongoc_object(
&intern->server_api,
version,
(bool) !strict_null,
(bool) strict,
(bool) !deprecation_errors_null,
(bool) deprecation_errors);
}
static PHP_METHOD(MongoDB_Driver_ServerApi, __set_state)
{
php_phongo_serverapi_t* intern;
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
object_init_ex(return_value, php_phongo_serverapi_ce);
intern = Z_SERVERAPI_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_serverapi_init_from_hash(intern, props);
}
static HashTable* php_phongo_serverapi_get_properties_hash(zend_object* object, bool is_temp, bool include_null)
{
php_phongo_serverapi_t* intern;
HashTable* props;
zval version, strict, deprecation_errors;
bool is_set;
intern = Z_OBJ_SERVERAPI(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_temp, intern, props, 1);
ZVAL_STRING(&version, mongoc_server_api_version_to_string(mongoc_server_api_get_version(intern->server_api)));
zend_hash_str_add(props, "version", sizeof("version") - 1, &version);
is_set = mongoc_optional_is_set(mongoc_server_api_get_strict(intern->server_api));
if (is_set) {
ZVAL_BOOL(&strict, mongoc_optional_value(mongoc_server_api_get_strict(intern->server_api)));
} else {
ZVAL_NULL(&strict);
}
if (include_null || is_set) {
zend_hash_str_add(props, "strict", sizeof("strict") - 1, &strict);
}
is_set = mongoc_optional_is_set(mongoc_server_api_get_deprecation_errors(intern->server_api));
if (is_set) {
ZVAL_BOOL(&deprecation_errors, mongoc_optional_value(mongoc_server_api_get_deprecation_errors(intern->server_api)));
} else {
ZVAL_NULL(&deprecation_errors);
}
if (include_null || is_set) {
zend_hash_str_add(props, "deprecationErrors", sizeof("deprecationErrors") - 1, &deprecation_errors);
}
return props;
}
static PHP_METHOD(MongoDB_Driver_ServerApi, bsonSerialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
ZVAL_ARR(return_value, php_phongo_serverapi_get_properties_hash(Z_OBJ_P(getThis()), true, false));
convert_to_object(return_value);
}
static PHP_METHOD(MongoDB_Driver_ServerApi, __serialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_ARR(php_phongo_serverapi_get_properties_hash(Z_OBJ_P(getThis()), true, true));
}
static PHP_METHOD(MongoDB_Driver_ServerApi, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_serverapi_init_from_hash(Z_SERVERAPI_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\Driver\ServerApi object handlers */
static zend_object_handlers php_phongo_handler_serverapi;
static void php_phongo_serverapi_free_object(zend_object* object)
{
php_phongo_serverapi_t* intern = Z_OBJ_SERVERAPI(object);
zend_object_std_dtor(&intern->std);
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
if (intern->server_api) {
mongoc_server_api_destroy(intern->server_api);
}
}
static zend_object* php_phongo_serverapi_create_object(zend_class_entry* class_type)
{
php_phongo_serverapi_t* intern = zend_object_alloc(sizeof(php_phongo_serverapi_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_serverapi;
return &intern->std;
}
static HashTable* php_phongo_serverapi_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return php_phongo_serverapi_get_properties_hash(object, true, true);
}
static HashTable* php_phongo_serverapi_get_properties(zend_object* object)
{
return php_phongo_serverapi_get_properties_hash(object, false, true);
}
void php_phongo_serverapi_init_ce(INIT_FUNC_ARGS)
{
php_phongo_serverapi_ce = register_class_MongoDB_Driver_ServerApi(php_phongo_serializable_ce);
php_phongo_serverapi_ce->create_object = php_phongo_serverapi_create_object;
memcpy(&php_phongo_handler_serverapi, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_serverapi.get_debug_info = php_phongo_serverapi_get_debug_info;
php_phongo_handler_serverapi.get_properties = php_phongo_serverapi_get_properties;
php_phongo_handler_serverapi.free_obj = php_phongo_serverapi_free_object;
php_phongo_handler_serverapi.offset = XtOffsetOf(php_phongo_serverapi_t, std);
}
mongodb-2.1.0/src/MongoDB/ServerApi_arginfo.h 0000644 0001751 0000166 00000005635 15014033047 015720 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 74dd9fd0766587d269341f3c74a43ab9959a03a4 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_ServerApi___construct, 0, 0, 1)
ZEND_ARG_TYPE_INFO(0, version, IS_STRING, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, strict, _IS_BOOL, 1, "null")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, deprecationErrors, _IS_BOOL, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_ServerApi___set_state, 0, 1, MongoDB\\Driver\\ServerApi, 0)
ZEND_ARG_TYPE_INFO(0, properties, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_ServerApi_bsonSerialize, 0, 0, stdClass, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_ServerApi___unserialize, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_ServerApi___serialize, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_ServerApi, __construct);
static ZEND_METHOD(MongoDB_Driver_ServerApi, __set_state);
static ZEND_METHOD(MongoDB_Driver_ServerApi, bsonSerialize);
static ZEND_METHOD(MongoDB_Driver_ServerApi, __unserialize);
static ZEND_METHOD(MongoDB_Driver_ServerApi, __serialize);
static const zend_function_entry class_MongoDB_Driver_ServerApi_methods[] = {
ZEND_ME(MongoDB_Driver_ServerApi, __construct, arginfo_class_MongoDB_Driver_ServerApi___construct, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ServerApi, __set_state, arginfo_class_MongoDB_Driver_ServerApi___set_state, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ServerApi, bsonSerialize, arginfo_class_MongoDB_Driver_ServerApi_bsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ServerApi, __unserialize, arginfo_class_MongoDB_Driver_ServerApi___unserialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ServerApi, __serialize, arginfo_class_MongoDB_Driver_ServerApi___serialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_ServerApi(zend_class_entry *class_entry_MongoDB_BSON_Serializable)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "ServerApi", class_MongoDB_Driver_ServerApi_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
zend_class_implements(class_entry, 1, class_entry_MongoDB_BSON_Serializable);
zval const_V1_value;
zend_string *const_V1_value_str = zend_string_init("1", strlen("1"), 1);
ZVAL_STR(&const_V1_value, const_V1_value_str);
zend_string *const_V1_name = zend_string_init_interned("V1", sizeof("V1") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_V1_name, &const_V1_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_V1_name);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/ServerDescription.c 0000644 0001751 0000166 00000023445 15014033047 015757 0 ustar /*
* Copyright 2021-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bson/bson.h"
#include "mongoc/mongoc.h"
#include
#include
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "MongoDB/ServerDescription.h"
#include "ServerDescription_arginfo.h"
zend_class_entry* php_phongo_serverdescription_ce;
php_phongo_server_description_type_map_t
php_phongo_server_description_type_map[PHONGO_SERVER_DESCRIPTION_TYPES] = {
{ PHONGO_SERVER_UNKNOWN, PHONGO_SERVER_TYPE_UNKNOWN },
{ PHONGO_SERVER_STANDALONE, PHONGO_SERVER_TYPE_STANDALONE },
{ PHONGO_SERVER_MONGOS, PHONGO_SERVER_TYPE_MONGOS },
{ PHONGO_SERVER_POSSIBLE_PRIMARY, PHONGO_SERVER_TYPE_POSSIBLE_PRIMARY },
{ PHONGO_SERVER_RS_PRIMARY, PHONGO_SERVER_TYPE_RS_PRIMARY },
{ PHONGO_SERVER_RS_SECONDARY, PHONGO_SERVER_TYPE_RS_SECONDARY },
{ PHONGO_SERVER_RS_ARBITER, PHONGO_SERVER_TYPE_RS_ARBITER },
{ PHONGO_SERVER_RS_OTHER, PHONGO_SERVER_TYPE_RS_OTHER },
{ PHONGO_SERVER_RS_GHOST, PHONGO_SERVER_TYPE_RS_GHOST },
{ PHONGO_SERVER_LOAD_BALANCER, PHONGO_SERVER_TYPE_LOAD_BALANCER },
};
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_ServerDescription)
/* Returns the most recent "hello" response */
static PHP_METHOD(MongoDB_Driver_ServerDescription, getHelloResponse)
{
php_phongo_serverdescription_t* intern;
const bson_t* helloResponse;
php_phongo_bson_state state;
intern = Z_SERVERDESCRIPTION_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
/* Note: the hello response will be empty for load balancers since they are
* not monitored. Unlike Server::getInfo(), we do not attempt to fetch the
* corresponding handshake description, as that would require holding a
* reference to the libmongoc client (and likely a Manager object) on the
* ServerDescription and TopologyDescription classes. */
helloResponse = mongoc_server_description_hello_response(intern->server_description);
PHONGO_BSON_INIT_DEBUG_STATE(state);
if (!php_phongo_bson_to_zval_ex(helloResponse, &state)) {
/* Exception should already have been thrown */
zval_ptr_dtor(&state.zchild);
return;
}
RETURN_ZVAL(&state.zchild, 0, 1);
}
/* Returns the server's hostname */
static PHP_METHOD(MongoDB_Driver_ServerDescription, getHost)
{
php_phongo_serverdescription_t* intern;
intern = Z_SERVERDESCRIPTION_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRING(mongoc_server_description_host(intern->server_description)->host);
}
/* Returns the server's last update time, in microseconds */
static PHP_METHOD(MongoDB_Driver_ServerDescription, getLastUpdateTime)
{
php_phongo_serverdescription_t* intern;
int64_t last_update_time;
intern = Z_SERVERDESCRIPTION_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
last_update_time = mongoc_server_description_last_update_time(intern->server_description);
#if SIZEOF_ZEND_LONG == 4
if (last_update_time > INT32_MAX || last_update_time < INT32_MIN) {
zend_error(E_WARNING, "Truncating 64-bit value for lastUpdateTime");
}
#endif
RETVAL_LONG(last_update_time);
}
/* Returns the server's port */
static PHP_METHOD(MongoDB_Driver_ServerDescription, getPort)
{
php_phongo_serverdescription_t* intern;
intern = Z_SERVERDESCRIPTION_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_LONG(mongoc_server_description_host(intern->server_description)->port);
}
/* Returns the server's round trip time, in milliseconds */
static PHP_METHOD(MongoDB_Driver_ServerDescription, getRoundTripTime)
{
php_phongo_serverdescription_t* intern;
intern = Z_SERVERDESCRIPTION_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
/* TODO: Use MONGOC_RTT_UNSET once it is added to libmongoc's public API (CDRIVER-4176) */
if (mongoc_server_description_round_trip_time(intern->server_description) == -1) {
RETVAL_NULL();
} else {
RETVAL_LONG(mongoc_server_description_round_trip_time(intern->server_description));
}
}
/* Returns the server's node type */
static PHP_METHOD(MongoDB_Driver_ServerDescription, getType)
{
php_phongo_serverdescription_t* intern;
intern = Z_SERVERDESCRIPTION_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRING(mongoc_server_description_type(intern->server_description));
}
/* MongoDB\Driver\ServerDescription object handlers */
static zend_object_handlers php_phongo_handler_serverdescription;
static void php_phongo_serverdescription_free_object(zend_object* object)
{
php_phongo_serverdescription_t* intern = Z_OBJ_SERVERDESCRIPTION(object);
zend_object_std_dtor(&intern->std);
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
if (intern->server_description) {
mongoc_server_description_destroy(intern->server_description);
}
}
static zend_object* php_phongo_serverdescription_create_object(zend_class_entry* class_type)
{
php_phongo_serverdescription_t* intern = zend_object_alloc(sizeof(php_phongo_serverdescription_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_serverdescription;
return &intern->std;
}
HashTable* php_phongo_serverdescription_get_properties_hash(zend_object* object, bool is_debug)
{
php_phongo_serverdescription_t* intern = NULL;
HashTable* props;
intern = Z_OBJ_SERVERDESCRIPTION(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_debug, intern, props, 6);
if (!intern->server_description) {
return props;
}
{
zval host, port, type;
mongoc_host_list_t* host_list = mongoc_server_description_host(intern->server_description);
ZVAL_STRING(&host, host_list->host);
zend_hash_str_update(props, "host", sizeof("host") - 1, &host);
ZVAL_LONG(&port, host_list->port);
zend_hash_str_update(props, "port", sizeof("port") - 1, &port);
ZVAL_STRING(&type, mongoc_server_description_type(intern->server_description));
zend_hash_str_update(props, "type", sizeof("type") - 1, &type);
}
{
const bson_t* hello_response = mongoc_server_description_hello_response(intern->server_description);
php_phongo_bson_state state;
PHONGO_BSON_INIT_DEBUG_STATE(state);
if (!php_phongo_bson_to_zval_ex(hello_response, &state)) {
zval_ptr_dtor(&state.zchild);
goto done;
}
zend_hash_str_update(props, "hello_response", sizeof("hello_response") - 1, &state.zchild);
}
{
int64_t last_update_time;
zval z_last_update_time;
last_update_time = mongoc_server_description_last_update_time(intern->server_description);
#if SIZEOF_ZEND_LONG == 4
if (last_update_time > INT32_MAX || last_update_time < INT32_MIN) {
ZVAL_INT64_STRING(&z_last_update_time, last_update_time);
} else {
ZVAL_LONG(&z_last_update_time, last_update_time);
}
#else
ZVAL_LONG(&z_last_update_time, last_update_time);
#endif
zend_hash_str_update(props, "last_update_time", sizeof("last_update_time") - 1, &z_last_update_time);
}
{
zval round_trip_time;
/* TODO: Use MONGOC_RTT_UNSET once it is added to libmongoc's public API (CDRIVER-4176) */
if (mongoc_server_description_round_trip_time(intern->server_description) == -1) {
ZVAL_NULL(&round_trip_time);
} else {
ZVAL_LONG(&round_trip_time, mongoc_server_description_round_trip_time(intern->server_description));
}
zend_hash_str_update(props, "round_trip_time", sizeof("round_trip_time") - 1, &round_trip_time);
}
done:
return props;
}
static HashTable* php_phongo_serverdescription_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return php_phongo_serverdescription_get_properties_hash(object, true);
}
static HashTable* php_phongo_serverdescription_get_properties(zend_object* object)
{
return php_phongo_serverdescription_get_properties_hash(object, false);
}
void php_phongo_serverdescription_init_ce(INIT_FUNC_ARGS)
{
php_phongo_serverdescription_ce = register_class_MongoDB_Driver_ServerDescription();
php_phongo_serverdescription_ce->create_object = php_phongo_serverdescription_create_object;
memcpy(&php_phongo_handler_serverdescription, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_serverdescription.get_debug_info = php_phongo_serverdescription_get_debug_info;
php_phongo_handler_serverdescription.get_properties = php_phongo_serverdescription_get_properties;
php_phongo_handler_serverdescription.free_obj = php_phongo_serverdescription_free_object;
php_phongo_handler_serverdescription.offset = XtOffsetOf(php_phongo_serverdescription_t, std);
}
void phongo_serverdescription_init_ex(zval* return_value, mongoc_server_description_t* server_description, bool copy)
{
php_phongo_serverdescription_t* intern;
object_init_ex(return_value, php_phongo_serverdescription_ce);
intern = Z_SERVERDESCRIPTION_OBJ_P(return_value);
intern->server_description = copy ? mongoc_server_description_new_copy(server_description) : server_description;
}
php_phongo_server_description_type_t php_phongo_server_description_type(mongoc_server_description_t* sd)
{
const char* name = mongoc_server_description_type(sd);
int i;
for (i = 0; i < PHONGO_SERVER_DESCRIPTION_TYPES; i++) {
if (!strcmp(name, php_phongo_server_description_type_map[i].name)) {
return php_phongo_server_description_type_map[i].type;
}
}
return PHONGO_SERVER_UNKNOWN;
}
mongodb-2.1.0/src/MongoDB/ServerDescription.h 0000644 0001751 0000166 00000005070 15014033047 015756 0 ustar /*
* Copyright 2022-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_SERVERDESCRIPTION_H
#define PHONGO_SERVERDESCRIPTION_H
#include "mongoc/mongoc.h"
#include
/* Note: these constants are derived from mongoc_server_description_type, since
* since mongoc_server_description_type_t is private. */
#define PHONGO_SERVER_TYPE_UNKNOWN "Unknown"
#define PHONGO_SERVER_TYPE_STANDALONE "Standalone"
#define PHONGO_SERVER_TYPE_MONGOS "Mongos"
#define PHONGO_SERVER_TYPE_POSSIBLE_PRIMARY "PossiblePrimary"
#define PHONGO_SERVER_TYPE_RS_PRIMARY "RSPrimary"
#define PHONGO_SERVER_TYPE_RS_SECONDARY "RSSecondary"
#define PHONGO_SERVER_TYPE_RS_ARBITER "RSArbiter"
#define PHONGO_SERVER_TYPE_RS_OTHER "RSOther"
#define PHONGO_SERVER_TYPE_RS_GHOST "RSGhost"
#define PHONGO_SERVER_TYPE_LOAD_BALANCER "LoadBalancer"
/* This enum is necessary since mongoc_server_description_type_t is private and
* we need to translate strings returned by mongoc_server_description_type() to
* Server integer constants. */
typedef enum {
PHONGO_SERVER_UNKNOWN = 0,
PHONGO_SERVER_STANDALONE = 1,
PHONGO_SERVER_MONGOS = 2,
PHONGO_SERVER_POSSIBLE_PRIMARY = 3,
PHONGO_SERVER_RS_PRIMARY = 4,
PHONGO_SERVER_RS_SECONDARY = 5,
PHONGO_SERVER_RS_ARBITER = 6,
PHONGO_SERVER_RS_OTHER = 7,
PHONGO_SERVER_RS_GHOST = 8,
PHONGO_SERVER_LOAD_BALANCER = 9,
PHONGO_SERVER_DESCRIPTION_TYPES = 10,
} php_phongo_server_description_type_t;
typedef struct {
php_phongo_server_description_type_t type;
const char* name;
} php_phongo_server_description_type_map_t;
extern php_phongo_server_description_type_map_t php_phongo_server_description_type_map[];
void phongo_serverdescription_init_ex(zval* return_value, mongoc_server_description_t* sd, bool copy);
#define phongo_serverdescription_init(r, sd) phongo_serverdescription_init_ex((r), (sd), true)
php_phongo_server_description_type_t php_phongo_server_description_type(mongoc_server_description_t* sd);
#endif /* PHONGO_SERVERDESCRIPTION_H */
mongodb-2.1.0/src/MongoDB/ServerDescription_arginfo.h 0000644 0001751 0000166 00000020546 15014033047 017470 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 482425509937fc9119cf140099b41af3c4a20fde */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_ServerDescription___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_ServerDescription_getHelloResponse, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_ServerDescription_getHost, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_ServerDescription_getLastUpdateTime, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_ServerDescription_getPort arginfo_class_MongoDB_Driver_ServerDescription_getLastUpdateTime
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_ServerDescription_getRoundTripTime, 0, 0, IS_LONG, 1)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_ServerDescription_getType arginfo_class_MongoDB_Driver_ServerDescription_getHost
static ZEND_METHOD(MongoDB_Driver_ServerDescription, __construct);
static ZEND_METHOD(MongoDB_Driver_ServerDescription, getHelloResponse);
static ZEND_METHOD(MongoDB_Driver_ServerDescription, getHost);
static ZEND_METHOD(MongoDB_Driver_ServerDescription, getLastUpdateTime);
static ZEND_METHOD(MongoDB_Driver_ServerDescription, getPort);
static ZEND_METHOD(MongoDB_Driver_ServerDescription, getRoundTripTime);
static ZEND_METHOD(MongoDB_Driver_ServerDescription, getType);
static const zend_function_entry class_MongoDB_Driver_ServerDescription_methods[] = {
ZEND_ME(MongoDB_Driver_ServerDescription, __construct, arginfo_class_MongoDB_Driver_ServerDescription___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ServerDescription, getHelloResponse, arginfo_class_MongoDB_Driver_ServerDescription_getHelloResponse, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ServerDescription, getHost, arginfo_class_MongoDB_Driver_ServerDescription_getHost, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ServerDescription, getLastUpdateTime, arginfo_class_MongoDB_Driver_ServerDescription_getLastUpdateTime, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ServerDescription, getPort, arginfo_class_MongoDB_Driver_ServerDescription_getPort, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ServerDescription, getRoundTripTime, arginfo_class_MongoDB_Driver_ServerDescription_getRoundTripTime, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_ServerDescription, getType, arginfo_class_MongoDB_Driver_ServerDescription_getType, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_ServerDescription(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "ServerDescription", class_MongoDB_Driver_ServerDescription_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
zval const_TYPE_UNKNOWN_value;
zend_string *const_TYPE_UNKNOWN_value_str = zend_string_init(PHONGO_SERVER_TYPE_UNKNOWN, strlen(PHONGO_SERVER_TYPE_UNKNOWN), 1);
ZVAL_STR(&const_TYPE_UNKNOWN_value, const_TYPE_UNKNOWN_value_str);
zend_string *const_TYPE_UNKNOWN_name = zend_string_init_interned("TYPE_UNKNOWN", sizeof("TYPE_UNKNOWN") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_UNKNOWN_name, &const_TYPE_UNKNOWN_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_UNKNOWN_name);
zval const_TYPE_STANDALONE_value;
zend_string *const_TYPE_STANDALONE_value_str = zend_string_init(PHONGO_SERVER_TYPE_STANDALONE, strlen(PHONGO_SERVER_TYPE_STANDALONE), 1);
ZVAL_STR(&const_TYPE_STANDALONE_value, const_TYPE_STANDALONE_value_str);
zend_string *const_TYPE_STANDALONE_name = zend_string_init_interned("TYPE_STANDALONE", sizeof("TYPE_STANDALONE") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_STANDALONE_name, &const_TYPE_STANDALONE_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_STANDALONE_name);
zval const_TYPE_MONGOS_value;
zend_string *const_TYPE_MONGOS_value_str = zend_string_init(PHONGO_SERVER_TYPE_MONGOS, strlen(PHONGO_SERVER_TYPE_MONGOS), 1);
ZVAL_STR(&const_TYPE_MONGOS_value, const_TYPE_MONGOS_value_str);
zend_string *const_TYPE_MONGOS_name = zend_string_init_interned("TYPE_MONGOS", sizeof("TYPE_MONGOS") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_MONGOS_name, &const_TYPE_MONGOS_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_MONGOS_name);
zval const_TYPE_POSSIBLE_PRIMARY_value;
zend_string *const_TYPE_POSSIBLE_PRIMARY_value_str = zend_string_init(PHONGO_SERVER_TYPE_POSSIBLE_PRIMARY, strlen(PHONGO_SERVER_TYPE_POSSIBLE_PRIMARY), 1);
ZVAL_STR(&const_TYPE_POSSIBLE_PRIMARY_value, const_TYPE_POSSIBLE_PRIMARY_value_str);
zend_string *const_TYPE_POSSIBLE_PRIMARY_name = zend_string_init_interned("TYPE_POSSIBLE_PRIMARY", sizeof("TYPE_POSSIBLE_PRIMARY") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_POSSIBLE_PRIMARY_name, &const_TYPE_POSSIBLE_PRIMARY_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_POSSIBLE_PRIMARY_name);
zval const_TYPE_RS_PRIMARY_value;
zend_string *const_TYPE_RS_PRIMARY_value_str = zend_string_init(PHONGO_SERVER_TYPE_RS_PRIMARY, strlen(PHONGO_SERVER_TYPE_RS_PRIMARY), 1);
ZVAL_STR(&const_TYPE_RS_PRIMARY_value, const_TYPE_RS_PRIMARY_value_str);
zend_string *const_TYPE_RS_PRIMARY_name = zend_string_init_interned("TYPE_RS_PRIMARY", sizeof("TYPE_RS_PRIMARY") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_RS_PRIMARY_name, &const_TYPE_RS_PRIMARY_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_RS_PRIMARY_name);
zval const_TYPE_RS_SECONDARY_value;
zend_string *const_TYPE_RS_SECONDARY_value_str = zend_string_init(PHONGO_SERVER_TYPE_RS_SECONDARY, strlen(PHONGO_SERVER_TYPE_RS_SECONDARY), 1);
ZVAL_STR(&const_TYPE_RS_SECONDARY_value, const_TYPE_RS_SECONDARY_value_str);
zend_string *const_TYPE_RS_SECONDARY_name = zend_string_init_interned("TYPE_RS_SECONDARY", sizeof("TYPE_RS_SECONDARY") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_RS_SECONDARY_name, &const_TYPE_RS_SECONDARY_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_RS_SECONDARY_name);
zval const_TYPE_RS_ARBITER_value;
zend_string *const_TYPE_RS_ARBITER_value_str = zend_string_init(PHONGO_SERVER_TYPE_RS_ARBITER, strlen(PHONGO_SERVER_TYPE_RS_ARBITER), 1);
ZVAL_STR(&const_TYPE_RS_ARBITER_value, const_TYPE_RS_ARBITER_value_str);
zend_string *const_TYPE_RS_ARBITER_name = zend_string_init_interned("TYPE_RS_ARBITER", sizeof("TYPE_RS_ARBITER") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_RS_ARBITER_name, &const_TYPE_RS_ARBITER_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_RS_ARBITER_name);
zval const_TYPE_RS_OTHER_value;
zend_string *const_TYPE_RS_OTHER_value_str = zend_string_init(PHONGO_SERVER_TYPE_RS_OTHER, strlen(PHONGO_SERVER_TYPE_RS_OTHER), 1);
ZVAL_STR(&const_TYPE_RS_OTHER_value, const_TYPE_RS_OTHER_value_str);
zend_string *const_TYPE_RS_OTHER_name = zend_string_init_interned("TYPE_RS_OTHER", sizeof("TYPE_RS_OTHER") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_RS_OTHER_name, &const_TYPE_RS_OTHER_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_RS_OTHER_name);
zval const_TYPE_RS_GHOST_value;
zend_string *const_TYPE_RS_GHOST_value_str = zend_string_init(PHONGO_SERVER_TYPE_RS_GHOST, strlen(PHONGO_SERVER_TYPE_RS_GHOST), 1);
ZVAL_STR(&const_TYPE_RS_GHOST_value, const_TYPE_RS_GHOST_value_str);
zend_string *const_TYPE_RS_GHOST_name = zend_string_init_interned("TYPE_RS_GHOST", sizeof("TYPE_RS_GHOST") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_RS_GHOST_name, &const_TYPE_RS_GHOST_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_RS_GHOST_name);
zval const_TYPE_LOAD_BALANCER_value;
zend_string *const_TYPE_LOAD_BALANCER_value_str = zend_string_init(PHONGO_SERVER_TYPE_LOAD_BALANCER, strlen(PHONGO_SERVER_TYPE_LOAD_BALANCER), 1);
ZVAL_STR(&const_TYPE_LOAD_BALANCER_value, const_TYPE_LOAD_BALANCER_value_str);
zend_string *const_TYPE_LOAD_BALANCER_name = zend_string_init_interned("TYPE_LOAD_BALANCER", sizeof("TYPE_LOAD_BALANCER") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_LOAD_BALANCER_name, &const_TYPE_LOAD_BALANCER_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_LOAD_BALANCER_name);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Server_arginfo.h 0000644 0001751 0000166 00000026337 15014033047 015270 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: ed6e371d10ddbcfd3ffed6aeb48758d0e88d717f */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_Server___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Server_executeBulkWrite, 0, 2, MongoDB\\Driver\\WriteResult, 0)
ZEND_ARG_TYPE_INFO(0, namespace, IS_STRING, 0)
ZEND_ARG_OBJ_INFO(0, bulkWrite, MongoDB\\Driver\\BulkWrite, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Server_executeBulkWriteCommand, 0, 1, MongoDB\\Driver\\BulkWriteCommandResult, 0)
ZEND_ARG_OBJ_INFO(0, bulkWriteCommand, MongoDB\\Driver\\BulkWriteCommand, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Server_executeCommand, 0, 2, MongoDB\\Driver\\CursorInterface, 0)
ZEND_ARG_TYPE_INFO(0, db, IS_STRING, 0)
ZEND_ARG_OBJ_INFO(0, command, MongoDB\\Driver\\Command, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Server_executeQuery, 0, 2, MongoDB\\Driver\\CursorInterface, 0)
ZEND_ARG_TYPE_INFO(0, namespace, IS_STRING, 0)
ZEND_ARG_OBJ_INFO(0, query, MongoDB\\Driver\\Query, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_Server_executeReadCommand arginfo_class_MongoDB_Driver_Server_executeCommand
#define arginfo_class_MongoDB_Driver_Server_executeReadWriteCommand arginfo_class_MongoDB_Driver_Server_executeCommand
#define arginfo_class_MongoDB_Driver_Server_executeWriteCommand arginfo_class_MongoDB_Driver_Server_executeCommand
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Server_getHost, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Server_getInfo, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Server_getLatency, 0, 0, IS_LONG, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Server_getPort, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Server_getServerDescription, 0, 0, MongoDB\\Driver\\ServerDescription, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_Server_getTags arginfo_class_MongoDB_Driver_Server_getInfo
#define arginfo_class_MongoDB_Driver_Server_getType arginfo_class_MongoDB_Driver_Server_getPort
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Server_isArbiter, 0, 0, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_Server_isHidden arginfo_class_MongoDB_Driver_Server_isArbiter
#define arginfo_class_MongoDB_Driver_Server_isPassive arginfo_class_MongoDB_Driver_Server_isArbiter
#define arginfo_class_MongoDB_Driver_Server_isPrimary arginfo_class_MongoDB_Driver_Server_isArbiter
#define arginfo_class_MongoDB_Driver_Server_isSecondary arginfo_class_MongoDB_Driver_Server_isArbiter
static ZEND_METHOD(MongoDB_Driver_Server, __construct);
static ZEND_METHOD(MongoDB_Driver_Server, executeBulkWrite);
static ZEND_METHOD(MongoDB_Driver_Server, executeBulkWriteCommand);
static ZEND_METHOD(MongoDB_Driver_Server, executeCommand);
static ZEND_METHOD(MongoDB_Driver_Server, executeQuery);
static ZEND_METHOD(MongoDB_Driver_Server, executeReadCommand);
static ZEND_METHOD(MongoDB_Driver_Server, executeReadWriteCommand);
static ZEND_METHOD(MongoDB_Driver_Server, executeWriteCommand);
static ZEND_METHOD(MongoDB_Driver_Server, getHost);
static ZEND_METHOD(MongoDB_Driver_Server, getInfo);
static ZEND_METHOD(MongoDB_Driver_Server, getLatency);
static ZEND_METHOD(MongoDB_Driver_Server, getPort);
static ZEND_METHOD(MongoDB_Driver_Server, getServerDescription);
static ZEND_METHOD(MongoDB_Driver_Server, getTags);
static ZEND_METHOD(MongoDB_Driver_Server, getType);
static ZEND_METHOD(MongoDB_Driver_Server, isArbiter);
static ZEND_METHOD(MongoDB_Driver_Server, isHidden);
static ZEND_METHOD(MongoDB_Driver_Server, isPassive);
static ZEND_METHOD(MongoDB_Driver_Server, isPrimary);
static ZEND_METHOD(MongoDB_Driver_Server, isSecondary);
static const zend_function_entry class_MongoDB_Driver_Server_methods[] = {
ZEND_ME(MongoDB_Driver_Server, __construct, arginfo_class_MongoDB_Driver_Server___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Server, executeBulkWrite, arginfo_class_MongoDB_Driver_Server_executeBulkWrite, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Server, executeBulkWriteCommand, arginfo_class_MongoDB_Driver_Server_executeBulkWriteCommand, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Server, executeCommand, arginfo_class_MongoDB_Driver_Server_executeCommand, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Server, executeQuery, arginfo_class_MongoDB_Driver_Server_executeQuery, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Server, executeReadCommand, arginfo_class_MongoDB_Driver_Server_executeReadCommand, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Server, executeReadWriteCommand, arginfo_class_MongoDB_Driver_Server_executeReadWriteCommand, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Server, executeWriteCommand, arginfo_class_MongoDB_Driver_Server_executeWriteCommand, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Server, getHost, arginfo_class_MongoDB_Driver_Server_getHost, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Server, getInfo, arginfo_class_MongoDB_Driver_Server_getInfo, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Server, getLatency, arginfo_class_MongoDB_Driver_Server_getLatency, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Server, getPort, arginfo_class_MongoDB_Driver_Server_getPort, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Server, getServerDescription, arginfo_class_MongoDB_Driver_Server_getServerDescription, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Server, getTags, arginfo_class_MongoDB_Driver_Server_getTags, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Server, getType, arginfo_class_MongoDB_Driver_Server_getType, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Server, isArbiter, arginfo_class_MongoDB_Driver_Server_isArbiter, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Server, isHidden, arginfo_class_MongoDB_Driver_Server_isHidden, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Server, isPassive, arginfo_class_MongoDB_Driver_Server_isPassive, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Server, isPrimary, arginfo_class_MongoDB_Driver_Server_isPrimary, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Server, isSecondary, arginfo_class_MongoDB_Driver_Server_isSecondary, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Server(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "Server", class_MongoDB_Driver_Server_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
zval const_TYPE_UNKNOWN_value;
ZVAL_LONG(&const_TYPE_UNKNOWN_value, PHONGO_SERVER_UNKNOWN);
zend_string *const_TYPE_UNKNOWN_name = zend_string_init_interned("TYPE_UNKNOWN", sizeof("TYPE_UNKNOWN") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_UNKNOWN_name, &const_TYPE_UNKNOWN_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_UNKNOWN_name);
zval const_TYPE_STANDALONE_value;
ZVAL_LONG(&const_TYPE_STANDALONE_value, PHONGO_SERVER_STANDALONE);
zend_string *const_TYPE_STANDALONE_name = zend_string_init_interned("TYPE_STANDALONE", sizeof("TYPE_STANDALONE") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_STANDALONE_name, &const_TYPE_STANDALONE_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_STANDALONE_name);
zval const_TYPE_MONGOS_value;
ZVAL_LONG(&const_TYPE_MONGOS_value, PHONGO_SERVER_MONGOS);
zend_string *const_TYPE_MONGOS_name = zend_string_init_interned("TYPE_MONGOS", sizeof("TYPE_MONGOS") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_MONGOS_name, &const_TYPE_MONGOS_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_MONGOS_name);
zval const_TYPE_POSSIBLE_PRIMARY_value;
ZVAL_LONG(&const_TYPE_POSSIBLE_PRIMARY_value, PHONGO_SERVER_POSSIBLE_PRIMARY);
zend_string *const_TYPE_POSSIBLE_PRIMARY_name = zend_string_init_interned("TYPE_POSSIBLE_PRIMARY", sizeof("TYPE_POSSIBLE_PRIMARY") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_POSSIBLE_PRIMARY_name, &const_TYPE_POSSIBLE_PRIMARY_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_POSSIBLE_PRIMARY_name);
zval const_TYPE_RS_PRIMARY_value;
ZVAL_LONG(&const_TYPE_RS_PRIMARY_value, PHONGO_SERVER_RS_PRIMARY);
zend_string *const_TYPE_RS_PRIMARY_name = zend_string_init_interned("TYPE_RS_PRIMARY", sizeof("TYPE_RS_PRIMARY") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_RS_PRIMARY_name, &const_TYPE_RS_PRIMARY_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_RS_PRIMARY_name);
zval const_TYPE_RS_SECONDARY_value;
ZVAL_LONG(&const_TYPE_RS_SECONDARY_value, PHONGO_SERVER_RS_SECONDARY);
zend_string *const_TYPE_RS_SECONDARY_name = zend_string_init_interned("TYPE_RS_SECONDARY", sizeof("TYPE_RS_SECONDARY") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_RS_SECONDARY_name, &const_TYPE_RS_SECONDARY_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_RS_SECONDARY_name);
zval const_TYPE_RS_ARBITER_value;
ZVAL_LONG(&const_TYPE_RS_ARBITER_value, PHONGO_SERVER_RS_ARBITER);
zend_string *const_TYPE_RS_ARBITER_name = zend_string_init_interned("TYPE_RS_ARBITER", sizeof("TYPE_RS_ARBITER") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_RS_ARBITER_name, &const_TYPE_RS_ARBITER_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_RS_ARBITER_name);
zval const_TYPE_RS_OTHER_value;
ZVAL_LONG(&const_TYPE_RS_OTHER_value, PHONGO_SERVER_RS_OTHER);
zend_string *const_TYPE_RS_OTHER_name = zend_string_init_interned("TYPE_RS_OTHER", sizeof("TYPE_RS_OTHER") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_RS_OTHER_name, &const_TYPE_RS_OTHER_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_RS_OTHER_name);
zval const_TYPE_RS_GHOST_value;
ZVAL_LONG(&const_TYPE_RS_GHOST_value, PHONGO_SERVER_RS_GHOST);
zend_string *const_TYPE_RS_GHOST_name = zend_string_init_interned("TYPE_RS_GHOST", sizeof("TYPE_RS_GHOST") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_RS_GHOST_name, &const_TYPE_RS_GHOST_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_RS_GHOST_name);
zval const_TYPE_LOAD_BALANCER_value;
ZVAL_LONG(&const_TYPE_LOAD_BALANCER_value, PHONGO_SERVER_LOAD_BALANCER);
zend_string *const_TYPE_LOAD_BALANCER_name = zend_string_init_interned("TYPE_LOAD_BALANCER", sizeof("TYPE_LOAD_BALANCER") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_LOAD_BALANCER_name, &const_TYPE_LOAD_BALANCER_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_LOAD_BALANCER_name);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/Session.c 0000644 0001751 0000166 00000051076 15014033047 013731 0 ustar /*
* Copyright 2017-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bson/bson.h"
#include "mongoc/mongoc.h"
#include
#include
#include "php_array_api.h"
#include "php_phongo.h"
#include "phongo_bson_encode.h"
#include "phongo_client.h"
#include "phongo_error.h"
#include "MongoDB/ReadConcern.h"
#include "MongoDB/ReadPreference.h"
#include "MongoDB/Server.h"
#include "MongoDB/Session.h"
#include "MongoDB/WriteConcern.h"
#include "Session_arginfo.h"
#include "BSON/Timestamp.h"
zend_class_entry* php_phongo_session_ce;
#define SESSION_CHECK_LIVELINESS(i, m) \
if (!(i)->client_session) { \
phongo_throw_exception( \
PHONGO_ERROR_LOGIC, \
"Cannot call '%s', as the session has already been ended.", \
(m)); \
return; \
}
static bool php_phongo_session_get_timestamp_parts(zval* obj, uint32_t* timestamp, uint32_t* increment)
{
bool retval = false;
zval ztimestamp = ZVAL_STATIC_INIT;
zval zincrement = ZVAL_STATIC_INIT;
zend_call_method_with_0_params(Z_OBJ_P(obj), NULL, NULL, "getTimestamp", &ztimestamp);
if (Z_ISUNDEF(ztimestamp) || EG(exception)) {
goto cleanup;
}
zend_call_method_with_0_params(Z_OBJ_P(obj), NULL, NULL, "getIncrement", &zincrement);
if (Z_ISUNDEF(zincrement) || EG(exception)) {
goto cleanup;
}
*timestamp = Z_LVAL(ztimestamp);
*increment = Z_LVAL(zincrement);
retval = true;
cleanup:
if (!Z_ISUNDEF(ztimestamp)) {
zval_ptr_dtor(&ztimestamp);
}
if (!Z_ISUNDEF(zincrement)) {
zval_ptr_dtor(&zincrement);
}
return retval;
}
static const char* php_phongo_get_transaction_state_string(mongoc_transaction_state_t state)
{
switch (state) {
case MONGOC_TRANSACTION_NONE:
return PHONGO_TRANSACTION_NONE;
case MONGOC_TRANSACTION_STARTING:
return PHONGO_TRANSACTION_STARTING;
case MONGOC_TRANSACTION_IN_PROGRESS:
return PHONGO_TRANSACTION_IN_PROGRESS;
case MONGOC_TRANSACTION_COMMITTED:
return PHONGO_TRANSACTION_COMMITTED;
case MONGOC_TRANSACTION_ABORTED:
return PHONGO_TRANSACTION_ABORTED;
default:
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Invalid transaction state %d given", (int) state);
return NULL;
}
}
static void php_phongo_transaction_options_to_zval(mongoc_client_session_t* cs, zval* retval)
{
mongoc_transaction_opt_t* opts;
int64_t max_commit_time_ms;
const mongoc_read_concern_t* read_concern;
const mongoc_read_prefs_t* read_preference;
const mongoc_write_concern_t* write_concern;
if (!cs) {
ZVAL_NULL(retval);
return;
}
opts = mongoc_session_opts_get_transaction_opts(cs);
if (!opts) {
ZVAL_NULL(retval);
return;
}
max_commit_time_ms = mongoc_transaction_opts_get_max_commit_time_ms(opts);
read_concern = mongoc_transaction_opts_get_read_concern(opts);
read_preference = mongoc_transaction_opts_get_read_prefs(opts);
write_concern = mongoc_transaction_opts_get_write_concern(opts);
array_init_size(retval, 4);
if (max_commit_time_ms) {
ADD_ASSOC_LONG_EX(retval, "maxCommitTimeMS", max_commit_time_ms);
}
if (!mongoc_read_concern_is_default(read_concern)) {
zval zread_concern;
phongo_readconcern_init(&zread_concern, read_concern);
ADD_ASSOC_ZVAL_EX(retval, "readConcern", &zread_concern);
}
if (read_preference) {
zval zread_preference;
phongo_readpreference_init(&zread_preference, read_preference);
ADD_ASSOC_ZVAL_EX(retval, "readPreference", &zread_preference);
}
if (!mongoc_write_concern_is_default(write_concern)) {
zval zwrite_concern;
phongo_writeconcern_init(&zwrite_concern, write_concern);
ADD_ASSOC_ZVAL_EX(retval, "writeConcern", &zwrite_concern);
}
mongoc_transaction_opts_destroy(opts);
}
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Session)
/* Advances the cluster time for this Session */
static PHP_METHOD(MongoDB_Driver_Session, advanceClusterTime)
{
php_phongo_session_t* intern;
zval* zcluster_time;
bson_t cluster_time = BSON_INITIALIZER;
intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "advanceClusterTime")
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY_OR_OBJECT(zcluster_time)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_zval_to_bson(zcluster_time, PHONGO_BSON_NONE, &cluster_time, NULL);
/* An exception may be thrown during BSON conversion */
if (EG(exception)) {
goto cleanup;
}
mongoc_client_session_advance_cluster_time(intern->client_session, &cluster_time);
cleanup:
bson_destroy(&cluster_time);
}
/* Advances the operation time for this Session */
static PHP_METHOD(MongoDB_Driver_Session, advanceOperationTime)
{
php_phongo_session_t* intern;
zval* ztimestamp;
uint32_t timestamp = 0;
uint32_t increment = 0;
intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "advanceOperationTime")
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_OBJECT_OF_CLASS(ztimestamp, php_phongo_timestamp_interface_ce)
PHONGO_PARSE_PARAMETERS_END();
if (!php_phongo_session_get_timestamp_parts(ztimestamp, ×tamp, &increment)) {
return;
}
mongoc_client_session_advance_operation_time(intern->client_session, timestamp, increment);
}
/* Returns the cluster time for this Session */
static PHP_METHOD(MongoDB_Driver_Session, getClusterTime)
{
php_phongo_session_t* intern;
const bson_t* cluster_time;
php_phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "getClusterTime")
PHONGO_PARSE_PARAMETERS_NONE();
cluster_time = mongoc_client_session_get_cluster_time(intern->client_session);
if (!cluster_time) {
RETURN_NULL();
}
if (!php_phongo_bson_to_zval_ex(cluster_time, &state)) {
/* Exception should already have been thrown */
zval_ptr_dtor(&state.zchild);
return;
}
RETURN_ZVAL(&state.zchild, 0, 1);
}
/* Returns the logical session ID for this Session */
static PHP_METHOD(MongoDB_Driver_Session, getLogicalSessionId)
{
php_phongo_session_t* intern;
const bson_t* lsid;
php_phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "getLogicalSessionId")
PHONGO_PARSE_PARAMETERS_NONE();
lsid = mongoc_client_session_get_lsid(intern->client_session);
if (!php_phongo_bson_to_zval_ex(lsid, &state)) {
/* Exception should already have been thrown */
zval_ptr_dtor(&state.zchild);
return;
}
RETURN_ZVAL(&state.zchild, 0, 1);
}
/* Returns the operation time for this Session */
static PHP_METHOD(MongoDB_Driver_Session, getOperationTime)
{
php_phongo_session_t* intern;
uint32_t timestamp, increment;
intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "getOperationTime")
PHONGO_PARSE_PARAMETERS_NONE();
mongoc_client_session_get_operation_time(intern->client_session, ×tamp, &increment);
/* mongoc_client_session_get_operation_time() returns 0 for both parts if
* the session has not been used. According to the causal consistency spec,
* the operation time for an unused session is null. */
if (timestamp == 0 && increment == 0) {
RETURN_NULL();
}
phongo_timestamp_new(return_value, increment, timestamp);
}
/* Returns the server this session is pinned to */
static PHP_METHOD(MongoDB_Driver_Session, getServer)
{
php_phongo_session_t* intern;
uint32_t server_id = 0;
intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "getServer")
PHONGO_PARSE_PARAMETERS_NONE();
server_id = mongoc_client_session_get_server_id(intern->client_session);
/* For sessions without a pinned server, 0 is returned. */
if (!server_id) {
RETURN_NULL();
}
phongo_server_init(return_value, &intern->manager, server_id);
}
/* Returns options for the currently running transaction */
static PHP_METHOD(MongoDB_Driver_Session, getTransactionOptions)
{
php_phongo_session_t* intern;
intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "getTransactionOptions")
PHONGO_PARSE_PARAMETERS_NONE();
php_phongo_transaction_options_to_zval(intern->client_session, return_value);
}
/* Returns the current transaction state for this session */
static PHP_METHOD(MongoDB_Driver_Session, getTransactionState)
{
php_phongo_session_t* intern;
const char* state;
intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "getTransactionState")
PHONGO_PARSE_PARAMETERS_NONE();
state = php_phongo_get_transaction_state_string(mongoc_client_session_get_transaction_state(intern->client_session));
if (!state) {
/* Exception already thrown */
return;
}
RETURN_STRING(state);
}
/* Creates a opts structure from an array optionally containing an RP, RC,
* WC object, and/or maxCommitTimeMS int. Returns NULL if no options were found,
* or there was an invalid option. If there was an invalid option or structure,
* an exception will be thrown too. */
mongoc_transaction_opt_t* php_mongodb_session_parse_transaction_options(zval* options)
{
mongoc_transaction_opt_t* opts = NULL;
if (php_array_existsc(options, "maxCommitTimeMS")) {
int64_t max_commit_time_ms = php_array_fetchc_long(options, "maxCommitTimeMS");
if (max_commit_time_ms < 0) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"maxCommitTimeMS\" option to be >= 0, %" PRId64 " given", max_commit_time_ms);
/* Freeing opts is not needed here, as it can't be set yet. The
* code is here to keep it consistent with the others in case more
* options are added before this one. */
if (opts) {
mongoc_transaction_opts_destroy(opts);
}
return NULL;
}
if (max_commit_time_ms > UINT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"maxCommitTimeMS\" option to be <= %" PRIu32 ", %" PRId64 " given", UINT32_MAX, max_commit_time_ms);
/* Freeing opts is not needed here, as it can't be set yet. The
* code is here to keep it consistent with the others in case more
* options are added before this one. */
if (opts) {
mongoc_transaction_opts_destroy(opts);
}
return NULL;
}
if (!opts) {
opts = mongoc_transaction_opts_new();
}
mongoc_transaction_opts_set_max_commit_time_ms(opts, max_commit_time_ms);
}
if (php_array_existsc(options, "readConcern")) {
zval* read_concern = php_array_fetchc_deref(options, "readConcern");
if (Z_TYPE_P(read_concern) != IS_OBJECT || !instanceof_function(Z_OBJCE_P(read_concern), php_phongo_readconcern_ce)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"readConcern\" option to be %s, %s given", ZSTR_VAL(php_phongo_readconcern_ce->name), zend_zval_type_name(read_concern));
if (opts) {
mongoc_transaction_opts_destroy(opts);
}
return NULL;
}
if (!opts) {
opts = mongoc_transaction_opts_new();
}
mongoc_transaction_opts_set_read_concern(opts, phongo_read_concern_from_zval(read_concern));
}
if (php_array_existsc(options, "readPreference")) {
zval* read_preference = php_array_fetchc_deref(options, "readPreference");
if (Z_TYPE_P(read_preference) != IS_OBJECT || !instanceof_function(Z_OBJCE_P(read_preference), php_phongo_readpreference_ce)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"readPreference\" option to be %s, %s given", ZSTR_VAL(php_phongo_readpreference_ce->name), zend_zval_type_name(read_preference));
if (opts) {
mongoc_transaction_opts_destroy(opts);
}
return NULL;
}
if (!opts) {
opts = mongoc_transaction_opts_new();
}
mongoc_transaction_opts_set_read_prefs(opts, phongo_read_preference_from_zval(read_preference));
}
if (php_array_existsc(options, "writeConcern")) {
zval* write_concern = php_array_fetchc_deref(options, "writeConcern");
if (Z_TYPE_P(write_concern) != IS_OBJECT || !instanceof_function(Z_OBJCE_P(write_concern), php_phongo_writeconcern_ce)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"writeConcern\" option to be %s, %s given", ZSTR_VAL(php_phongo_writeconcern_ce->name), zend_zval_type_name(write_concern));
if (opts) {
mongoc_transaction_opts_destroy(opts);
}
return NULL;
}
if (!opts) {
opts = mongoc_transaction_opts_new();
}
mongoc_transaction_opts_set_write_concern(opts, phongo_write_concern_from_zval(write_concern));
}
return opts;
}
/* Starts a new transaction */
static PHP_METHOD(MongoDB_Driver_Session, startTransaction)
{
php_phongo_session_t* intern;
zval* options = NULL;
mongoc_transaction_opt_t* txn_options = NULL;
bson_error_t error;
intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "startTransaction")
PHONGO_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
if (options) {
txn_options = php_mongodb_session_parse_transaction_options(options);
}
if (EG(exception)) {
return;
}
if (!mongoc_client_session_start_transaction(intern->client_session, txn_options, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
}
if (txn_options) {
mongoc_transaction_opts_destroy(txn_options);
}
}
/* Commits an existing transaction */
static PHP_METHOD(MongoDB_Driver_Session, commitTransaction)
{
php_phongo_session_t* intern;
bson_error_t error;
bson_t reply;
intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "commitTransaction")
PHONGO_PARSE_PARAMETERS_NONE();
if (!mongoc_client_session_commit_transaction(intern->client_session, &reply, &error)) {
phongo_throw_exception_from_bson_error_t_and_reply(&error, &reply);
}
bson_destroy(&reply);
}
/* Aborts (rolls back) an existing transaction */
static PHP_METHOD(MongoDB_Driver_Session, abortTransaction)
{
php_phongo_session_t* intern;
bson_error_t error;
intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "abortTransaction")
PHONGO_PARSE_PARAMETERS_NONE();
if (!mongoc_client_session_abort_transaction(intern->client_session, &error)) {
phongo_throw_exception_from_bson_error_t(&error);
}
}
/* Ends the session, and a running transaction if active */
static PHP_METHOD(MongoDB_Driver_Session, endSession)
{
php_phongo_session_t* intern;
intern = Z_SESSION_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
mongoc_client_session_destroy(intern->client_session);
intern->client_session = NULL;
}
/* Returns whether the session is dirty (i.e. was used with a command that
encountered a network error) and will be discarded when returned to the
server session pool. */
static PHP_METHOD(MongoDB_Driver_Session, isDirty)
{
php_phongo_session_t* intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "isDirty")
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_BOOL(mongoc_client_session_get_dirty(intern->client_session));
}
/* Returns whether a multi-document transaction is in progress */
static PHP_METHOD(MongoDB_Driver_Session, isInTransaction)
{
php_phongo_session_t* intern;
intern = Z_SESSION_OBJ_P(getThis());
SESSION_CHECK_LIVELINESS(intern, "isInTransaction")
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_BOOL(mongoc_client_session_in_transaction(intern->client_session));
}
/* MongoDB\Driver\Session object handlers */
static zend_object_handlers php_phongo_handler_session;
static void php_phongo_session_free_object(zend_object* object)
{
php_phongo_session_t* intern = Z_OBJ_SESSION(object);
zend_object_std_dtor(&intern->std);
/* If this Session was created in a different process, reset the client so
* that its session pool is cleared and mongoc_client_session_destroy will
* destroy the corresponding server session rather than return it to the
* now-empty pool. This will ensure that we do not re-use a server session
* (i.e. LSID) created by a parent process. */
PHONGO_RESET_CLIENT_IF_PID_DIFFERS(intern, Z_MANAGER_OBJ_P(&intern->manager));
if (intern->client_session) {
mongoc_client_session_destroy(intern->client_session);
}
if (!Z_ISUNDEF(intern->manager)) {
zval_ptr_dtor(&intern->manager);
}
}
static zend_object* php_phongo_session_create_object(zend_class_entry* class_type)
{
php_phongo_session_t* intern = zend_object_alloc(sizeof(php_phongo_session_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
PHONGO_SET_CREATED_BY_PID(intern);
intern->std.handlers = &php_phongo_handler_session;
return &intern->std;
}
static HashTable* php_phongo_session_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_session_t* intern = NULL;
zval retval = ZVAL_STATIC_INIT;
*is_temp = 1;
intern = Z_OBJ_SESSION(object);
array_init(&retval);
if (!intern->client_session) {
ADD_ASSOC_BOOL_EX(&retval, "ended", true);
goto done;
}
{
const bson_t* lsid = mongoc_client_session_get_lsid(intern->client_session);
php_phongo_bson_state state;
PHONGO_BSON_INIT_DEBUG_STATE(state);
if (!php_phongo_bson_to_zval_ex(lsid, &state)) {
zval_ptr_dtor(&state.zchild);
goto done;
}
ADD_ASSOC_ZVAL_EX(&retval, "logicalSessionId", &state.zchild);
}
{
const bson_t* cluster_time = mongoc_client_session_get_cluster_time(intern->client_session);
if (cluster_time) {
php_phongo_bson_state state;
PHONGO_BSON_INIT_DEBUG_STATE(state);
if (!php_phongo_bson_to_zval_ex(cluster_time, &state)) {
zval_ptr_dtor(&state.zchild);
goto done;
}
ADD_ASSOC_ZVAL_EX(&retval, "clusterTime", &state.zchild);
} else {
ADD_ASSOC_NULL_EX(&retval, "clusterTime");
}
}
{
const mongoc_session_opt_t* cs_opts = mongoc_client_session_get_opts(intern->client_session);
ADD_ASSOC_BOOL_EX(&retval, "causalConsistency", mongoc_session_opts_get_causal_consistency(cs_opts));
ADD_ASSOC_BOOL_EX(&retval, "snapshot", mongoc_session_opts_get_snapshot(cs_opts));
}
{
uint32_t timestamp, increment;
mongoc_client_session_get_operation_time(intern->client_session, ×tamp, &increment);
if (timestamp && increment) {
zval ztimestamp;
if (!phongo_timestamp_new(&ztimestamp, increment, timestamp)) {
/* Exception should already have been thrown */
goto done;
}
ADD_ASSOC_ZVAL_EX(&retval, "operationTime", &ztimestamp);
} else {
ADD_ASSOC_NULL_EX(&retval, "operationTime");
}
}
{
uint32_t server_id = mongoc_client_session_get_server_id(intern->client_session);
if (server_id) {
zval server;
phongo_server_init(&server, &intern->manager, server_id);
ADD_ASSOC_ZVAL_EX(&retval, "server", &server);
} else {
ADD_ASSOC_NULL_EX(&retval, "server");
}
}
ADD_ASSOC_BOOL_EX(&retval, "dirty", mongoc_client_session_get_dirty(intern->client_session));
ADD_ASSOC_BOOL_EX(&retval, "inTransaction", mongoc_client_session_in_transaction(intern->client_session));
{
const char* state = php_phongo_get_transaction_state_string(mongoc_client_session_get_transaction_state(intern->client_session));
if (!state) {
/* Exception should already have been thrown */
goto done;
}
ADD_ASSOC_STRING(&retval, "transactionState", state);
}
{
zval txn_opts;
php_phongo_transaction_options_to_zval(intern->client_session, &txn_opts);
ADD_ASSOC_ZVAL_EX(&retval, "transactionOptions", &txn_opts);
}
done:
return Z_ARRVAL(retval);
}
void php_phongo_session_init_ce(INIT_FUNC_ARGS)
{
php_phongo_session_ce = register_class_MongoDB_Driver_Session();
php_phongo_session_ce->create_object = php_phongo_session_create_object;
memcpy(&php_phongo_handler_session, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_session.get_debug_info = php_phongo_session_get_debug_info;
php_phongo_handler_session.free_obj = php_phongo_session_free_object;
php_phongo_handler_session.offset = XtOffsetOf(php_phongo_session_t, std);
}
void phongo_session_init(zval* return_value, zval* manager, mongoc_client_session_t* client_session)
{
php_phongo_session_t* session;
object_init_ex(return_value, php_phongo_session_ce);
session = Z_SESSION_OBJ_P(return_value);
session->client_session = client_session;
ZVAL_ZVAL(&session->manager, manager, 1, 0);
}
mongodb-2.1.0/src/MongoDB/Session.h 0000644 0001751 0000166 00000002254 15014033047 013730 0 ustar /*
* Copyright 2017-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHP_MONGODB_DRIVER_SESSION_H
#define PHP_MONGODB_DRIVER_SESSION_H
#include "mongoc/mongoc.h"
#include
#define PHONGO_TRANSACTION_NONE "none"
#define PHONGO_TRANSACTION_STARTING "starting"
#define PHONGO_TRANSACTION_IN_PROGRESS "in_progress"
#define PHONGO_TRANSACTION_COMMITTED "committed"
#define PHONGO_TRANSACTION_ABORTED "aborted"
mongoc_transaction_opt_t* php_mongodb_session_parse_transaction_options(zval* txnOptions);
void phongo_session_init(zval* return_value, zval* manager, mongoc_client_session_t* client_session);
#endif /* PHP_MONGODB_DRIVER_SESSION_H */
mongodb-2.1.0/src/MongoDB/Session_arginfo.h 0000644 0001751 0000166 00000020732 15014033047 015436 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 22e0a387ed21d232c61f805ba258c4781a08a68e */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_Session___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Session_abortTransaction, 0, 0, IS_VOID, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Session_advanceClusterTime, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_MASK(0, clusterTime, MAY_BE_ARRAY|MAY_BE_OBJECT, NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Session_advanceOperationTime, 0, 1, IS_VOID, 0)
ZEND_ARG_OBJ_INFO(0, operationTime, MongoDB\\BSON\\TimestampInterface, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_Session_commitTransaction arginfo_class_MongoDB_Driver_Session_abortTransaction
#define arginfo_class_MongoDB_Driver_Session_endSession arginfo_class_MongoDB_Driver_Session_abortTransaction
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Session_getClusterTime, 0, 0, IS_OBJECT, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Session_getLogicalSessionId, 0, 0, IS_OBJECT, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Session_getOperationTime, 0, 0, MongoDB\\BSON\\Timestamp, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_Session_getServer, 0, 0, MongoDB\\Driver\\Server, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Session_getTransactionOptions, 0, 0, IS_ARRAY, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Session_getTransactionState, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Session_isDirty, 0, 0, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_Session_isInTransaction arginfo_class_MongoDB_Driver_Session_isDirty
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_Session_startTransaction, 0, 0, IS_VOID, 0)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, options, IS_ARRAY, 1, "null")
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_Session, __construct);
static ZEND_METHOD(MongoDB_Driver_Session, abortTransaction);
static ZEND_METHOD(MongoDB_Driver_Session, advanceClusterTime);
static ZEND_METHOD(MongoDB_Driver_Session, advanceOperationTime);
static ZEND_METHOD(MongoDB_Driver_Session, commitTransaction);
static ZEND_METHOD(MongoDB_Driver_Session, endSession);
static ZEND_METHOD(MongoDB_Driver_Session, getClusterTime);
static ZEND_METHOD(MongoDB_Driver_Session, getLogicalSessionId);
static ZEND_METHOD(MongoDB_Driver_Session, getOperationTime);
static ZEND_METHOD(MongoDB_Driver_Session, getServer);
static ZEND_METHOD(MongoDB_Driver_Session, getTransactionOptions);
static ZEND_METHOD(MongoDB_Driver_Session, getTransactionState);
static ZEND_METHOD(MongoDB_Driver_Session, isDirty);
static ZEND_METHOD(MongoDB_Driver_Session, isInTransaction);
static ZEND_METHOD(MongoDB_Driver_Session, startTransaction);
static const zend_function_entry class_MongoDB_Driver_Session_methods[] = {
ZEND_ME(MongoDB_Driver_Session, __construct, arginfo_class_MongoDB_Driver_Session___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Session, abortTransaction, arginfo_class_MongoDB_Driver_Session_abortTransaction, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Session, advanceClusterTime, arginfo_class_MongoDB_Driver_Session_advanceClusterTime, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Session, advanceOperationTime, arginfo_class_MongoDB_Driver_Session_advanceOperationTime, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Session, commitTransaction, arginfo_class_MongoDB_Driver_Session_commitTransaction, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Session, endSession, arginfo_class_MongoDB_Driver_Session_endSession, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Session, getClusterTime, arginfo_class_MongoDB_Driver_Session_getClusterTime, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Session, getLogicalSessionId, arginfo_class_MongoDB_Driver_Session_getLogicalSessionId, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Session, getOperationTime, arginfo_class_MongoDB_Driver_Session_getOperationTime, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Session, getServer, arginfo_class_MongoDB_Driver_Session_getServer, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Session, getTransactionOptions, arginfo_class_MongoDB_Driver_Session_getTransactionOptions, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Session, getTransactionState, arginfo_class_MongoDB_Driver_Session_getTransactionState, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Session, isDirty, arginfo_class_MongoDB_Driver_Session_isDirty, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Session, isInTransaction, arginfo_class_MongoDB_Driver_Session_isInTransaction, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_Session, startTransaction, arginfo_class_MongoDB_Driver_Session_startTransaction, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_Session(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "Session", class_MongoDB_Driver_Session_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
zval const_TRANSACTION_NONE_value;
zend_string *const_TRANSACTION_NONE_value_str = zend_string_init(PHONGO_TRANSACTION_NONE, strlen(PHONGO_TRANSACTION_NONE), 1);
ZVAL_STR(&const_TRANSACTION_NONE_value, const_TRANSACTION_NONE_value_str);
zend_string *const_TRANSACTION_NONE_name = zend_string_init_interned("TRANSACTION_NONE", sizeof("TRANSACTION_NONE") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TRANSACTION_NONE_name, &const_TRANSACTION_NONE_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TRANSACTION_NONE_name);
zval const_TRANSACTION_STARTING_value;
zend_string *const_TRANSACTION_STARTING_value_str = zend_string_init(PHONGO_TRANSACTION_STARTING, strlen(PHONGO_TRANSACTION_STARTING), 1);
ZVAL_STR(&const_TRANSACTION_STARTING_value, const_TRANSACTION_STARTING_value_str);
zend_string *const_TRANSACTION_STARTING_name = zend_string_init_interned("TRANSACTION_STARTING", sizeof("TRANSACTION_STARTING") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TRANSACTION_STARTING_name, &const_TRANSACTION_STARTING_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TRANSACTION_STARTING_name);
zval const_TRANSACTION_IN_PROGRESS_value;
zend_string *const_TRANSACTION_IN_PROGRESS_value_str = zend_string_init(PHONGO_TRANSACTION_IN_PROGRESS, strlen(PHONGO_TRANSACTION_IN_PROGRESS), 1);
ZVAL_STR(&const_TRANSACTION_IN_PROGRESS_value, const_TRANSACTION_IN_PROGRESS_value_str);
zend_string *const_TRANSACTION_IN_PROGRESS_name = zend_string_init_interned("TRANSACTION_IN_PROGRESS", sizeof("TRANSACTION_IN_PROGRESS") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TRANSACTION_IN_PROGRESS_name, &const_TRANSACTION_IN_PROGRESS_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TRANSACTION_IN_PROGRESS_name);
zval const_TRANSACTION_COMMITTED_value;
zend_string *const_TRANSACTION_COMMITTED_value_str = zend_string_init(PHONGO_TRANSACTION_COMMITTED, strlen(PHONGO_TRANSACTION_COMMITTED), 1);
ZVAL_STR(&const_TRANSACTION_COMMITTED_value, const_TRANSACTION_COMMITTED_value_str);
zend_string *const_TRANSACTION_COMMITTED_name = zend_string_init_interned("TRANSACTION_COMMITTED", sizeof("TRANSACTION_COMMITTED") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TRANSACTION_COMMITTED_name, &const_TRANSACTION_COMMITTED_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TRANSACTION_COMMITTED_name);
zval const_TRANSACTION_ABORTED_value;
zend_string *const_TRANSACTION_ABORTED_value_str = zend_string_init(PHONGO_TRANSACTION_ABORTED, strlen(PHONGO_TRANSACTION_ABORTED), 1);
ZVAL_STR(&const_TRANSACTION_ABORTED_value, const_TRANSACTION_ABORTED_value_str);
zend_string *const_TRANSACTION_ABORTED_name = zend_string_init_interned("TRANSACTION_ABORTED", sizeof("TRANSACTION_ABORTED") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TRANSACTION_ABORTED_name, &const_TRANSACTION_ABORTED_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TRANSACTION_ABORTED_name);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/TopologyDescription.c 0000644 0001751 0000166 00000015041 15014033047 016316 0 ustar /*
* Copyright 2021-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mongoc/mongoc.h"
#include
#include
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "MongoDB/ReadPreference.h"
#include "MongoDB/ServerDescription.h"
#include "MongoDB/TopologyDescription.h"
#include "TopologyDescription_arginfo.h"
zend_class_entry* php_phongo_topologydescription_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_TopologyDescription)
/* Returns an array of ServerDescription objects for all known servers in the topology */
static PHP_METHOD(MongoDB_Driver_TopologyDescription, getServers)
{
php_phongo_topologydescription_t* intern;
mongoc_server_description_t** sds;
size_t i, n = 0;
intern = Z_TOPOLOGYDESCRIPTION_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
sds = mongoc_topology_description_get_servers(intern->topology_description, &n);
array_init_size(return_value, n);
for (i = 0; i < n; i++) {
zval sd;
phongo_serverdescription_init(&sd, sds[i]);
add_next_index_zval(return_value, &sd);
}
mongoc_server_descriptions_destroy_all(sds, n);
}
/* Returns whether the topology has a readable server available */
static PHP_METHOD(MongoDB_Driver_TopologyDescription, hasReadableServer)
{
php_phongo_topologydescription_t* intern;
const mongoc_read_prefs_t* read_preference = NULL;
zval* z_read_preference = NULL;
intern = Z_TOPOLOGYDESCRIPTION_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_OBJECT_OF_CLASS(z_read_preference, php_phongo_readpreference_ce)
PHONGO_PARSE_PARAMETERS_END();
if (z_read_preference) {
read_preference = phongo_read_preference_from_zval(z_read_preference);
}
RETVAL_BOOL(mongoc_topology_description_has_readable_server(intern->topology_description, read_preference));
}
/* Returns whether the topology has a writable server available */
static PHP_METHOD(MongoDB_Driver_TopologyDescription, hasWritableServer)
{
php_phongo_topologydescription_t* intern = Z_TOPOLOGYDESCRIPTION_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_BOOL(mongoc_topology_description_has_writable_server(intern->topology_description));
}
/* Returns the topology type */
static PHP_METHOD(MongoDB_Driver_TopologyDescription, getType)
{
php_phongo_topologydescription_t* intern = Z_TOPOLOGYDESCRIPTION_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRING(mongoc_topology_description_type(intern->topology_description));
}
/* MongoDB\Driver\TopologyDescription object handlers */
static zend_object_handlers php_phongo_handler_topologydescription;
static void php_phongo_topologydescription_free_object(zend_object* object)
{
php_phongo_topologydescription_t* intern = Z_OBJ_TOPOLOGYDESCRIPTION(object);
zend_object_std_dtor(&intern->std);
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
if (intern->topology_description) {
mongoc_topology_description_destroy(intern->topology_description);
}
}
static zend_object* php_phongo_topologydescription_create_object(zend_class_entry* class_type)
{
php_phongo_topologydescription_t* intern = zend_object_alloc(sizeof(php_phongo_topologydescription_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_topologydescription;
return &intern->std;
}
HashTable* php_phongo_topologydescription_get_properties_hash(zend_object* object, bool is_debug)
{
php_phongo_topologydescription_t* intern = NULL;
HashTable* props;
intern = Z_OBJ_TOPOLOGYDESCRIPTION(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_debug, intern, props, 2);
if (!intern->topology_description) {
return props;
}
{
zval servers;
size_t i, n = 0;
mongoc_server_description_t** sds = mongoc_topology_description_get_servers(intern->topology_description, &n);
array_init_size(&servers, n);
for (i = 0; i < n; i++) {
zval sd;
phongo_serverdescription_init(&sd, sds[i]);
add_next_index_zval(&servers, &sd);
}
zend_hash_str_update(props, "servers", sizeof("servers") - 1, &servers);
mongoc_server_descriptions_destroy_all(sds, n);
}
{
zval type;
ZVAL_STRING(&type, mongoc_topology_description_type(intern->topology_description));
zend_hash_str_update(props, "type", sizeof("type") - 1, &type);
}
return props;
}
static HashTable* php_phongo_topologydescription_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return php_phongo_topologydescription_get_properties_hash(object, true);
}
static HashTable* php_phongo_topologydescription_get_properties(zend_object* object)
{
return php_phongo_topologydescription_get_properties_hash(object, false);
}
void php_phongo_topologydescription_init_ce(INIT_FUNC_ARGS)
{
php_phongo_topologydescription_ce = register_class_MongoDB_Driver_TopologyDescription();
php_phongo_topologydescription_ce->create_object = php_phongo_topologydescription_create_object;
memcpy(&php_phongo_handler_topologydescription, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_topologydescription.get_debug_info = php_phongo_topologydescription_get_debug_info;
php_phongo_handler_topologydescription.get_properties = php_phongo_topologydescription_get_properties;
php_phongo_handler_topologydescription.free_obj = php_phongo_topologydescription_free_object;
php_phongo_handler_topologydescription.offset = XtOffsetOf(php_phongo_topologydescription_t, std);
}
void phongo_topologydescription_init(zval* return_value, mongoc_topology_description_t* topology_description)
{
php_phongo_topologydescription_t* intern;
object_init_ex(return_value, php_phongo_topologydescription_ce);
intern = Z_TOPOLOGYDESCRIPTION_OBJ_P(return_value);
intern->topology_description = mongoc_topology_description_new_copy(topology_description);
}
mongodb-2.1.0/src/MongoDB/TopologyDescription.h 0000644 0001751 0000166 00000002462 15014033047 016326 0 ustar /*
* Copyright 2022-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_TOPOLOGYDESCRIPTION_H
#define PHONGO_TOPOLOGYDESCRIPTION_H
#include "mongoc/mongoc.h"
#include
/* Note: these constants are derived from _mongoc_topology_description_type,
* since mongoc_topology_description_t is private. */
#define PHONGO_TOPOLOGY_UNKNOWN "Unknown"
#define PHONGO_TOPOLOGY_SINGLE "Single"
#define PHONGO_TOPOLOGY_SHARDED "Sharded"
#define PHONGO_TOPOLOGY_REPLICA_SET_NO_PRIMARY "ReplicaSetNoPrimary"
#define PHONGO_TOPOLOGY_REPLICA_SET_WITH_PRIMARY "ReplicaSetWithPrimary"
#define PHONGO_TOPOLOGY_LOAD_BALANCED "LoadBalanced"
void phongo_topologydescription_init(zval* return_value, mongoc_topology_description_t* topology_description);
#endif /* PHONGO_TOPOLOGYDESCRIPTION_H */
mongodb-2.1.0/src/MongoDB/TopologyDescription_arginfo.h 0000644 0001751 0000166 00000013607 15014033047 020036 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 2cd175f4e81e332cd83adb867d51db77907ee8c7 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_TopologyDescription___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_TopologyDescription_getServers, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_TopologyDescription_getType, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_TopologyDescription_hasReadableServer, 0, 0, _IS_BOOL, 0)
ZEND_ARG_OBJ_INFO_WITH_DEFAULT_VALUE(0, readPreference, MongoDB\\Driver\\ReadPreference, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_TopologyDescription_hasWritableServer, 0, 0, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_TopologyDescription, __construct);
static ZEND_METHOD(MongoDB_Driver_TopologyDescription, getServers);
static ZEND_METHOD(MongoDB_Driver_TopologyDescription, getType);
static ZEND_METHOD(MongoDB_Driver_TopologyDescription, hasReadableServer);
static ZEND_METHOD(MongoDB_Driver_TopologyDescription, hasWritableServer);
static const zend_function_entry class_MongoDB_Driver_TopologyDescription_methods[] = {
ZEND_ME(MongoDB_Driver_TopologyDescription, __construct, arginfo_class_MongoDB_Driver_TopologyDescription___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_TopologyDescription, getServers, arginfo_class_MongoDB_Driver_TopologyDescription_getServers, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_TopologyDescription, getType, arginfo_class_MongoDB_Driver_TopologyDescription_getType, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_TopologyDescription, hasReadableServer, arginfo_class_MongoDB_Driver_TopologyDescription_hasReadableServer, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_TopologyDescription, hasWritableServer, arginfo_class_MongoDB_Driver_TopologyDescription_hasWritableServer, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_TopologyDescription(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "TopologyDescription", class_MongoDB_Driver_TopologyDescription_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
zval const_TYPE_UNKNOWN_value;
zend_string *const_TYPE_UNKNOWN_value_str = zend_string_init(PHONGO_TOPOLOGY_UNKNOWN, strlen(PHONGO_TOPOLOGY_UNKNOWN), 1);
ZVAL_STR(&const_TYPE_UNKNOWN_value, const_TYPE_UNKNOWN_value_str);
zend_string *const_TYPE_UNKNOWN_name = zend_string_init_interned("TYPE_UNKNOWN", sizeof("TYPE_UNKNOWN") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_UNKNOWN_name, &const_TYPE_UNKNOWN_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_UNKNOWN_name);
zval const_TYPE_SINGLE_value;
zend_string *const_TYPE_SINGLE_value_str = zend_string_init(PHONGO_TOPOLOGY_SINGLE, strlen(PHONGO_TOPOLOGY_SINGLE), 1);
ZVAL_STR(&const_TYPE_SINGLE_value, const_TYPE_SINGLE_value_str);
zend_string *const_TYPE_SINGLE_name = zend_string_init_interned("TYPE_SINGLE", sizeof("TYPE_SINGLE") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_SINGLE_name, &const_TYPE_SINGLE_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_SINGLE_name);
zval const_TYPE_SHARDED_value;
zend_string *const_TYPE_SHARDED_value_str = zend_string_init(PHONGO_TOPOLOGY_SHARDED, strlen(PHONGO_TOPOLOGY_SHARDED), 1);
ZVAL_STR(&const_TYPE_SHARDED_value, const_TYPE_SHARDED_value_str);
zend_string *const_TYPE_SHARDED_name = zend_string_init_interned("TYPE_SHARDED", sizeof("TYPE_SHARDED") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_SHARDED_name, &const_TYPE_SHARDED_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_SHARDED_name);
zval const_TYPE_REPLICA_SET_NO_PRIMARY_value;
zend_string *const_TYPE_REPLICA_SET_NO_PRIMARY_value_str = zend_string_init(PHONGO_TOPOLOGY_REPLICA_SET_NO_PRIMARY, strlen(PHONGO_TOPOLOGY_REPLICA_SET_NO_PRIMARY), 1);
ZVAL_STR(&const_TYPE_REPLICA_SET_NO_PRIMARY_value, const_TYPE_REPLICA_SET_NO_PRIMARY_value_str);
zend_string *const_TYPE_REPLICA_SET_NO_PRIMARY_name = zend_string_init_interned("TYPE_REPLICA_SET_NO_PRIMARY", sizeof("TYPE_REPLICA_SET_NO_PRIMARY") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_REPLICA_SET_NO_PRIMARY_name, &const_TYPE_REPLICA_SET_NO_PRIMARY_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_REPLICA_SET_NO_PRIMARY_name);
zval const_TYPE_REPLICA_SET_WITH_PRIMARY_value;
zend_string *const_TYPE_REPLICA_SET_WITH_PRIMARY_value_str = zend_string_init(PHONGO_TOPOLOGY_REPLICA_SET_WITH_PRIMARY, strlen(PHONGO_TOPOLOGY_REPLICA_SET_WITH_PRIMARY), 1);
ZVAL_STR(&const_TYPE_REPLICA_SET_WITH_PRIMARY_value, const_TYPE_REPLICA_SET_WITH_PRIMARY_value_str);
zend_string *const_TYPE_REPLICA_SET_WITH_PRIMARY_name = zend_string_init_interned("TYPE_REPLICA_SET_WITH_PRIMARY", sizeof("TYPE_REPLICA_SET_WITH_PRIMARY") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_REPLICA_SET_WITH_PRIMARY_name, &const_TYPE_REPLICA_SET_WITH_PRIMARY_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_REPLICA_SET_WITH_PRIMARY_name);
zval const_TYPE_LOAD_BALANCED_value;
zend_string *const_TYPE_LOAD_BALANCED_value_str = zend_string_init(PHONGO_TOPOLOGY_LOAD_BALANCED, strlen(PHONGO_TOPOLOGY_LOAD_BALANCED), 1);
ZVAL_STR(&const_TYPE_LOAD_BALANCED_value, const_TYPE_LOAD_BALANCED_value_str);
zend_string *const_TYPE_LOAD_BALANCED_name = zend_string_init_interned("TYPE_LOAD_BALANCED", sizeof("TYPE_LOAD_BALANCED") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_LOAD_BALANCED_name, &const_TYPE_LOAD_BALANCED_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_LOAD_BALANCED_name);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/WriteConcern.c 0000644 0001751 0000166 00000035304 15014033047 014704 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "mongoc/mongoc.h"
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "phongo_util.h"
#include "MongoDB/WriteConcern.h"
#include "WriteConcern_arginfo.h"
zend_class_entry* php_phongo_writeconcern_ce;
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool php_phongo_writeconcern_init_from_hash(php_phongo_writeconcern_t* intern, HashTable* props)
{
zval *w, *wtimeout, *j;
intern->write_concern = mongoc_write_concern_new();
if ((w = zend_hash_str_find(props, "w", sizeof("w") - 1))) {
if (Z_TYPE_P(w) == IS_LONG) {
if (Z_LVAL_P(w) < -3) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"w\" integer field to be >= -3", ZSTR_VAL(php_phongo_writeconcern_ce->name));
goto failure;
}
mongoc_write_concern_set_w(intern->write_concern, Z_LVAL_P(w));
} else if (Z_TYPE_P(w) == IS_STRING) {
if (strcmp(Z_STRVAL_P(w), PHONGO_WRITE_CONCERN_W_MAJORITY) == 0) {
mongoc_write_concern_set_w(intern->write_concern, MONGOC_WRITE_CONCERN_W_MAJORITY);
} else {
mongoc_write_concern_set_wtag(intern->write_concern, Z_STRVAL_P(w));
}
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"w\" field to be integer or string", ZSTR_VAL(php_phongo_writeconcern_ce->name));
goto failure;
}
}
if ((wtimeout = zend_hash_str_find(props, "wtimeout", sizeof("wtimeout") - 1))) {
if (Z_TYPE_P(wtimeout) == IS_LONG) {
if (Z_LVAL_P(wtimeout) < 0) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"wtimeout\" integer field to be >= 0", ZSTR_VAL(php_phongo_writeconcern_ce->name));
goto failure;
}
mongoc_write_concern_set_wtimeout_int64(intern->write_concern, (int64_t) Z_LVAL_P(wtimeout));
} else if (Z_TYPE_P(wtimeout) == IS_STRING) {
int64_t timeout;
if (!php_phongo_parse_int64(&timeout, Z_STRVAL_P(wtimeout), Z_STRLEN_P(wtimeout))) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Error parsing \"%s\" as 64-bit value for %s initialization", Z_STRVAL_P(wtimeout), ZSTR_VAL(php_phongo_writeconcern_ce->name));
return false;
}
mongoc_write_concern_set_wtimeout_int64(intern->write_concern, timeout);
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"wtimeout\" field to be integer or string", ZSTR_VAL(php_phongo_writeconcern_ce->name));
goto failure;
}
}
if ((j = zend_hash_str_find(props, "j", sizeof("j") - 1))) {
if (Z_TYPE_P(j) == IS_TRUE || Z_TYPE_P(j) == IS_FALSE) {
if (zend_is_true(j) && (mongoc_write_concern_get_w(intern->write_concern) == MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED || mongoc_write_concern_get_w(intern->write_concern) == MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Cannot enable journaling when using w = 0");
goto failure;
}
mongoc_write_concern_set_journal(intern->write_concern, zend_is_true(j));
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"j\" field to be boolean", ZSTR_VAL(php_phongo_writeconcern_ce->name));
goto failure;
}
}
if (!mongoc_write_concern_is_valid(intern->write_concern)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Write concern is not valid");
goto failure;
}
return true;
failure:
mongoc_write_concern_destroy(intern->write_concern);
intern->write_concern = NULL;
return false;
}
/* Constructs a new WriteConcern */
static PHP_METHOD(MongoDB_Driver_WriteConcern, __construct)
{
php_phongo_writeconcern_t* intern;
zval * w, *journal = NULL;
zend_long wtimeout = 0;
intern = Z_WRITECONCERN_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_START(1, 3)
Z_PARAM_ZVAL(w)
Z_PARAM_OPTIONAL
Z_PARAM_LONG(wtimeout)
Z_PARAM_ZVAL(journal)
PHONGO_PARSE_PARAMETERS_END();
intern->write_concern = mongoc_write_concern_new();
if (Z_TYPE_P(w) == IS_LONG) {
if (Z_LVAL_P(w) < -3) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected w to be >= -3, %ld given", Z_LVAL_P(w));
return;
}
mongoc_write_concern_set_w(intern->write_concern, Z_LVAL_P(w));
} else if (Z_TYPE_P(w) == IS_STRING) {
if (strcmp(Z_STRVAL_P(w), PHONGO_WRITE_CONCERN_W_MAJORITY) == 0) {
mongoc_write_concern_set_w(intern->write_concern, MONGOC_WRITE_CONCERN_W_MAJORITY);
} else {
mongoc_write_concern_set_wtag(intern->write_concern, Z_STRVAL_P(w));
}
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected w to be integer or string, %s given", zend_zval_type_name(w));
return;
}
switch (ZEND_NUM_ARGS()) {
case 3:
if (journal && Z_TYPE_P(journal) != IS_NULL) {
if (zend_is_true(journal) && (mongoc_write_concern_get_w(intern->write_concern) == MONGOC_WRITE_CONCERN_W_UNACKNOWLEDGED || mongoc_write_concern_get_w(intern->write_concern) == MONGOC_WRITE_CONCERN_W_ERRORS_IGNORED)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Cannot enable journaling when using w = 0");
return;
}
mongoc_write_concern_set_journal(intern->write_concern, zend_is_true(journal));
}
PHONGO_BREAK_INTENTIONALLY_MISSING
case 2:
if (wtimeout < 0) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected wtimeout to be >= 0, %" PHONGO_LONG_FORMAT " given", wtimeout);
return;
}
mongoc_write_concern_set_wtimeout_int64(intern->write_concern, (int64_t) wtimeout);
}
if (!mongoc_write_concern_is_valid(intern->write_concern)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Write concern is not valid");
return;
}
}
static PHP_METHOD(MongoDB_Driver_WriteConcern, __set_state)
{
php_phongo_writeconcern_t* intern;
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
object_init_ex(return_value, php_phongo_writeconcern_ce);
intern = Z_WRITECONCERN_OBJ_P(return_value);
props = Z_ARRVAL_P(array);
php_phongo_writeconcern_init_from_hash(intern, props);
}
/* Returns the WriteConcern "w" option */
static PHP_METHOD(MongoDB_Driver_WriteConcern, getW)
{
php_phongo_writeconcern_t* intern;
const char* wtag;
intern = Z_WRITECONCERN_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
wtag = mongoc_write_concern_get_wtag(intern->write_concern);
if (wtag) {
RETURN_STRING(wtag);
}
if (mongoc_write_concern_get_wmajority(intern->write_concern)) {
RETURN_STRING(PHONGO_WRITE_CONCERN_W_MAJORITY);
}
if (mongoc_write_concern_get_w(intern->write_concern) != MONGOC_WRITE_CONCERN_W_DEFAULT) {
RETURN_LONG(mongoc_write_concern_get_w(intern->write_concern));
}
RETURN_NULL();
}
/* Returns the WriteConcern "wtimeout" option */
static PHP_METHOD(MongoDB_Driver_WriteConcern, getWtimeout)
{
php_phongo_writeconcern_t* intern;
int64_t wtimeout;
intern = Z_WRITECONCERN_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
wtimeout = mongoc_write_concern_get_wtimeout_int64(intern->write_concern);
#if SIZEOF_ZEND_LONG == 4
if (wtimeout > INT32_MAX || wtimeout < INT32_MIN) {
zend_error(E_WARNING, "Truncating 64-bit value for wTimeoutMS");
}
#endif
RETURN_LONG(wtimeout);
}
/* Returns the WriteConcern "journal" option */
static PHP_METHOD(MongoDB_Driver_WriteConcern, getJournal)
{
php_phongo_writeconcern_t* intern;
intern = Z_WRITECONCERN_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
if (mongoc_write_concern_journal_is_set(intern->write_concern)) {
RETURN_BOOL(mongoc_write_concern_get_journal(intern->write_concern));
}
RETURN_NULL();
}
/* Returns whether the write concern has not been modified (i.e. from a Manager
with no write concern URI options). */
static PHP_METHOD(MongoDB_Driver_WriteConcern, isDefault)
{
php_phongo_writeconcern_t* intern;
intern = Z_WRITECONCERN_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_BOOL(mongoc_write_concern_is_default(intern->write_concern));
}
static HashTable* php_phongo_writeconcern_get_properties_hash(zend_object* object, bool is_temp, bool is_bson, bool is_serialize)
{
php_phongo_writeconcern_t* intern;
HashTable* props;
const char* wtag;
int32_t w;
int64_t wtimeout;
intern = Z_OBJ_WRITECONCERN(object);
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_temp, intern, props, 4);
if (!intern->write_concern) {
return props;
}
wtag = mongoc_write_concern_get_wtag(intern->write_concern);
w = mongoc_write_concern_get_w(intern->write_concern);
wtimeout = mongoc_write_concern_get_wtimeout_int64(intern->write_concern);
{
zval z_w;
if (wtag) {
ZVAL_STRING(&z_w, wtag);
zend_hash_str_update(props, "w", sizeof("w") - 1, &z_w);
} else if (mongoc_write_concern_get_wmajority(intern->write_concern)) {
ZVAL_STRING(&z_w, PHONGO_WRITE_CONCERN_W_MAJORITY);
zend_hash_str_update(props, "w", sizeof("w") - 1, &z_w);
} else if (w != MONGOC_WRITE_CONCERN_W_DEFAULT) {
ZVAL_LONG(&z_w, w);
zend_hash_str_update(props, "w", sizeof("w") - 1, &z_w);
}
if (mongoc_write_concern_journal_is_set(intern->write_concern)) {
zval z_j;
ZVAL_BOOL(&z_j, mongoc_write_concern_get_journal(intern->write_concern));
zend_hash_str_update(props, "j", sizeof("j") - 1, &z_j);
}
if (wtimeout != 0) {
zval z_wtimeout;
if (is_bson) {
ZVAL_INT64(&z_wtimeout, wtimeout);
} else if (is_serialize) {
if (wtimeout > INT32_MAX || wtimeout < INT32_MIN) {
ZVAL_INT64_STRING(&z_wtimeout, wtimeout);
} else {
ZVAL_LONG(&z_wtimeout, wtimeout);
}
} else {
#if SIZEOF_ZEND_LONG == 4
if (wtimeout > INT32_MAX || wtimeout < INT32_MIN) {
ZVAL_INT64_STRING(&z_wtimeout, wtimeout);
} else {
ZVAL_LONG(&z_wtimeout, wtimeout);
}
#else
ZVAL_LONG(&z_wtimeout, wtimeout);
#endif
}
zend_hash_str_update(props, "wtimeout", sizeof("wtimeout") - 1, &z_wtimeout);
}
}
return props;
}
static PHP_METHOD(MongoDB_Driver_WriteConcern, bsonSerialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
ZVAL_ARR(return_value, php_phongo_writeconcern_get_properties_hash(Z_OBJ_P(getThis()), true, true, false));
convert_to_object(return_value);
}
static PHP_METHOD(MongoDB_Driver_WriteConcern, __serialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_ARR(php_phongo_writeconcern_get_properties_hash(Z_OBJ_P(getThis()), true, false, true));
}
static PHP_METHOD(MongoDB_Driver_WriteConcern, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
php_phongo_writeconcern_init_from_hash(Z_WRITECONCERN_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\Driver\WriteConcern object handlers */
static zend_object_handlers php_phongo_handler_writeconcern;
static void php_phongo_writeconcern_free_object(zend_object* object)
{
php_phongo_writeconcern_t* intern = Z_OBJ_WRITECONCERN(object);
zend_object_std_dtor(&intern->std);
if (intern->properties) {
zend_hash_destroy(intern->properties);
FREE_HASHTABLE(intern->properties);
}
if (intern->write_concern) {
mongoc_write_concern_destroy(intern->write_concern);
}
}
static zend_object* php_phongo_writeconcern_create_object(zend_class_entry* class_type)
{
php_phongo_writeconcern_t* intern = zend_object_alloc(sizeof(php_phongo_writeconcern_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_writeconcern;
return &intern->std;
}
static HashTable* php_phongo_writeconcern_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return php_phongo_writeconcern_get_properties_hash(object, true, false, false);
}
static HashTable* php_phongo_writeconcern_get_properties(zend_object* object)
{
return php_phongo_writeconcern_get_properties_hash(object, false, false, false);
}
void php_phongo_writeconcern_init_ce(INIT_FUNC_ARGS)
{
php_phongo_writeconcern_ce = register_class_MongoDB_Driver_WriteConcern(php_phongo_serializable_ce);
php_phongo_writeconcern_ce->create_object = php_phongo_writeconcern_create_object;
memcpy(&php_phongo_handler_writeconcern, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_writeconcern.get_debug_info = php_phongo_writeconcern_get_debug_info;
php_phongo_handler_writeconcern.get_properties = php_phongo_writeconcern_get_properties;
php_phongo_handler_writeconcern.free_obj = php_phongo_writeconcern_free_object;
php_phongo_handler_writeconcern.offset = XtOffsetOf(php_phongo_writeconcern_t, std);
}
void phongo_writeconcern_init(zval* return_value, const mongoc_write_concern_t* write_concern)
{
php_phongo_writeconcern_t* intern;
object_init_ex(return_value, php_phongo_writeconcern_ce);
intern = Z_WRITECONCERN_OBJ_P(return_value);
intern->write_concern = mongoc_write_concern_copy(write_concern);
}
const mongoc_write_concern_t* phongo_write_concern_from_zval(zval* zwrite_concern)
{
if (zwrite_concern) {
php_phongo_writeconcern_t* intern = Z_WRITECONCERN_OBJ_P(zwrite_concern);
if (intern) {
return intern->write_concern;
}
}
return NULL;
}
void php_phongo_write_concern_to_zval(zval* retval, const mongoc_write_concern_t* write_concern)
{
const char* wtag = mongoc_write_concern_get_wtag(write_concern);
const int32_t w = mongoc_write_concern_get_w(write_concern);
const int64_t wtimeout = mongoc_write_concern_get_wtimeout_int64(write_concern);
array_init_size(retval, 4);
if (wtag) {
ADD_ASSOC_STRING(retval, "w", wtag);
} else if (mongoc_write_concern_get_wmajority(write_concern)) {
ADD_ASSOC_STRING(retval, "w", PHONGO_WRITE_CONCERN_W_MAJORITY);
} else if (w != MONGOC_WRITE_CONCERN_W_DEFAULT) {
ADD_ASSOC_LONG_EX(retval, "w", w);
}
if (mongoc_write_concern_journal_is_set(write_concern)) {
ADD_ASSOC_BOOL_EX(retval, "j", mongoc_write_concern_get_journal(write_concern));
}
if (wtimeout != 0) {
#if SIZEOF_ZEND_LONG == 4
if (wtimeout > INT32_MAX || wtimeout < INT32_MIN) {
ADD_ASSOC_INT64_AS_STRING(retval, "wtimeout", wtimeout);
} else {
ADD_ASSOC_LONG_EX(retval, "wtimeout", wtimeout);
}
#else
ADD_ASSOC_LONG_EX(retval, "wtimeout", wtimeout);
#endif
}
}
mongodb-2.1.0/src/MongoDB/WriteConcern.h 0000644 0001751 0000166 00000002067 15014033047 014711 0 ustar /*
* Copyright 2022-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_WRITECONCERN_H
#define PHONGO_WRITECONCERN_H
#include "mongoc/mongoc.h"
#include
#define PHONGO_WRITE_CONCERN_W_MAJORITY "majority"
void phongo_writeconcern_init(zval* return_value, const mongoc_write_concern_t* write_concern);
const mongoc_write_concern_t* phongo_write_concern_from_zval(zval* zwrite_concern);
void php_phongo_write_concern_to_zval(zval* retval, const mongoc_write_concern_t* write_concern);
#endif /* PHONGO_WRITECONCERN_H */
mongodb-2.1.0/src/MongoDB/WriteConcernError.c 0000644 0001751 0000166 00000012706 15014033047 015717 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bson/bson.h"
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "MongoDB/WriteConcernError.h"
#include "WriteConcernError_arginfo.h"
zend_class_entry* php_phongo_writeconcernerror_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_WriteConcernError)
/* Returns the MongoDB error code */
static PHP_METHOD(MongoDB_Driver_WriteConcernError, getCode)
{
php_phongo_writeconcernerror_t* intern;
intern = Z_WRITECONCERNERROR_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_LONG(intern->code);
}
/* Returns additional metadata for the error */
static PHP_METHOD(MongoDB_Driver_WriteConcernError, getInfo)
{
php_phongo_writeconcernerror_t* intern;
intern = Z_WRITECONCERNERROR_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
if (!Z_ISUNDEF(intern->info)) {
RETURN_ZVAL(&intern->info, 1, 0);
}
}
/* Returns the actual error message from the server */
static PHP_METHOD(MongoDB_Driver_WriteConcernError, getMessage)
{
php_phongo_writeconcernerror_t* intern;
intern = Z_WRITECONCERNERROR_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
if (!intern->message) {
RETURN_STRING("");
}
RETURN_STRING(intern->message);
}
/* MongoDB\Driver\WriteConcernError object handlers */
static zend_object_handlers php_phongo_handler_writeconcernerror;
static void php_phongo_writeconcernerror_free_object(zend_object* object)
{
php_phongo_writeconcernerror_t* intern = Z_OBJ_WRITECONCERNERROR(object);
zend_object_std_dtor(&intern->std);
if (intern->message) {
efree(intern->message);
}
if (!Z_ISUNDEF(intern->info)) {
zval_ptr_dtor(&intern->info);
}
}
static zend_object* php_phongo_writeconcernerror_create_object(zend_class_entry* class_type)
{
php_phongo_writeconcernerror_t* intern = zend_object_alloc(sizeof(php_phongo_writeconcernerror_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_writeconcernerror;
return &intern->std;
}
static HashTable* php_phongo_writeconcernerror_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_writeconcernerror_t* intern;
zval retval = ZVAL_STATIC_INIT;
*is_temp = 1;
intern = Z_OBJ_WRITECONCERNERROR(object);
array_init_size(&retval, 3);
ADD_ASSOC_STRING(&retval, "message", intern->message ? intern->message : "");
ADD_ASSOC_LONG_EX(&retval, "code", intern->code);
if (!Z_ISUNDEF(intern->info)) {
Z_ADDREF(intern->info);
ADD_ASSOC_ZVAL_EX(&retval, "info", &intern->info);
} else {
ADD_ASSOC_NULL_EX(&retval, "info");
}
return Z_ARRVAL(retval);
}
void php_phongo_writeconcernerror_init_ce(INIT_FUNC_ARGS)
{
php_phongo_writeconcernerror_ce = register_class_MongoDB_Driver_WriteConcernError();
php_phongo_writeconcernerror_ce->create_object = php_phongo_writeconcernerror_create_object;
memcpy(&php_phongo_handler_writeconcernerror, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_writeconcernerror.get_debug_info = php_phongo_writeconcernerror_get_debug_info;
php_phongo_handler_writeconcernerror.free_obj = php_phongo_writeconcernerror_free_object;
php_phongo_handler_writeconcernerror.offset = XtOffsetOf(php_phongo_writeconcernerror_t, std);
}
/* Initializes a new WriteConcernError in return_value using the BSON document.
* Returns true on success; otherwise, false is returned and an exception is
* thrown.
*
* This function supports documents from both mongoc_bulk_operation_execute and
* mongoc_bulkwriteexception_t (returned by mongoc_bulkwrite_execute). */
bool phongo_writeconcernerror_init(zval* return_value, const bson_t* bson)
{
bson_iter_t iter;
php_phongo_writeconcernerror_t* intern;
object_init_ex(return_value, php_phongo_writeconcernerror_ce);
intern = Z_WRITECONCERNERROR_OBJ_P(return_value);
intern->code = 0;
if (bson_iter_init_find(&iter, bson, "code") && BSON_ITER_HOLDS_INT32(&iter)) {
intern->code = bson_iter_int32(&iter);
}
// Additionally check for field name used by mongoc_bulkwriteexception_t
if ((bson_iter_init_find(&iter, bson, "errmsg") && BSON_ITER_HOLDS_UTF8(&iter)) ||
(bson_iter_init_find(&iter, bson, "message") && BSON_ITER_HOLDS_UTF8(&iter))) {
uint32_t len;
const char* message = bson_iter_utf8(&iter, &len);
intern->message = estrndup(message, len);
}
// Additionally check for field name used by mongoc_bulkwriteexception_t
if ((bson_iter_init_find(&iter, bson, "errInfo") && BSON_ITER_HOLDS_DOCUMENT(&iter)) ||
(bson_iter_init_find(&iter, bson, "details") && BSON_ITER_HOLDS_DOCUMENT(&iter))) {
uint32_t len;
const uint8_t* data = NULL;
bson_iter_document(&iter, &len, &data);
if (!php_phongo_bson_data_to_zval(data, len, &intern->info)) {
zval_ptr_dtor(&intern->info);
ZVAL_UNDEF(&intern->info);
return false;
}
}
return true;
}
mongodb-2.1.0/src/MongoDB/WriteConcernError.h 0000644 0001751 0000166 00000001502 15014033047 015714 0 ustar /*
* Copyright 2022-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_WRITECONCERNERROR_H
#define PHONGO_WRITECONCERNERROR_H
#include "bson/bson.h"
#include
bool phongo_writeconcernerror_init(zval* return_value, const bson_t* bson);
#endif /* PHONGO_WRITECONCERNERROR_H */
mongodb-2.1.0/src/MongoDB/WriteConcernError_arginfo.h 0000644 0001751 0000166 00000003661 15014033047 017431 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: a405afbb8eaa3bf544759f7a6ae9330ced7e7cc0 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_WriteConcernError___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_WriteConcernError_getCode, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_WriteConcernError_getInfo, 0, 0, IS_OBJECT, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_WriteConcernError_getMessage, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_WriteConcernError, __construct);
static ZEND_METHOD(MongoDB_Driver_WriteConcernError, getCode);
static ZEND_METHOD(MongoDB_Driver_WriteConcernError, getInfo);
static ZEND_METHOD(MongoDB_Driver_WriteConcernError, getMessage);
static const zend_function_entry class_MongoDB_Driver_WriteConcernError_methods[] = {
ZEND_ME(MongoDB_Driver_WriteConcernError, __construct, arginfo_class_MongoDB_Driver_WriteConcernError___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteConcernError, getCode, arginfo_class_MongoDB_Driver_WriteConcernError_getCode, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteConcernError, getInfo, arginfo_class_MongoDB_Driver_WriteConcernError_getInfo, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteConcernError, getMessage, arginfo_class_MongoDB_Driver_WriteConcernError_getMessage, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_WriteConcernError(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "WriteConcernError", class_MongoDB_Driver_WriteConcernError_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
mongodb-2.1.0/src/MongoDB/WriteConcern_arginfo.h 0000644 0001751 0000166 00000010615 15014033047 016414 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 1a859d43ebd260284aff6114b169cbe70869ae61 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_WriteConcern___construct, 0, 0, 1)
ZEND_ARG_TYPE_MASK(0, w, MAY_BE_STRING|MAY_BE_LONG, NULL)
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, wtimeout, IS_LONG, 1, "null")
ZEND_ARG_TYPE_INFO_WITH_DEFAULT_VALUE(0, journal, _IS_BOOL, 1, "null")
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_WriteConcern_getJournal, 0, 0, _IS_BOOL, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_MASK_EX(arginfo_class_MongoDB_Driver_WriteConcern_getW, 0, 0, MAY_BE_STRING|MAY_BE_LONG|MAY_BE_NULL)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_WriteConcern_getWtimeout, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_WriteConcern_isDefault, 0, 0, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_WriteConcern___set_state, 0, 1, MongoDB\\Driver\\WriteConcern, 0)
ZEND_ARG_TYPE_INFO(0, properties, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_WriteConcern_bsonSerialize, 0, 0, stdClass, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_WriteConcern___unserialize, 0, 1, IS_VOID, 0)
ZEND_ARG_TYPE_INFO(0, data, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_WriteConcern___serialize, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_WriteConcern, __construct);
static ZEND_METHOD(MongoDB_Driver_WriteConcern, getJournal);
static ZEND_METHOD(MongoDB_Driver_WriteConcern, getW);
static ZEND_METHOD(MongoDB_Driver_WriteConcern, getWtimeout);
static ZEND_METHOD(MongoDB_Driver_WriteConcern, isDefault);
static ZEND_METHOD(MongoDB_Driver_WriteConcern, __set_state);
static ZEND_METHOD(MongoDB_Driver_WriteConcern, bsonSerialize);
static ZEND_METHOD(MongoDB_Driver_WriteConcern, __unserialize);
static ZEND_METHOD(MongoDB_Driver_WriteConcern, __serialize);
static const zend_function_entry class_MongoDB_Driver_WriteConcern_methods[] = {
ZEND_ME(MongoDB_Driver_WriteConcern, __construct, arginfo_class_MongoDB_Driver_WriteConcern___construct, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteConcern, getJournal, arginfo_class_MongoDB_Driver_WriteConcern_getJournal, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteConcern, getW, arginfo_class_MongoDB_Driver_WriteConcern_getW, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteConcern, getWtimeout, arginfo_class_MongoDB_Driver_WriteConcern_getWtimeout, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteConcern, isDefault, arginfo_class_MongoDB_Driver_WriteConcern_isDefault, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteConcern, __set_state, arginfo_class_MongoDB_Driver_WriteConcern___set_state, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteConcern, bsonSerialize, arginfo_class_MongoDB_Driver_WriteConcern_bsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteConcern, __unserialize, arginfo_class_MongoDB_Driver_WriteConcern___unserialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteConcern, __serialize, arginfo_class_MongoDB_Driver_WriteConcern___serialize, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_WriteConcern(zend_class_entry *class_entry_MongoDB_BSON_Serializable)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "WriteConcern", class_MongoDB_Driver_WriteConcern_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
zend_class_implements(class_entry, 1, class_entry_MongoDB_BSON_Serializable);
zval const_MAJORITY_value;
zend_string *const_MAJORITY_value_str = zend_string_init(PHONGO_WRITE_CONCERN_W_MAJORITY, strlen(PHONGO_WRITE_CONCERN_W_MAJORITY), 1);
ZVAL_STR(&const_MAJORITY_value, const_MAJORITY_value_str);
zend_string *const_MAJORITY_name = zend_string_init_interned("MAJORITY", sizeof("MAJORITY") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_MAJORITY_name, &const_MAJORITY_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_MAJORITY_name);
return class_entry;
}
mongodb-2.1.0/src/MongoDB/WriteError.c 0000644 0001751 0000166 00000014062 15014033047 014404 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bson/bson.h"
#include
#include
#include "php_phongo.h"
#include "phongo_error.h"
#include "MongoDB/WriteError.h"
#include "WriteError_arginfo.h"
zend_class_entry* php_phongo_writeerror_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_WriteError)
/* Returns the MongoDB error code */
static PHP_METHOD(MongoDB_Driver_WriteError, getCode)
{
php_phongo_writeerror_t* intern;
intern = Z_WRITEERROR_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_LONG(intern->code);
}
/* Returns the index of the operation in the BulkWrite to which this WriteError
corresponds. */
static PHP_METHOD(MongoDB_Driver_WriteError, getIndex)
{
php_phongo_writeerror_t* intern;
intern = Z_WRITEERROR_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_LONG(intern->index);
}
/* Returns the actual error message from the server */
static PHP_METHOD(MongoDB_Driver_WriteError, getMessage)
{
php_phongo_writeerror_t* intern;
intern = Z_WRITEERROR_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_STRING(intern->message);
}
/* Returns additional metadata for the error */
static PHP_METHOD(MongoDB_Driver_WriteError, getInfo)
{
php_phongo_writeerror_t* intern;
intern = Z_WRITEERROR_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
if (!Z_ISUNDEF(intern->info)) {
RETURN_ZVAL(&intern->info, 1, 0);
}
}
/* MongoDB\Driver\WriteError object handlers */
static zend_object_handlers php_phongo_handler_writeerror;
static void php_phongo_writeerror_free_object(zend_object* object)
{
php_phongo_writeerror_t* intern = Z_OBJ_WRITEERROR(object);
zend_object_std_dtor(&intern->std);
if (intern->message) {
efree(intern->message);
}
if (!Z_ISUNDEF(intern->info)) {
zval_ptr_dtor(&intern->info);
}
}
static zend_object* php_phongo_writeerror_create_object(zend_class_entry* class_type)
{
php_phongo_writeerror_t* intern = zend_object_alloc(sizeof(php_phongo_writeerror_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_writeerror;
return &intern->std;
}
static HashTable* php_phongo_writeerror_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_writeerror_t* intern;
zval retval = ZVAL_STATIC_INIT;
*is_temp = 1;
intern = Z_OBJ_WRITEERROR(object);
array_init_size(&retval, 3);
ADD_ASSOC_STRING(&retval, "message", intern->message);
ADD_ASSOC_LONG_EX(&retval, "code", intern->code);
ADD_ASSOC_LONG_EX(&retval, "index", intern->index);
if (!Z_ISUNDEF(intern->info)) {
Z_ADDREF(intern->info);
ADD_ASSOC_ZVAL_EX(&retval, "info", &intern->info);
} else {
ADD_ASSOC_NULL_EX(&retval, "info");
}
return Z_ARRVAL(retval);
}
void php_phongo_writeerror_init_ce(INIT_FUNC_ARGS)
{
php_phongo_writeerror_ce = register_class_MongoDB_Driver_WriteError();
php_phongo_writeerror_ce->create_object = php_phongo_writeerror_create_object;
memcpy(&php_phongo_handler_writeerror, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_writeerror.get_debug_info = php_phongo_writeerror_get_debug_info;
php_phongo_handler_writeerror.free_obj = php_phongo_writeerror_free_object;
php_phongo_handler_writeerror.offset = XtOffsetOf(php_phongo_writeerror_t, std);
}
bool phongo_writeerror_init(zval* return_value, const bson_t* bson)
{
return phongo_writeerror_init_ex(return_value, bson, 0);
}
/* Initializes a new WriteError in return_value using the BSON document. Returns
* true on success; otherwise, false is returned and an exception is thrown.
*
* This function supports documents from both mongoc_bulk_operation_execute and
* mongoc_bulkwriteexception_t (returned by mongoc_bulkwrite_execute). When
* initializing from mongoc_bulkwriteexception_t, an index should be explicitly
* provided since the BSON document will not have an "index" field. */
bool phongo_writeerror_init_ex(zval* return_value, const bson_t* bson, int32_t index)
{
bson_iter_t iter;
php_phongo_writeerror_t* intern;
object_init_ex(return_value, php_phongo_writeerror_ce);
intern = Z_WRITEERROR_OBJ_P(return_value);
intern->code = 0;
intern->index = index;
if (bson_iter_init_find(&iter, bson, "code") && BSON_ITER_HOLDS_INT32(&iter)) {
intern->code = bson_iter_int32(&iter);
}
// Additionally check for field name used by mongoc_bulkwriteexception_t
if ((bson_iter_init_find(&iter, bson, "errmsg") && BSON_ITER_HOLDS_UTF8(&iter)) ||
(bson_iter_init_find(&iter, bson, "message") && BSON_ITER_HOLDS_UTF8(&iter))) {
uint32_t errmsg_len;
const char* err_msg = bson_iter_utf8(&iter, &errmsg_len);
intern->message = estrndup(err_msg, errmsg_len);
}
// Additionally check for field name used by mongoc_bulkwriteexception_t
if ((bson_iter_init_find(&iter, bson, "errInfo") && BSON_ITER_HOLDS_DOCUMENT(&iter)) ||
(bson_iter_init_find(&iter, bson, "details") && BSON_ITER_HOLDS_DOCUMENT(&iter))) {
uint32_t len;
const uint8_t* data = NULL;
bson_iter_document(&iter, &len, &data);
if (!php_phongo_bson_data_to_zval(data, len, &intern->info)) {
/* Exception already thrown */
zval_ptr_dtor(&intern->info);
ZVAL_UNDEF(&intern->info);
return false;
}
}
/* If the WriteError is initialized from mongoc_bulkwriteexception_t, an
* index should already have been specified. */
if (!intern->index && bson_iter_init_find(&iter, bson, "index") && BSON_ITER_HOLDS_INT32(&iter)) {
intern->index = bson_iter_int32(&iter);
}
return true;
}
mongodb-2.1.0/src/MongoDB/WriteError.h 0000644 0001751 0000166 00000001575 15014033047 014416 0 ustar /*
* Copyright 2022-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_WRITEERROR_H
#define PHONGO_WRITEERROR_H
#include "bson/bson.h"
#include
bool phongo_writeerror_init(zval* return_value, const bson_t* bson);
bool phongo_writeerror_init_ex(zval* return_value, const bson_t* bson, int32_t index);
#endif /* PHONGO_WRITEERROR_H */
mongodb-2.1.0/src/MongoDB/WriteError_arginfo.h 0000644 0001751 0000166 00000004110 15014033047 016107 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 8f9ebc299c90e86c6a55ea39e02d5a1734d10402 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_WriteError___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_WriteError_getCode, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_WriteError_getIndex arginfo_class_MongoDB_Driver_WriteError_getCode
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_WriteError_getInfo, 0, 0, IS_OBJECT, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_WriteError_getMessage, 0, 0, IS_STRING, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_WriteError, __construct);
static ZEND_METHOD(MongoDB_Driver_WriteError, getCode);
static ZEND_METHOD(MongoDB_Driver_WriteError, getIndex);
static ZEND_METHOD(MongoDB_Driver_WriteError, getInfo);
static ZEND_METHOD(MongoDB_Driver_WriteError, getMessage);
static const zend_function_entry class_MongoDB_Driver_WriteError_methods[] = {
ZEND_ME(MongoDB_Driver_WriteError, __construct, arginfo_class_MongoDB_Driver_WriteError___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteError, getCode, arginfo_class_MongoDB_Driver_WriteError_getCode, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteError, getIndex, arginfo_class_MongoDB_Driver_WriteError_getIndex, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteError, getInfo, arginfo_class_MongoDB_Driver_WriteError_getInfo, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteError, getMessage, arginfo_class_MongoDB_Driver_WriteError_getMessage, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_WriteError(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "WriteError", class_MongoDB_Driver_WriteError_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
mongodb-2.1.0/src/MongoDB/WriteResult.c 0000644 0001751 0000166 00000032504 15014033047 014572 0 ustar /*
* Copyright 2014-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "bson/bson.h"
#include "mongoc/mongoc.h"
#include
#include
#include "php_array_api.h"
#include "php_phongo.h"
#include "phongo_error.h"
#include "MongoDB/Server.h"
#include "MongoDB/WriteConcern.h"
#include "MongoDB/WriteConcernError.h"
#include "MongoDB/WriteError.h"
#include "WriteResult_arginfo.h"
#define PHONGO_WRITERESULT_CHECK_ACKNOWLEDGED(method) \
if (!mongoc_write_concern_is_acknowledged(intern->write_concern)) { \
phongo_throw_exception(PHONGO_ERROR_LOGIC, "MongoDB\\Driver\\WriteResult::" method "() should not be called for an unacknowledged write result"); \
}
#define PHONGO_WRITERESULT_RETURN_LONG_FROM_BSON_INT32(iter, bson, key) \
if (bson_iter_init_find((iter), (bson), (key)) && BSON_ITER_HOLDS_INT32((iter))) { \
RETURN_LONG(bson_iter_int32((iter))); \
} \
RETURN_LONG(0);
zend_class_entry* php_phongo_writeresult_ce;
/* Populates return_value with a WriteConcernError object (if available).
* Returns true on success; otherwise, false is returned and an exception is
* thrown. */
static bool phongo_writeresult_get_writeconcernerror(php_phongo_writeresult_t* intern, zval* return_value)
{
bson_iter_t iter, child;
zval writeconcernerror;
ZVAL_NULL(return_value);
if (bson_iter_init_find(&iter, intern->reply, "writeConcernErrors") && BSON_ITER_HOLDS_ARRAY(&iter) && bson_iter_recurse(&iter, &child)) {
while (bson_iter_next(&child)) {
bson_t cbson;
uint32_t len;
const uint8_t* data;
if (!BSON_ITER_HOLDS_DOCUMENT(&child)) {
continue;
}
bson_iter_document(&child, &len, &data);
if (!bson_init_static(&cbson, data, len)) {
continue;
}
if (!phongo_writeconcernerror_init(&writeconcernerror, &cbson)) {
/* Exception already thrown */
zval_ptr_dtor(&writeconcernerror);
return false;
}
ZVAL_ZVAL(return_value, &writeconcernerror, 1, 1);
return true;
}
}
return true;
}
/* Populates return_value with a list of WriteError objects. Returns true on
* success; otherwise, false is returned and an exception is thrown. */
static bool phongo_writeresult_get_writeerrors(php_phongo_writeresult_t* intern, zval* return_value)
{
bson_iter_t iter, child;
array_init(return_value);
if (bson_iter_init_find(&iter, intern->reply, "writeErrors") && BSON_ITER_HOLDS_ARRAY(&iter) && bson_iter_recurse(&iter, &child)) {
while (bson_iter_next(&child)) {
bson_t cbson;
uint32_t len;
const uint8_t* data;
zval writeerror;
if (!BSON_ITER_HOLDS_DOCUMENT(&child)) {
continue;
}
bson_iter_document(&child, &len, &data);
if (!bson_init_static(&cbson, data, len)) {
continue;
}
if (!phongo_writeerror_init(&writeerror, &cbson)) {
/* Exception already thrown */
zval_ptr_dtor(&writeerror);
return false;
}
add_next_index_zval(return_value, &writeerror);
}
}
return true;
}
static bool php_phongo_writeresult_get_error_replies(php_phongo_writeresult_t* intern, zval* return_value)
{
bson_iter_t iter, child;
array_init(return_value);
if (bson_iter_init_find(&iter, intern->reply, "errorReplies") && BSON_ITER_HOLDS_ARRAY(&iter) && bson_iter_recurse(&iter, &child)) {
while (bson_iter_next(&child)) {
uint32_t len;
const uint8_t* data;
zval error_reply;
if (!BSON_ITER_HOLDS_DOCUMENT(&child)) {
continue;
}
bson_iter_document(&child, &len, &data);
php_phongo_bson_data_to_zval(data, len, &error_reply);
add_next_index_zval(return_value, &error_reply);
}
}
return true;
}
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_WriteResult)
/* Returns the number of documents that were inserted */
static PHP_METHOD(MongoDB_Driver_WriteResult, getInsertedCount)
{
bson_iter_t iter;
php_phongo_writeresult_t* intern;
intern = Z_WRITERESULT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
PHONGO_WRITERESULT_CHECK_ACKNOWLEDGED("getInsertedCount");
PHONGO_WRITERESULT_RETURN_LONG_FROM_BSON_INT32(&iter, intern->reply, "nInserted");
}
/* Returns the number of documents that matched the update criteria */
static PHP_METHOD(MongoDB_Driver_WriteResult, getMatchedCount)
{
bson_iter_t iter;
php_phongo_writeresult_t* intern;
intern = Z_WRITERESULT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
PHONGO_WRITERESULT_CHECK_ACKNOWLEDGED("getMatchedCount");
PHONGO_WRITERESULT_RETURN_LONG_FROM_BSON_INT32(&iter, intern->reply, "nMatched");
}
/* Returns the number of documents that were actually modified by an update */
static PHP_METHOD(MongoDB_Driver_WriteResult, getModifiedCount)
{
bson_iter_t iter;
php_phongo_writeresult_t* intern;
intern = Z_WRITERESULT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
PHONGO_WRITERESULT_CHECK_ACKNOWLEDGED("getModifiedCount");
PHONGO_WRITERESULT_RETURN_LONG_FROM_BSON_INT32(&iter, intern->reply, "nModified");
}
/* Returns the number of documents that were deleted */
static PHP_METHOD(MongoDB_Driver_WriteResult, getDeletedCount)
{
bson_iter_t iter;
php_phongo_writeresult_t* intern;
intern = Z_WRITERESULT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
PHONGO_WRITERESULT_CHECK_ACKNOWLEDGED("getDeletedCount");
PHONGO_WRITERESULT_RETURN_LONG_FROM_BSON_INT32(&iter, intern->reply, "nRemoved");
}
/* Returns the number of documents that were upserted */
static PHP_METHOD(MongoDB_Driver_WriteResult, getUpsertedCount)
{
bson_iter_t iter;
php_phongo_writeresult_t* intern;
intern = Z_WRITERESULT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
PHONGO_WRITERESULT_CHECK_ACKNOWLEDGED("getUpsertedCount");
PHONGO_WRITERESULT_RETURN_LONG_FROM_BSON_INT32(&iter, intern->reply, "nUpserted");
}
/* Returns the Server from which the result originated */
static PHP_METHOD(MongoDB_Driver_WriteResult, getServer)
{
php_phongo_writeresult_t* intern;
intern = Z_WRITERESULT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
phongo_server_init(return_value, &intern->manager, intern->server_id);
}
/* Returns the identifiers generated by the server for upsert operations. */
static PHP_METHOD(MongoDB_Driver_WriteResult, getUpsertedIds)
{
bson_iter_t iter, child;
php_phongo_writeresult_t* intern;
intern = Z_WRITERESULT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
PHONGO_WRITERESULT_CHECK_ACKNOWLEDGED("getUpsertedIds");
array_init(return_value);
if (bson_iter_init_find(&iter, intern->reply, "upserted") && BSON_ITER_HOLDS_ARRAY(&iter) && bson_iter_recurse(&iter, &child)) {
while (bson_iter_next(&child)) {
uint32_t data_len;
const uint8_t* data = NULL;
php_phongo_bson_state state;
/* Use PHONGO_TYPEMAP_NATIVE_ARRAY for the root type so we can
* easily access the "index" and "_id" fields. */
PHONGO_BSON_INIT_STATE(state);
state.map.root.type = PHONGO_TYPEMAP_NATIVE_ARRAY;
if (!BSON_ITER_HOLDS_DOCUMENT(&child)) {
continue;
}
bson_iter_document(&child, &data_len, &data);
if (php_phongo_bson_data_to_zval_ex(data, data_len, &state)) {
zval* zid = php_array_fetchc(&state.zchild, "_id");
add_index_zval(return_value, php_array_fetchc_long(&state.zchild, "index"), zid);
zval_add_ref(zid);
}
zval_ptr_dtor(&state.zchild);
}
}
}
/* Return any write concern error that occurred */
static PHP_METHOD(MongoDB_Driver_WriteResult, getWriteConcernError)
{
php_phongo_writeresult_t* intern;
intern = Z_WRITERESULT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
phongo_writeresult_get_writeconcernerror(intern, return_value);
}
/* Returns any write errors that occurred */
static PHP_METHOD(MongoDB_Driver_WriteResult, getWriteErrors)
{
php_phongo_writeresult_t* intern;
intern = Z_WRITERESULT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
phongo_writeresult_get_writeerrors(intern, return_value);
}
static PHP_METHOD(MongoDB_Driver_WriteResult, getErrorReplies)
{
php_phongo_writeresult_t* intern;
intern = Z_WRITERESULT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
php_phongo_writeresult_get_error_replies(intern, return_value);
}
/* Returns whether the write operation was acknowledged (based on the write
concern). */
static PHP_METHOD(MongoDB_Driver_WriteResult, isAcknowledged)
{
php_phongo_writeresult_t* intern;
intern = Z_WRITERESULT_OBJ_P(getThis());
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_BOOL(mongoc_write_concern_is_acknowledged(intern->write_concern));
}
/* MongoDB\Driver\WriteResult object handlers */
static zend_object_handlers php_phongo_handler_writeresult;
static void php_phongo_writeresult_free_object(zend_object* object)
{
php_phongo_writeresult_t* intern = Z_OBJ_WRITERESULT(object);
zend_object_std_dtor(&intern->std);
if (intern->reply) {
bson_destroy(intern->reply);
}
if (intern->write_concern) {
mongoc_write_concern_destroy(intern->write_concern);
}
if (!Z_ISUNDEF(intern->manager)) {
zval_ptr_dtor(&intern->manager);
}
}
static zend_object* php_phongo_writeresult_create_object(zend_class_entry* class_type)
{
php_phongo_writeresult_t* intern = zend_object_alloc(sizeof(php_phongo_writeresult_t), class_type);
zend_object_std_init(&intern->std, class_type);
object_properties_init(&intern->std, class_type);
intern->std.handlers = &php_phongo_handler_writeresult;
return &intern->std;
}
static HashTable* php_phongo_writeresult_get_debug_info(zend_object* object, int* is_temp)
{
php_phongo_writeresult_t* intern;
zval retval = ZVAL_STATIC_INIT;
bson_iter_t iter;
intern = Z_OBJ_WRITERESULT(object);
*is_temp = 1;
array_init_size(&retval, 10);
#define PHONGO_WRITERESULT_SCP(field) \
if (bson_iter_init_find(&iter, intern->reply, (field)) && BSON_ITER_HOLDS_INT32(&iter)) { \
ADD_ASSOC_LONG_EX(&retval, (field), bson_iter_int32(&iter)); \
} else { \
ADD_ASSOC_NULL_EX(&retval, (field)); \
}
PHONGO_WRITERESULT_SCP("nInserted");
PHONGO_WRITERESULT_SCP("nMatched");
PHONGO_WRITERESULT_SCP("nModified");
PHONGO_WRITERESULT_SCP("nRemoved");
PHONGO_WRITERESULT_SCP("nUpserted");
#undef PHONGO_WRITERESULT_SCP
if (bson_iter_init_find(&iter, intern->reply, "upserted") && BSON_ITER_HOLDS_ARRAY(&iter)) {
uint32_t len;
const uint8_t* data;
php_phongo_bson_state state;
PHONGO_BSON_INIT_DEBUG_STATE(state);
bson_iter_array(&iter, &len, &data);
if (!php_phongo_bson_data_to_zval_ex(data, len, &state)) {
zval_ptr_dtor(&state.zchild);
goto done;
}
ADD_ASSOC_ZVAL_EX(&retval, "upsertedIds", &state.zchild);
} else {
zval upsertedIds;
array_init(&upsertedIds);
ADD_ASSOC_ZVAL_EX(&retval, "upsertedIds", &upsertedIds);
}
{
zval writeerrors;
phongo_writeresult_get_writeerrors(intern, &writeerrors);
ADD_ASSOC_ZVAL_EX(&retval, "writeErrors", &writeerrors);
}
{
zval writeconcernerror;
phongo_writeresult_get_writeconcernerror(intern, &writeconcernerror);
ADD_ASSOC_ZVAL_EX(&retval, "writeConcernError", &writeconcernerror);
}
if (intern->write_concern) {
zval write_concern;
phongo_writeconcern_init(&write_concern, intern->write_concern);
ADD_ASSOC_ZVAL_EX(&retval, "writeConcern", &write_concern);
} else {
ADD_ASSOC_NULL_EX(&retval, "writeConcern");
}
{
zval error_replies;
php_phongo_writeresult_get_error_replies(intern, &error_replies);
ADD_ASSOC_ZVAL_EX(&retval, "errorReplies", &error_replies);
}
done:
return Z_ARRVAL(retval);
}
void php_phongo_writeresult_init_ce(INIT_FUNC_ARGS)
{
php_phongo_writeresult_ce = register_class_MongoDB_Driver_WriteResult();
php_phongo_writeresult_ce->create_object = php_phongo_writeresult_create_object;
memcpy(&php_phongo_handler_writeresult, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
php_phongo_handler_writeresult.get_debug_info = php_phongo_writeresult_get_debug_info;
php_phongo_handler_writeresult.free_obj = php_phongo_writeresult_free_object;
php_phongo_handler_writeresult.offset = XtOffsetOf(php_phongo_writeresult_t, std);
}
php_phongo_writeresult_t* phongo_writeresult_init(zval* return_value, bson_t* reply, zval* manager, uint32_t server_id)
{
php_phongo_writeresult_t* writeresult;
object_init_ex(return_value, php_phongo_writeresult_ce);
writeresult = Z_WRITERESULT_OBJ_P(return_value);
writeresult->reply = bson_copy(reply);
writeresult->server_id = server_id;
ZVAL_ZVAL(&writeresult->manager, manager, 1, 0);
return writeresult;
}
mongodb-2.1.0/src/MongoDB/WriteResult.h 0000644 0001751 0000166 00000001572 15014033047 014600 0 ustar /*
* Copyright 2022-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef PHONGO_WRITERESULT_H
#define PHONGO_WRITERESULT_H
#include "bson/bson.h"
#include
#include "phongo_structs.h"
php_phongo_writeresult_t* phongo_writeresult_init(zval* return_value, bson_t* reply, zval* manager, uint32_t server_id);
#endif /* PHONGO_WRITERESULT_H */
mongodb-2.1.0/src/MongoDB/WriteResult_arginfo.h 0000644 0001751 0000166 00000011056 15014033047 016303 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 217742ba620620cfaee2758070ff13e651620f87 */
ZEND_BEGIN_ARG_INFO_EX(arginfo_class_MongoDB_Driver_WriteResult___construct, 0, 0, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_WriteResult_getInsertedCount, 0, 0, IS_LONG, 0)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_WriteResult_getMatchedCount arginfo_class_MongoDB_Driver_WriteResult_getInsertedCount
#define arginfo_class_MongoDB_Driver_WriteResult_getModifiedCount arginfo_class_MongoDB_Driver_WriteResult_getInsertedCount
#define arginfo_class_MongoDB_Driver_WriteResult_getDeletedCount arginfo_class_MongoDB_Driver_WriteResult_getInsertedCount
#define arginfo_class_MongoDB_Driver_WriteResult_getUpsertedCount arginfo_class_MongoDB_Driver_WriteResult_getInsertedCount
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_WriteResult_getServer, 0, 0, MongoDB\\Driver\\Server, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_WriteResult_getUpsertedIds, 0, 0, IS_ARRAY, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(arginfo_class_MongoDB_Driver_WriteResult_getWriteConcernError, 0, 0, MongoDB\\Driver\\WriteConcernError, 1)
ZEND_END_ARG_INFO()
#define arginfo_class_MongoDB_Driver_WriteResult_getWriteErrors arginfo_class_MongoDB_Driver_WriteResult_getUpsertedIds
#define arginfo_class_MongoDB_Driver_WriteResult_getErrorReplies arginfo_class_MongoDB_Driver_WriteResult_getUpsertedIds
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_Driver_WriteResult_isAcknowledged, 0, 0, _IS_BOOL, 0)
ZEND_END_ARG_INFO()
static ZEND_METHOD(MongoDB_Driver_WriteResult, __construct);
static ZEND_METHOD(MongoDB_Driver_WriteResult, getInsertedCount);
static ZEND_METHOD(MongoDB_Driver_WriteResult, getMatchedCount);
static ZEND_METHOD(MongoDB_Driver_WriteResult, getModifiedCount);
static ZEND_METHOD(MongoDB_Driver_WriteResult, getDeletedCount);
static ZEND_METHOD(MongoDB_Driver_WriteResult, getUpsertedCount);
static ZEND_METHOD(MongoDB_Driver_WriteResult, getServer);
static ZEND_METHOD(MongoDB_Driver_WriteResult, getUpsertedIds);
static ZEND_METHOD(MongoDB_Driver_WriteResult, getWriteConcernError);
static ZEND_METHOD(MongoDB_Driver_WriteResult, getWriteErrors);
static ZEND_METHOD(MongoDB_Driver_WriteResult, getErrorReplies);
static ZEND_METHOD(MongoDB_Driver_WriteResult, isAcknowledged);
static const zend_function_entry class_MongoDB_Driver_WriteResult_methods[] = {
ZEND_ME(MongoDB_Driver_WriteResult, __construct, arginfo_class_MongoDB_Driver_WriteResult___construct, ZEND_ACC_PRIVATE|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteResult, getInsertedCount, arginfo_class_MongoDB_Driver_WriteResult_getInsertedCount, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteResult, getMatchedCount, arginfo_class_MongoDB_Driver_WriteResult_getMatchedCount, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteResult, getModifiedCount, arginfo_class_MongoDB_Driver_WriteResult_getModifiedCount, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteResult, getDeletedCount, arginfo_class_MongoDB_Driver_WriteResult_getDeletedCount, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteResult, getUpsertedCount, arginfo_class_MongoDB_Driver_WriteResult_getUpsertedCount, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteResult, getServer, arginfo_class_MongoDB_Driver_WriteResult_getServer, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteResult, getUpsertedIds, arginfo_class_MongoDB_Driver_WriteResult_getUpsertedIds, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteResult, getWriteConcernError, arginfo_class_MongoDB_Driver_WriteResult_getWriteConcernError, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteResult, getWriteErrors, arginfo_class_MongoDB_Driver_WriteResult_getWriteErrors, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteResult, getErrorReplies, arginfo_class_MongoDB_Driver_WriteResult_getErrorReplies, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_Driver_WriteResult, isAcknowledged, arginfo_class_MongoDB_Driver_WriteResult_isAcknowledged, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_FE_END
};
static zend_class_entry *register_class_MongoDB_Driver_WriteResult(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\Driver", "WriteResult", class_MongoDB_Driver_WriteResult_methods);
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
return class_entry;
}
mongodb-2.1.0/src/contrib/php_array_api.h 0000644 0001751 0000166 00000047703 15014033047 015306 0 ustar /* +----------------------------------------------------------------------+
| PHP Version 7 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2018 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Author: Sara Golemon (pollita@php.net) |
+----------------------------------------------------------------------+
*/
#ifndef PHP_ARRAY_API_H
#define PHP_ARRAY_API_H
#include "zend.h"
#include "zend_execute.h"
#include "zend_API.h"
#include "zend_operators.h"
#include "zend_hash.h"
#include "zend_list.h"
/**
* All APIs in this file follow a general format:
*
* php_array_{$verb}{$modifier}_{$type}(zval *zarr, ...)
*
* $verb is one of:
* exists - Boolean check whether the array offset exists
* fetch - Retrieve the value at $zarr[$key]
* unset - Delete the named offset from the array
*
* $modifier specifies what type of offset (key) is being used:
* - NULL terminated string variable, unknown length
* l - NULL terminated string variable, known length
* l_safe - String variable of known length, not necessarily NULL terminated
* n - Long (integer) offset
* c - NULL terminated string literal (e.g. "foo" rather than foo)
* z - zval* offset, type should be NULL, BOOL, LONG, DOUBLE, or STRING
*
* $type is specific to the "fetch" verb:
* - Fetch a zval* of any type
* bool - Fetch a zend_bool (converting as needed)
* long - Fetch a long (converting as needed)
* double - Fetch a double (converting as needed)
* string - Fetch a string (converting as needed, caller may need to free)
* array - Fetch an array (no conversion from other types)
* object - Fetch an object (no conversion, type spec optional)
* resource - Fetch a resource (no conversion, type spec mandatory)
*
* See the specific subsection for additional details
*/
/* isset($zarr[$key]) - Check for the existence of a key within an array
*
* zend_bool php_array_exists(zval *zarr, const char *key)
* zend_bool php_array_existsc(zval *zarr, const char *litstr)
* zend_bool php_array_existsl(zval *zarr, const char *key, int key_len)
* zend_bool php_array_existsl_safe(zval *zarr, const char *key, int key_len)
* zend_bool php_array_existsn(zval *zarr, unsigned long idx)
* zend_bool php_array_existsz(zval *zarr, zval *key)
*/
static inline
zend_bool php_array_exists(zval *zarr, const char *key) {
return zend_symtable_str_exists(Z_ARRVAL_P(zarr), key, strlen(key));
}
#define php_array_existsc(zarr, litstr) \
zend_symtable_str_exists(Z_ARRVAL_P(zarr), litstr, sizeof(litstr) - 1)
#define php_array_existsl(zarr, key, len) \
zend_symtable_str_exists(Z_ARRVAL_P(zarr), key, len)
static inline
zend_bool php_array_existsl_safe(zval *zarr, const char *key, int key_len) {
zend_string *keystr = zend_string_init(key, key_len, 0);
zend_bool ret = zend_symtable_exists(Z_ARRVAL_P(zarr), keystr);
zend_string_release(keystr);
return ret;
}
#define php_array_existsn(zarr, idx) \
zend_hash_index_exists(Z_ARRVAL_P(zarr), idx)
static inline
zend_bool php_array_existsz(zval *zarr, zval *key) {
switch (Z_TYPE_P(key)) {
case IS_NULL:
return php_array_existsc(zarr, "");
case IS_FALSE:
return zend_hash_index_exists(Z_ARRVAL_P(zarr), 0);
case IS_TRUE:
return zend_hash_index_exists(Z_ARRVAL_P(zarr), 1);
case IS_LONG:
return zend_hash_index_exists(Z_ARRVAL_P(zarr), Z_LVAL_P(key));
case IS_DOUBLE:
return zend_hash_index_exists(Z_ARRVAL_P(zarr),
zend_dval_to_lval(Z_DVAL_P(key)));
case IS_STRING:
return php_array_existsl(zarr, Z_STRVAL_P(key), Z_STRLEN_P(key));
default:
return 0;
}
}
/* =$zarr[$key] - Fetch a zval (or appropriate type) from an array
*
* Methods returning pointers yield NULL on key not existing,
* others yield 0, false, etc... as appropriate.
* Callers needing to distinguish empty scalars from non-existent
* scalars should use php_array_exists*() or fetch the zval then convert.
*
* If the type of the value does not match what is requested
* it will be implicitly converted (if possible).
*
* See each type section for specific prototypes
*
* php_array_fetch* - Fetch a zval
* php_array_fetch*_bool - Fetch a boolean
* php_array_fetch*_long - Fetch a long
* php_array_fetch*_double - Fetch a double
* php_array_fetch*_string - Fetch a string (must be efree()'d by caller)
* php_array_fetch*_array - Fetch an array
* php_array_fetch*_resource - Fetch a resource or a specific type
* php_array_fetch*_object - Fetch an object
*
* For each result type, there are six key forms:
* php_array_fetch_T(zval *zarr, const char *key, ...)
* NULL terminated string key
* php_array_fetchc_T(zval *zarr, const char *litkey, ...)
* String literal key
* php_array_fetchl_T(zval *zarr, const char *key, int key_len, ...)
* NULL terminated string key of known length
* php_array_fetchl_safe_T(zval *zarr, const char *key, int key_len, ...)
* String key of known length, may not be NULL terminated
* php_array_fetchn_T(zval *zarr, unsigned long idx, ...)
* Numeric key
* php_array_fetchz_T(zval *zarr, zval *key, ...)
* zval* key
*/
/* Fetch zval*
*
* zval *php_array_fetch(zval *zarr, const char *key)
* zval *php_array_fetchl(zval *zarr, const char *key, int key_len)
* zval *php_array_fetchl_safe(zval *zarr, const char *key, int key_len)
* zval *php_array_fetchn(zval *zarr, unsigned long idx)
* zval *php_array_fetchc(zval *zarr, const char *litstr)
* zval *php_array_fetchz(zval *zarr, zval *key)
*/
static inline
zval *php_array_fetchl(zval *zarr, const char *key, int key_len) {
return zend_symtable_str_find(Z_ARRVAL_P(zarr), key, key_len);
}
static inline
zval *php_array_fetch(zval *zarr, const char *key) {
return php_array_fetchl(zarr, key, strlen(key));
}
#define php_array_fetchc(zarr, litstr) php_array_fetchl(zarr, litstr, sizeof(litstr)-1)
static inline
zval *php_array_fetchl_safe(zval *zarr, const char *key, int key_len) {
zend_string *keystr = zend_string_init(key, key_len, 0);
zval *ret = zend_symtable_find(Z_ARRVAL_P(zarr), keystr);
zend_string_release(keystr);
return ret;
}
static inline
zval *php_array_fetchn(zval *zarr, zend_ulong idx) {
return zend_hash_index_find(Z_ARRVAL_P(zarr), idx);
}
static inline
zval *php_array_fetchz(zval *zarr, zval *key) {
switch (Z_TYPE_P(key)) {
case IS_NULL:
case IS_FALSE:
return php_array_fetchn(zarr, 0);
case IS_TRUE:
return php_array_fetchn(zarr, 1);
case IS_LONG:
return php_array_fetchn(zarr, Z_LVAL_P(key));
case IS_DOUBLE:
return php_array_fetchn(zarr, (zend_ulong) Z_DVAL_P(key));
case IS_STRING:
return php_array_fetchl(zarr, Z_STRVAL_P(key), Z_STRLEN_P(key));
default:
return NULL;
}
}
static inline zval* zval_deref_safe(zval* z) {
if (z) { ZVAL_DEREF(z); }
return z;
}
/* Fetch zval*, resolving references
*
* zval *php_array_fetch_deref(zval *zarr, const char *key)
* zval *php_array_fetchl_deref(zval *zarr, const char *key, int key_len)
* zval *php_array_fetchl_safe_deref(zval *zarr, const char *key, int key_len)
* zval *php_array_fetchn_deref(zval *zarr, unsigned long idx)
* zval *php_array_fetchc_deref(zval *zarr, const char *litstr)
* zval *php_array_fetchz_deref(zval *zarr, zval *key)
*/
static inline
zval *php_array_fetchl_deref(zval *zarr, const char *key, int key_len) {
return zval_deref_safe(php_array_fetchl(zarr, key, key_len));
}
static inline
zval *php_array_fetch_deref(zval *zarr, const char *key) {
return zval_deref_safe(php_array_fetch(zarr, key));
}
#define php_array_fetchc_deref(zarr, litstr) zval_deref_safe(php_array_fetchl(zarr, litstr, sizeof(litstr)-1))
static inline
zval *php_array_fetchl_safe_deref(zval *zarr, const char *key, int key_len) {
return zval_deref_safe(php_array_fetchl_safe(zarr, key, key_len));
}
static inline
zval *php_array_fetchn_deref(zval *zarr, zend_ulong idx) {
return zval_deref_safe(php_array_fetchn(zarr, idx));
}
static inline
zval *php_array_fetchz_deref(zval *zarr, zval *key) {
return zval_deref_safe(php_array_fetchz(zarr, key));
}
#define PHP_ARRAY_FETCH_TYPE_MAP(ctype, ztype) \
static inline ctype php_array_fetch_##ztype(zval *zarr, const char *key) \
{ return php_array_zval_to_##ztype(php_array_fetch_deref(zarr, key)); } \
static inline ctype php_array_fetchl_##ztype(zval *zarr, const char *key, int key_len) \
{ return php_array_zval_to_##ztype(php_array_fetchl_deref(zarr, key, key_len)); } \
static inline ctype php_array_fetchl_safe_##ztype(zval *zarr, const char *key, int key_len) \
{ return php_array_zval_to_##ztype(php_array_fetchl_safe_deref(zarr, key, key_len)); } \
static inline ctype php_array_fetchn_##ztype(zval *zarr, zend_ulong idx) \
{ return php_array_zval_to_##ztype(php_array_fetchn_deref(zarr, idx)); } \
static inline ctype php_array_fetchz_##ztype(zval *zarr, zval *key) \
{ return php_array_zval_to_##ztype(php_array_fetchz_deref(zarr, key)); }
/* Fetch zend_bool
*
* zend_bool php_array_fetch_bool(zval *zarr, const char *key)
* zend_bool php_array_fetchl_bool(zval *zarr, const char *key, int key_len)
* zend_bool php_array_fetchl_safe_bool(zval *zarr, const char *key, int key_len)
* zend_bool php_array_fetchn_bool(zval *zarr, unsigned long idx)
* zend_bool php_array_fetchc_bool(zval *zarr, const char *litstr)
* zend_bool php_array_fetchz_bool(zval *zarr, zval *key)
*/
static inline
zend_bool php_array_zval_to_bool(zval *z) {
return z && zend_is_true(z);
}
PHP_ARRAY_FETCH_TYPE_MAP(zend_bool, bool)
#define php_array_fetchc_bool(zarr, litstr) \
php_array_zval_to_bool(php_array_fetchc_deref(zarr, litstr))
/* Fetch long
*
* long php_array_fetch_long(zval *zarr, const char *key)
* long php_array_fetchl_long(zval *zarr, const char *key, int key_len)
* long php_array_fetchl_safe_long(zval *zarr, const char *key, int key_len)
* long php_array_fetchn_long(zval *zarr, unsigned long idx)
* long php_array_fetchc_long(zval *zarr, const char *litstr)
* long php_array_fetchz_long(zval *zarr, zval *key)
*/
static inline
zend_long php_array_zval_to_long(zval *z) {
if (!z) { return 0; }
switch(Z_TYPE_P(z)) {
case IS_NULL:
case IS_FALSE:
return 0;
case IS_TRUE:
return 1;
case IS_LONG:
return Z_LVAL_P(z);
default:
{
zval c = *z;
zval_copy_ctor(&c);
convert_to_long(&c);
return Z_LVAL(c);
}
}
}
PHP_ARRAY_FETCH_TYPE_MAP(zend_long, long)
#define php_array_fetchc_long(zarr, litstr) \
php_array_zval_to_long(php_array_fetchc_deref(zarr, litstr))
/* Fetch double
*
* double php_array_fetch_double(zval *zarr, const char *key)
* double php_array_fetchl_double(zval *zarr, const char *key, int key_len)
* double php_array_fetchl_safe_double(zval *zarr, const char *key, int key_len)
* double php_array_fetchn_double(zval *zarr, unsigned long idx)
* double php_array_fetchc_double(zval *zarr, const char *litstr)
* double php_array_fetchz_double(zval *zarr, zval *key)
*/
static inline
double php_array_zval_to_double(zval *z) {
if (!z) { return 0.0; }
switch (Z_TYPE_P(z)) {
case IS_NULL:
case IS_FALSE:
return 0.0;
case IS_TRUE:
return 1.0;
case IS_LONG:
return (double) Z_LVAL_P(z);
case IS_DOUBLE:
return Z_DVAL_P(z);
default:
{
zval c = *z;
zval_copy_ctor(&c);
convert_to_double(&c);
return Z_DVAL(c);
}
}
}
PHP_ARRAY_FETCH_TYPE_MAP(double, double)
#define php_array_fetchc_double(zarr, litstr) \
php_array_zval_to_double(php_array_fetchc_deref(zarr, litstr))
/* Fetch string
*
* If the pfree is set to 1 on exit, then the return value is owned by the caller
* and must be efree()'d once it is no longer in use.
*
* plen is populated with the binary safe length of the string returned.
*
* char *php_array_fetch_string(zval *zarr, const char *key, int *plen, zend_bool *pfree)
* char *php_array_fetchl_string(zval *zarr, const char *key, int key_len, int *plen, zend_bool *pfree)
* char *php_array_fetchl_safe_string(zval *zarr, const char *key, int key_len, int *plen, zend_bool *pfree)
* char *php_array_fetchn_string(zval *zarr, unsigned long idx, int *plen, zend_bool *pfree)
* char *php_array_fetchc_string(zval *zarr, const char *litstr, int *plen, zend_bool *pfree)
* char *php_array_fetchz_string(zval *zarr, zval *key, int *plen, zend_bool *pfree)
*/
static inline
char *php_array_zval_to_string(zval *z, int *plen, zend_bool *pfree) {
*plen = 0;
*pfree = 0;
if (!z) { return NULL; }
switch (Z_TYPE_P(z)) {
case IS_NULL:
return (char *) "";
case IS_STRING:
*plen = Z_STRLEN_P(z);
return Z_STRVAL_P(z);
default:
{
zval c = *z;
zval_copy_ctor(&c);
convert_to_string(&c);
*pfree = ! IS_INTERNED(Z_STR(c));
*plen = Z_STRLEN(c);
return Z_STRVAL(c);
}
}
}
#define php_array_fetch_string(zarr, key, plen, pfree) \
php_array_zval_to_string(php_array_fetch_deref(zarr, key), plen, pfree)
#define php_array_fetchl_string(zarr, key, key_len, plen, pfree) \
php_array_zval_to_string(php_array_fetchl_deref(zarr, key, key_len), plen, pfree)
#define php_array_fetchl_safe_string(zarr, key, key_len, plen, pfree) \
php_array_zval_to_string(php_array_fetchl_safe_deref(zarr, key, key_le), plen, pfree)
#define php_array_fetchn_string(zarr, idx, plen, pfree) \
php_array_zval_to_string(php_array_fetchn_deref(zarr, idx), plen, pfree)
#define php_array_fetchc_string(zarr, litstr, plen, pfree) \
php_array_zval_to_string(php_array_fetchc_deref(zarr, litstr), plen, pfree)
#define php_array_fetchz_string(zarr, key, plen, pfree) \
php_array_zval_to_string(php_array_fetchz_deref(zarr, key), plen, pfree)
/* Fetch array
*
* No implicit conversion is performed.
*
* If the value is an array, then that zval is returned,
* otherwise NULL is returned.
*
* zval *php_array_fetch_array(zval *zarr, const char *key)
* zval *php_array_fetchl_array(zval *zarr, const char *key, int key_len)
* zval *php_array_fetchl_safe_array(zval *zarr, const char *key, int key_len)
* zval *php_array_fetchn_array(zval *zarr, unsigned long idx)
* zval *php_array_fetchc_array(zval *zarr, const char *litstr)
* zval *php_array_fetchz_array(zval *zarr, zval *key)
*/
static inline zval *php_array_zval_to_array(zval *zarr) {
return zarr && Z_TYPE_P(zarr) == IS_ARRAY ? zarr : NULL;
}
PHP_ARRAY_FETCH_TYPE_MAP(zval*, array)
#define php_array_fetchc_array(zarr, litstr) \
php_array_zval_to_array(php_array_fetchc_deref(zarr, litstr))
/* count($arr) - Count number of elements in the array
*
* int php_array_count(zval *arr)
*/
#define php_array_count(zarr) zend_hash_num_elements(Z_ARRVAL_P(zarr))
/* Fetch resource
*
* No implicit conversion is performed.
*
* If the value is a resource of the named type,
* then the pointer for it is returned,
* otherwise NULL is returned.
*
* To test for multiple resource types (e.g. 'stream' and 'persistent stream')
* Fetch a generic zval* and use Zend's ZEND_FETCH_RESOURCE() macro.
*
* zval *php_array_fetch_resource(zval *zarr, const char *key, int le)
* zval *php_array_fetchl_resource(zval *zarr, const char *key, int key_len, int le)
* zval *php_array_fetchl_safe_resource(zval *zarr, const char *key, int key_len, int le)
* zval *php_array_fetchn_resource(zval *zarr, unsigned long idx, int le)
* zval *php_array_fetchc_resource(zval *zarr, const char *litstr, int le)
* zval *php_array_fetchz_resource(zval *zarr, zval *key, int le)
*/
static inline
void *php_array_zval_to_resource(zval *z, int le) {
return zend_fetch_resource_ex(z, NULL, le);
}
#define php_array_fetch_resource(zarr, key, le) \
php_array_zval_to_resource(php_array_fetch_deref(zarr, key), le)
#define php_array_fetchl_resource(zarr, key, key_len, le) \
php_array_zval_to_resource(php_array_fetchl_deref(zarr, key, key_len), le)
#define php_array_fetchl_safe_resource(zarr, key, key_len, le) \
php_array_zval_to_resource(php_array_fetchl_safe_deref(zarr, key, key_len), le)
#define php_array_fetchn_resource(zarr, idx, le) \
php_array_zval_to_resource(php_array_fetchn_deref(zarr, idx), le)
#define php_array_fetchc_resource(zarr, litstr, le) \
php_array_zval_to_resource(php_array_fetchc_deref(zarr, litstr), le)
#define php_array_fetchz_resource(zarr, key, le) \
php_array_zval_to_resource(php_array_fetchz_deref(zarr, key), le)
/* Fetch Object
*
* Fetch an object of a specific or non-specific type (pass ce == NULL)
*
* No implicit conversion is performed
*
* zval *php_array_fetch_object(zval *zarr, const char *key, zend_class_entry *ce)
* zval *php_array_fetchl_object(zval *zarr, const char *key, int key_len, zend_class_entry *ce)
* zval *php_array_fetchl_safe_object(zval *zarr, const char *key, int key_len, zend_class_entry *ce)
* zval *php_array_fetchn_object(zval *zarr, unsigned long idx, zend_class_entry *ce)
* zval *php_array_fetchc_object(zval *zarr, const char *litstr, zend_class_entry *ce)
* zval *php_array_fetchz_object(zval *zarr, zval *key, zend_class_entry *ce)
*/
static inline
zval *php_array_zval_to_object(zval *z, zend_class_entry *ce) {
if (!z || Z_TYPE_P(z) != IS_OBJECT) { return NULL; }
return (!ce) || instanceof_function(Z_OBJCE_P(z), ce) ? z : NULL;
}
#define php_array_fetch_object(zarr, key, ce) \
php_array_zval_to_object(php_array_fetch_deref(zarr, key), ce)
#define php_array_fetchl_object(zarr, key, len, ce) \
php_array_zval_to_object(php_array_fetchl_deref(zarr, key, len), ce)
#define php_array_fetchl_safe_object(zarr, key, len, ce) \
php_array_zval_to_object(php_array_fetchl_safe_deref(zarr, key, len), ce)
#define php_array_fetchn_object(zarr, idx, ce) \
php_array_zval_to_object(php_array_fetchn_deref(zarr, idx), ce)
#define php_array_fetchc_object(zarr, litstr, ce) \
php_array_zval_to_object(php_array_fetchc_deref(zarr, litstr), ce)
#define php_array_fetchz_object(zarr, key, ce) \
php_array_zval_to_object(php_array_fetchz_deref(zarr, key), ce)
/* unset($zarr[$key]) - Erase a key from an array
*
* void php_array_unset(zval *zarr, const char *key)
* void php_array_unsetl(zval *zarr, const char *key, int key_len)
* void php_array_unsetl_safe(zval *zarr, const char *key, int key_len)
* void php_array_unsetn(zval *zarr, long idx)
* void php_array_unsetc(zval *zarr, const char *litstr)
* void php_array_unsetz(zval *zarr, zval *key)
*/
static inline
void php_array_unset(zval *zarr, const char *key) {
zend_symtable_str_del(Z_ARRVAL_P(zarr), key, strlen(key));
}
#define php_array_unsetl(zarr, key, len) \
zend_symtable_str_del(Z_ARRVAL_P(zarr), key, len)
static inline
void php_array_unsetl_safe(zval *zarr, const char *key, int key_len) {
char *k = estrndup(key, key_len);
zend_symtable_str_del(Z_ARRVAL_P(zarr), k, key_len);
efree(k);
}
#define php_array_unsetn(zarr, idx) \
zend_symtable_index_del(Z_ARRVAL_P(zarr), idx)
#define php_array_unsetc(zarr, litstr) \
zend_symtable_str_del(Z_ARRVAL_P(zarr), litstr, sizeof(litstr) - 1)
static inline void php_array_unsetz(zval *zarr, zval *key) {
switch (Z_TYPE_P(key)) {
case IS_NULL:
case IS_FALSE:
zend_hash_index_del(Z_ARRVAL_P(zarr), 0);
return;
case IS_TRUE:
zend_hash_index_del(Z_ARRVAL_P(zarr), 1);
return;
case IS_LONG:
zend_hash_index_del(Z_ARRVAL_P(zarr), Z_LVAL_P(key));
return;
case IS_DOUBLE:
zend_hash_index_del(Z_ARRVAL_P(zarr), (zend_ulong) Z_DVAL_P(key));
break;
case IS_STRING:
php_array_unsetl(zarr, Z_STRVAL_P(key), Z_STRLEN_P(key));
break;
}
}
#endif /* PHP_ARRAY_API_H */
mongodb-2.1.0/src/libmongoc/src/common/src/common-atomic-private.h 0000644 0001751 0000166 00000111173 15014033047 022052 0 ustar /*
* Copyright 2009-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#ifndef MONGO_C_DRIVER_COMMON_ATOMIC_PRIVATE_H
#define MONGO_C_DRIVER_COMMON_ATOMIC_PRIVATE_H
#include // BSON_INLINE
#ifdef _MSC_VER
#include
#endif
enum mcommon_memory_order {
mcommon_memory_order_seq_cst,
mcommon_memory_order_acquire,
mcommon_memory_order_release,
mcommon_memory_order_relaxed,
mcommon_memory_order_acq_rel,
mcommon_memory_order_consume,
};
#if defined(_M_ARM) /* MSVC memorder atomics are only avail on ARM */
#define MSVC_MEMORDER_SUFFIX(X) X
#else
#define MSVC_MEMORDER_SUFFIX(X)
#endif
#if defined(USE_LEGACY_GCC_ATOMICS) || (!defined(__clang__) && __GNUC__ == 4) || defined(__xlC__)
#define MCOMMON_USE_LEGACY_GCC_ATOMICS
#else
#undef MCOMMON_USE_LEGACY_GCC_ATOMICS
#endif
/* Not all GCC-like compilers support the current __atomic built-ins. Older
* GCC (pre-5) used different built-ins named with the __sync prefix. When
* compiling with such older GCC versions, it is necessary to use the applicable
* functions, which requires redefining BSON_IF_GNU_LIKE and defining the
* additional MCOMMON_IF_GNU_LEGACY_ATOMICS macro here. */
#ifdef MCOMMON_USE_LEGACY_GCC_ATOMICS
#undef BSON_IF_GNU_LIKE
#define BSON_IF_GNU_LIKE(...)
#define MCOMMON_IF_GNU_LEGACY_ATOMICS(...) __VA_ARGS__
#else
#define MCOMMON_IF_GNU_LEGACY_ATOMICS(...)
#endif
/* CDRIVER-4229 zSeries with gcc 4.8.4 produces illegal instructions for int and
* int32 atomic intrinsics. */
#if defined(__s390__) || defined(__s390x__) || defined(__zarch__)
#define MCOMMON_EMULATE_INT32
#define MCOMMON_EMULATE_INT
#endif
/* CDRIVER-4264 Contrary to documentation, VS 2013 targeting x86 does not
* correctly/consistently provide _InterlockedPointerExchange. */
#if defined(_MSC_VER) && _MSC_VER < 1900 && defined(_M_IX86)
#define MCOMMON_EMULATE_PTR
#endif
#define DEF_ATOMIC_OP(MSVC_Intrinsic, GNU_Intrinsic, GNU_Legacy_Intrinsic, Order, ...) \
do { \
switch (Order) { \
case mcommon_memory_order_acq_rel: \
BSON_IF_MSVC (return MSVC_Intrinsic (__VA_ARGS__);) \
BSON_IF_GNU_LIKE (return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_ACQ_REL);) \
MCOMMON_IF_GNU_LEGACY_ATOMICS (return GNU_Legacy_Intrinsic (__VA_ARGS__);) \
case mcommon_memory_order_seq_cst: \
BSON_IF_MSVC (return MSVC_Intrinsic (__VA_ARGS__);) \
BSON_IF_GNU_LIKE (return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_SEQ_CST);) \
MCOMMON_IF_GNU_LEGACY_ATOMICS (return GNU_Legacy_Intrinsic (__VA_ARGS__);) \
case mcommon_memory_order_acquire: \
BSON_IF_MSVC (return BSON_CONCAT (MSVC_Intrinsic, MSVC_MEMORDER_SUFFIX (_acq)) (__VA_ARGS__);) \
BSON_IF_GNU_LIKE (return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_ACQUIRE);) \
MCOMMON_IF_GNU_LEGACY_ATOMICS (return GNU_Legacy_Intrinsic (__VA_ARGS__);) \
case mcommon_memory_order_consume: \
BSON_IF_MSVC (return BSON_CONCAT (MSVC_Intrinsic, MSVC_MEMORDER_SUFFIX (_acq)) (__VA_ARGS__);) \
BSON_IF_GNU_LIKE (return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_CONSUME);) \
MCOMMON_IF_GNU_LEGACY_ATOMICS (return GNU_Legacy_Intrinsic (__VA_ARGS__);) \
case mcommon_memory_order_release: \
BSON_IF_MSVC (return BSON_CONCAT (MSVC_Intrinsic, MSVC_MEMORDER_SUFFIX (_rel)) (__VA_ARGS__);) \
BSON_IF_GNU_LIKE (return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_RELEASE);) \
MCOMMON_IF_GNU_LEGACY_ATOMICS (return GNU_Legacy_Intrinsic (__VA_ARGS__);) \
case mcommon_memory_order_relaxed: \
BSON_IF_MSVC (return BSON_CONCAT (MSVC_Intrinsic, MSVC_MEMORDER_SUFFIX (_nf)) (__VA_ARGS__);) \
BSON_IF_GNU_LIKE (return GNU_Intrinsic (__VA_ARGS__, __ATOMIC_RELAXED);) \
MCOMMON_IF_GNU_LEGACY_ATOMICS (return GNU_Legacy_Intrinsic (__VA_ARGS__);) \
default: \
BSON_UNREACHABLE ("Invalid mcommon_memory_order value"); \
} \
} while (0)
#define DEF_ATOMIC_CMPEXCH_STRONG(VCSuffix1, VCSuffix2, GNU_MemOrder, Ptr, ExpectActualVar, NewValue) \
do { \
BSON_IF_MSVC (ExpectActualVar = BSON_CONCAT3 (_InterlockedCompareExchange, VCSuffix1, VCSuffix2) ( \
Ptr, NewValue, ExpectActualVar);) \
BSON_IF_GNU_LIKE ((void) __atomic_compare_exchange_n (Ptr, \
&ExpectActualVar, \
NewValue, \
false, /* Not weak */ \
GNU_MemOrder, \
GNU_MemOrder);) \
MCOMMON_IF_GNU_LEGACY_ATOMICS (__typeof__ (ExpectActualVar) _val; \
_val = __sync_val_compare_and_swap (Ptr, ExpectActualVar, NewValue); \
ExpectActualVar = _val;) \
} while (0)
#define DEF_ATOMIC_CMPEXCH_WEAK(VCSuffix1, VCSuffix2, GNU_MemOrder, Ptr, ExpectActualVar, NewValue) \
do { \
BSON_IF_MSVC (ExpectActualVar = BSON_CONCAT3 (_InterlockedCompareExchange, VCSuffix1, VCSuffix2) ( \
Ptr, NewValue, ExpectActualVar);) \
BSON_IF_GNU_LIKE ((void) __atomic_compare_exchange_n (Ptr, \
&ExpectActualVar, \
NewValue, \
true, /* Yes weak */ \
GNU_MemOrder, \
GNU_MemOrder);) \
MCOMMON_IF_GNU_LEGACY_ATOMICS (__typeof__ (ExpectActualVar) _val; \
_val = __sync_val_compare_and_swap (Ptr, ExpectActualVar, NewValue); \
ExpectActualVar = _val;) \
} while (0)
#define DECL_ATOMIC_INTEGRAL(NamePart, Type, VCIntrinSuffix) \
static BSON_INLINE Type mcommon_atomic_##NamePart##_fetch_add ( \
Type volatile *a, Type addend, enum mcommon_memory_order ord) \
{ \
DEF_ATOMIC_OP (BSON_CONCAT (_InterlockedExchangeAdd, VCIntrinSuffix), \
__atomic_fetch_add, \
__sync_fetch_and_add, \
ord, \
a, \
addend); \
} \
\
static BSON_INLINE Type mcommon_atomic_##NamePart##_fetch_sub ( \
Type volatile *a, Type subtrahend, enum mcommon_memory_order ord) \
{ \
/* MSVC doesn't have a subtract intrinsic, so just reuse addition */ \
BSON_IF_MSVC (return mcommon_atomic_##NamePart##_fetch_add (a, -subtrahend, ord);) \
BSON_IF_GNU_LIKE (DEF_ATOMIC_OP (~, __atomic_fetch_sub, ~, ord, a, subtrahend);) \
MCOMMON_IF_GNU_LEGACY_ATOMICS (DEF_ATOMIC_OP (~, ~, __sync_fetch_and_sub, ord, a, subtrahend);) \
} \
\
static BSON_INLINE Type mcommon_atomic_##NamePart##_fetch (Type volatile const *a, enum mcommon_memory_order order) \
{ \
/* MSVC doesn't have a load intrinsic, so just add zero */ \
BSON_IF_MSVC (return mcommon_atomic_##NamePart##_fetch_add ((Type volatile *) a, 0, order);) \
/* GNU doesn't want RELEASE order for the fetch operation, so we can't \
* just use DEF_ATOMIC_OP. */ \
BSON_IF_GNU_LIKE (switch (order) { \
case mcommon_memory_order_release: /* Fall back to seqcst */ \
case mcommon_memory_order_acq_rel: /* Fall back to seqcst */ \
case mcommon_memory_order_seq_cst: \
return __atomic_load_n (a, __ATOMIC_SEQ_CST); \
case mcommon_memory_order_acquire: \
return __atomic_load_n (a, __ATOMIC_ACQUIRE); \
case mcommon_memory_order_consume: \
return __atomic_load_n (a, __ATOMIC_CONSUME); \
case mcommon_memory_order_relaxed: \
return __atomic_load_n (a, __ATOMIC_RELAXED); \
default: \
BSON_UNREACHABLE ("Invalid mcommon_memory_order value"); \
}) \
MCOMMON_IF_GNU_LEGACY_ATOMICS ({ \
BSON_UNUSED (order); \
__sync_synchronize (); \
return *a; \
}) \
} \
\
static BSON_INLINE Type mcommon_atomic_##NamePart##_exchange ( \
Type volatile *a, Type value, enum mcommon_memory_order ord) \
{ \
BSON_IF_MSVC (DEF_ATOMIC_OP (BSON_CONCAT (_InterlockedExchange, VCIntrinSuffix), ~, ~, ord, a, value);) \
/* GNU doesn't want CONSUME order for the exchange operation, so we \
* cannot use DEF_ATOMIC_OP. */ \
BSON_IF_GNU_LIKE (switch (ord) { \
case mcommon_memory_order_acq_rel: \
return __atomic_exchange_n (a, value, __ATOMIC_ACQ_REL); \
case mcommon_memory_order_release: \
return __atomic_exchange_n (a, value, __ATOMIC_RELEASE); \
case mcommon_memory_order_seq_cst: \
return __atomic_exchange_n (a, value, __ATOMIC_SEQ_CST); \
case mcommon_memory_order_consume: /* Fall back to acquire */ \
case mcommon_memory_order_acquire: \
return __atomic_exchange_n (a, value, __ATOMIC_ACQUIRE); \
case mcommon_memory_order_relaxed: \
return __atomic_exchange_n (a, value, __ATOMIC_RELAXED); \
default: \
BSON_UNREACHABLE ("Invalid mcommon_memory_order value"); \
}) \
MCOMMON_IF_GNU_LEGACY_ATOMICS (BSON_UNUSED (ord); return __sync_val_compare_and_swap (a, *a, value);) \
} \
\
static BSON_INLINE Type mcommon_atomic_##NamePart##_compare_exchange_strong ( \
Type volatile *a, Type expect, Type new_value, enum mcommon_memory_order ord) \
{ \
Type actual = expect; \
switch (ord) { \
case mcommon_memory_order_release: \
case mcommon_memory_order_acq_rel: \
case mcommon_memory_order_seq_cst: \
DEF_ATOMIC_CMPEXCH_STRONG (VCIntrinSuffix, , __ATOMIC_SEQ_CST, a, actual, new_value); \
break; \
case mcommon_memory_order_acquire: \
DEF_ATOMIC_CMPEXCH_STRONG ( \
VCIntrinSuffix, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_ACQUIRE, a, actual, new_value); \
break; \
case mcommon_memory_order_consume: \
DEF_ATOMIC_CMPEXCH_STRONG ( \
VCIntrinSuffix, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_CONSUME, a, actual, new_value); \
break; \
case mcommon_memory_order_relaxed: \
DEF_ATOMIC_CMPEXCH_STRONG ( \
VCIntrinSuffix, MSVC_MEMORDER_SUFFIX (_nf), __ATOMIC_RELAXED, a, actual, new_value); \
break; \
default: \
BSON_UNREACHABLE ("Invalid mcommon_memory_order value"); \
} \
return actual; \
} \
\
static BSON_INLINE Type mcommon_atomic_##NamePart##_compare_exchange_weak ( \
Type volatile *a, Type expect, Type new_value, enum mcommon_memory_order ord) \
{ \
Type actual = expect; \
switch (ord) { \
case mcommon_memory_order_release: \
case mcommon_memory_order_acq_rel: \
case mcommon_memory_order_seq_cst: \
DEF_ATOMIC_CMPEXCH_WEAK (VCIntrinSuffix, , __ATOMIC_SEQ_CST, a, actual, new_value); \
break; \
case mcommon_memory_order_acquire: \
DEF_ATOMIC_CMPEXCH_WEAK ( \
VCIntrinSuffix, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_ACQUIRE, a, actual, new_value); \
break; \
case mcommon_memory_order_consume: \
DEF_ATOMIC_CMPEXCH_WEAK ( \
VCIntrinSuffix, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_CONSUME, a, actual, new_value); \
break; \
case mcommon_memory_order_relaxed: \
DEF_ATOMIC_CMPEXCH_WEAK (VCIntrinSuffix, MSVC_MEMORDER_SUFFIX (_nf), __ATOMIC_RELAXED, a, actual, new_value); \
break; \
default: \
BSON_UNREACHABLE ("Invalid mcommon_memory_order value"); \
} \
return actual; \
}
#define DECL_ATOMIC_STDINT(Name, VCSuffix) DECL_ATOMIC_INTEGRAL (Name, Name##_t, VCSuffix)
#if defined(_MSC_VER) || defined(MCOMMON_USE_LEGACY_GCC_ATOMICS)
/* MSVC and GCC require built-in types (not typedefs) for their atomic
* intrinsics. */
#if defined(_MSC_VER)
#define DECL_ATOMIC_INTEGRAL_INT8 char
#define DECL_ATOMIC_INTEGRAL_INT32 long
#define DECL_ATOMIC_INTEGRAL_INT long
#else
#define DECL_ATOMIC_INTEGRAL_INT8 signed char
#define DECL_ATOMIC_INTEGRAL_INT32 int
#define DECL_ATOMIC_INTEGRAL_INT int
#endif
DECL_ATOMIC_INTEGRAL (int8, DECL_ATOMIC_INTEGRAL_INT8, 8)
DECL_ATOMIC_INTEGRAL (int16, short, 16)
#if !defined(MCOMMON_EMULATE_INT32)
DECL_ATOMIC_INTEGRAL (int32, DECL_ATOMIC_INTEGRAL_INT32, )
#endif
#if !defined(MCOMMON_EMULATE_INT)
DECL_ATOMIC_INTEGRAL (int, DECL_ATOMIC_INTEGRAL_INT, )
#endif
#else
/* Other compilers that we support provide generic intrinsics */
DECL_ATOMIC_STDINT (int8, 8)
DECL_ATOMIC_STDINT (int16, 16)
#if !defined(MCOMMON_EMULATE_INT32)
DECL_ATOMIC_STDINT (int32, )
#endif
#if !defined(MCOMMON_EMULATE_INT)
DECL_ATOMIC_INTEGRAL (int, int, )
#endif
#endif
#ifndef DECL_ATOMIC_INTEGRAL_INT32
#define DECL_ATOMIC_INTEGRAL_INT32 int32_t
#endif
#define _mcommon_emul_atomic_int64_fetch_add COMMON_NAME (emul_atomic_int64_fetch_add)
#define _mcommon_emul_atomic_int64_exchange COMMON_NAME (emul_atomic_int64_exchange)
#define _mcommon_emul_atomic_int64_compare_exchange_strong COMMON_NAME (emul_atomic_int64_compare_exchange_strong)
#define _mcommon_emul_atomic_int64_compare_exchange_weak COMMON_NAME (emul_atomic_int64_compare_exchange_weak)
#define _mcommon_emul_atomic_int32_fetch_add COMMON_NAME (emul_atomic_int32_fetch_add)
#define _mcommon_emul_atomic_int32_exchange COMMON_NAME (emul_atomic_int32_exchange)
#define _mcommon_emul_atomic_int32_compare_exchange_strong COMMON_NAME (emul_atomic_int32_compare_exchange_strong)
#define _mcommon_emul_atomic_int32_compare_exchange_weak COMMON_NAME (emul_atomic_int32_compare_exchange_weak)
#define _mcommon_emul_atomic_int_fetch_add COMMON_NAME (emul_atomic_int_fetch_add)
#define _mcommon_emul_atomic_int_exchange COMMON_NAME (emul_atomic_int_exchange)
#define _mcommon_emul_atomic_int_compare_exchange_strong COMMON_NAME (emul_atomic_int_compare_exchange_strong)
#define _mcommon_emul_atomic_int_compare_exchange_weak COMMON_NAME (emul_atomic_int_compare_exchange_weak)
#define _mcommon_emul_atomic_ptr_exchange COMMON_NAME (emul_atomic_ptr_exchange)
#define mcommon_thrd_yield COMMON_NAME (thrd_yield)
int64_t
_mcommon_emul_atomic_int64_fetch_add (int64_t volatile *val, int64_t v, enum mcommon_memory_order);
int64_t
_mcommon_emul_atomic_int64_exchange (int64_t volatile *val, int64_t v, enum mcommon_memory_order);
int64_t
_mcommon_emul_atomic_int64_compare_exchange_strong (int64_t volatile *val,
int64_t expect_value,
int64_t new_value,
enum mcommon_memory_order);
int64_t
_mcommon_emul_atomic_int64_compare_exchange_weak (int64_t volatile *val,
int64_t expect_value,
int64_t new_value,
enum mcommon_memory_order);
int32_t
_mcommon_emul_atomic_int32_fetch_add (int32_t volatile *val, int32_t v, enum mcommon_memory_order);
int32_t
_mcommon_emul_atomic_int32_exchange (int32_t volatile *val, int32_t v, enum mcommon_memory_order);
int32_t
_mcommon_emul_atomic_int32_compare_exchange_strong (int32_t volatile *val,
int32_t expect_value,
int32_t new_value,
enum mcommon_memory_order);
int32_t
_mcommon_emul_atomic_int32_compare_exchange_weak (int32_t volatile *val,
int32_t expect_value,
int32_t new_value,
enum mcommon_memory_order);
int
_mcommon_emul_atomic_int_fetch_add (int volatile *val, int v, enum mcommon_memory_order);
int
_mcommon_emul_atomic_int_exchange (int volatile *val, int v, enum mcommon_memory_order);
int
_mcommon_emul_atomic_int_compare_exchange_strong (int volatile *val,
int expect_value,
int new_value,
enum mcommon_memory_order);
int
_mcommon_emul_atomic_int_compare_exchange_weak (int volatile *val,
int expect_value,
int new_value,
enum mcommon_memory_order);
void *
_mcommon_emul_atomic_ptr_exchange (void *volatile *val, void *v, enum mcommon_memory_order);
void
mcommon_thrd_yield (void);
#if (defined(_MSC_VER) && !defined(_M_IX86)) || (defined(__LP64__) && __LP64__)
/* (64-bit intrinsics are only available in x64) */
#ifdef _MSC_VER
DECL_ATOMIC_INTEGRAL (int64, __int64, 64)
#else
DECL_ATOMIC_STDINT (int64, 64)
#endif
#else
static BSON_INLINE int64_t
mcommon_atomic_int64_fetch (const int64_t volatile *val, enum mcommon_memory_order order)
{
return _mcommon_emul_atomic_int64_fetch_add ((int64_t volatile *) val, 0, order);
}
static BSON_INLINE int64_t
mcommon_atomic_int64_fetch_add (int64_t volatile *val, int64_t v, enum mcommon_memory_order order)
{
return _mcommon_emul_atomic_int64_fetch_add (val, v, order);
}
static BSON_INLINE int64_t
mcommon_atomic_int64_fetch_sub (int64_t volatile *val, int64_t v, enum mcommon_memory_order order)
{
return _mcommon_emul_atomic_int64_fetch_add (val, -v, order);
}
static BSON_INLINE int64_t
mcommon_atomic_int64_exchange (int64_t volatile *val, int64_t v, enum mcommon_memory_order order)
{
return _mcommon_emul_atomic_int64_exchange (val, v, order);
}
static BSON_INLINE int64_t
mcommon_atomic_int64_compare_exchange_strong (int64_t volatile *val,
int64_t expect_value,
int64_t new_value,
enum mcommon_memory_order order)
{
return _mcommon_emul_atomic_int64_compare_exchange_strong (val, expect_value, new_value, order);
}
static BSON_INLINE int64_t
mcommon_atomic_int64_compare_exchange_weak (int64_t volatile *val,
int64_t expect_value,
int64_t new_value,
enum mcommon_memory_order order)
{
return _mcommon_emul_atomic_int64_compare_exchange_weak (val, expect_value, new_value, order);
}
#endif
#if defined(MCOMMON_EMULATE_INT32)
static BSON_INLINE int32_t
mcommon_atomic_int32_fetch (const int32_t volatile *val, enum mcommon_memory_order order)
{
return _mcommon_emul_atomic_int32_fetch_add ((int32_t volatile *) val, 0, order);
}
static BSON_INLINE int32_t
mcommon_atomic_int32_fetch_add (int32_t volatile *val, int32_t v, enum mcommon_memory_order order)
{
return _mcommon_emul_atomic_int32_fetch_add (val, v, order);
}
static BSON_INLINE int32_t
mcommon_atomic_int32_fetch_sub (int32_t volatile *val, int32_t v, enum mcommon_memory_order order)
{
return _mcommon_emul_atomic_int32_fetch_add (val, -v, order);
}
static BSON_INLINE int32_t
mcommon_atomic_int32_exchange (int32_t volatile *val, int32_t v, enum mcommon_memory_order order)
{
return _mcommon_emul_atomic_int32_exchange (val, v, order);
}
static BSON_INLINE int32_t
mcommon_atomic_int32_compare_exchange_strong (int32_t volatile *val,
int32_t expect_value,
int32_t new_value,
enum mcommon_memory_order order)
{
return _mcommon_emul_atomic_int32_compare_exchange_strong (val, expect_value, new_value, order);
}
static BSON_INLINE int32_t
mcommon_atomic_int32_compare_exchange_weak (int32_t volatile *val,
int32_t expect_value,
int32_t new_value,
enum mcommon_memory_order order)
{
return _mcommon_emul_atomic_int32_compare_exchange_weak (val, expect_value, new_value, order);
}
#endif /* MCOMMON_EMULATE_INT32 */
#if defined(MCOMMON_EMULATE_INT)
static BSON_INLINE int
mcommon_atomic_int_fetch (const int volatile *val, enum mcommon_memory_order order)
{
return _mcommon_emul_atomic_int_fetch_add ((int volatile *) val, 0, order);
}
static BSON_INLINE int
mcommon_atomic_int_fetch_add (int volatile *val, int v, enum mcommon_memory_order order)
{
return _mcommon_emul_atomic_int_fetch_add (val, v, order);
}
static BSON_INLINE int
mcommon_atomic_int_fetch_sub (int volatile *val, int v, enum mcommon_memory_order order)
{
return _mcommon_emul_atomic_int_fetch_add (val, -v, order);
}
static BSON_INLINE int
mcommon_atomic_int_exchange (int volatile *val, int v, enum mcommon_memory_order order)
{
return _mcommon_emul_atomic_int_exchange (val, v, order);
}
static BSON_INLINE int
mcommon_atomic_int_compare_exchange_strong (int volatile *val,
int expect_value,
int new_value,
enum mcommon_memory_order order)
{
return _mcommon_emul_atomic_int_compare_exchange_strong (val, expect_value, new_value, order);
}
static BSON_INLINE int
mcommon_atomic_int_compare_exchange_weak (int volatile *val,
int expect_value,
int new_value,
enum mcommon_memory_order order)
{
return _mcommon_emul_atomic_int_compare_exchange_weak (val, expect_value, new_value, order);
}
#endif /* MCOMMON_EMULATE_INT */
static BSON_INLINE void *
mcommon_atomic_ptr_exchange (void *volatile *ptr, void *new_value, enum mcommon_memory_order ord)
{
#if defined(MCOMMON_EMULATE_PTR)
return _mcommon_emul_atomic_ptr_exchange (ptr, new_value, ord);
#elif defined(MCOMMON_USE_LEGACY_GCC_ATOMICS)
/* The older __sync_val_compare_and_swap also takes oldval */
DEF_ATOMIC_OP (_InterlockedExchangePointer, , __sync_val_compare_and_swap, ord, ptr, *ptr, new_value);
#else
DEF_ATOMIC_OP (_InterlockedExchangePointer, __atomic_exchange_n, , ord, ptr, new_value);
#endif
}
static BSON_INLINE void *
mcommon_atomic_ptr_compare_exchange_strong (void *volatile *ptr,
void *expect,
void *new_value,
enum mcommon_memory_order ord)
{
switch (ord) {
case mcommon_memory_order_release:
case mcommon_memory_order_acq_rel:
case mcommon_memory_order_seq_cst:
DEF_ATOMIC_CMPEXCH_STRONG (Pointer, , __ATOMIC_SEQ_CST, ptr, expect, new_value);
return expect;
case mcommon_memory_order_relaxed:
DEF_ATOMIC_CMPEXCH_STRONG (Pointer, MSVC_MEMORDER_SUFFIX (_nf), __ATOMIC_RELAXED, ptr, expect, new_value);
return expect;
case mcommon_memory_order_consume:
DEF_ATOMIC_CMPEXCH_STRONG (Pointer, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_CONSUME, ptr, expect, new_value);
return expect;
case mcommon_memory_order_acquire:
DEF_ATOMIC_CMPEXCH_STRONG (Pointer, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_ACQUIRE, ptr, expect, new_value);
return expect;
default:
BSON_UNREACHABLE ("Invalid mcommon_memory_order value");
}
}
static BSON_INLINE void *
mcommon_atomic_ptr_compare_exchange_weak (void *volatile *ptr,
void *expect,
void *new_value,
enum mcommon_memory_order ord)
{
switch (ord) {
case mcommon_memory_order_release:
case mcommon_memory_order_acq_rel:
case mcommon_memory_order_seq_cst:
DEF_ATOMIC_CMPEXCH_WEAK (Pointer, , __ATOMIC_SEQ_CST, ptr, expect, new_value);
return expect;
case mcommon_memory_order_relaxed:
DEF_ATOMIC_CMPEXCH_WEAK (Pointer, MSVC_MEMORDER_SUFFIX (_nf), __ATOMIC_RELAXED, ptr, expect, new_value);
return expect;
case mcommon_memory_order_consume:
DEF_ATOMIC_CMPEXCH_WEAK (Pointer, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_CONSUME, ptr, expect, new_value);
return expect;
case mcommon_memory_order_acquire:
DEF_ATOMIC_CMPEXCH_WEAK (Pointer, MSVC_MEMORDER_SUFFIX (_acq), __ATOMIC_ACQUIRE, ptr, expect, new_value);
return expect;
default:
BSON_UNREACHABLE ("Invalid mcommon_memory_order value");
}
}
static BSON_INLINE void *
mcommon_atomic_ptr_fetch (void *volatile const *ptr, enum mcommon_memory_order ord)
{
return mcommon_atomic_ptr_compare_exchange_strong ((void *volatile *) ptr, NULL, NULL, ord);
}
#undef DECL_ATOMIC_STDINT
#undef DECL_ATOMIC_INTEGRAL
#undef DEF_ATOMIC_OP
#undef DEF_ATOMIC_CMPEXCH_STRONG
#undef DEF_ATOMIC_CMPEXCH_WEAK
#undef MSVC_MEMORDER_SUFFIX
/**
* @brief Generate a full-fence memory barrier at the call site.
*/
static BSON_INLINE void
mcommon_atomic_thread_fence (void)
{
BSON_IF_MSVC (MemoryBarrier ();)
BSON_IF_GNU_LIKE (__sync_synchronize ();)
MCOMMON_IF_GNU_LEGACY_ATOMICS (__sync_synchronize ();)
}
#ifdef MCOMMON_USE_LEGACY_GCC_ATOMICS
#undef BSON_IF_GNU_LIKE
#define BSON_IF_GNU_LIKE(...) __VA_ARGS__
#endif
#undef MCOMMON_IF_GNU_LEGACY_ATOMICS
#undef MCOMMON_USE_LEGACY_GCC_ATOMICS
#undef MCOMMON_EMULATE_PTR
#undef MCOMMON_EMULATE_INT32
#undef MCOMMON_EMULATE_INT
#endif /* MONGO_C_DRIVER_COMMON_ATOMIC_PRIVATE_H */
mongodb-2.1.0/src/libmongoc/src/common/src/common-atomic.c 0000644 0001751 0000166 00000014535 15014033047 020401 0 ustar /*
* Copyright 2009-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#ifdef BSON_OS_UNIX
/* For sched_yield() */
#include
#endif
void
mcommon_thrd_yield (void)
{
BSON_IF_WINDOWS (SwitchToThread ();)
BSON_IF_POSIX (sched_yield ();)
}
/**
* Some platforms do not support compiler intrinsics for atomic operations.
* We emulate that here using a spin lock and regular arithmetic operations
*/
static int8_t gEmulAtomicLock = 0;
static void
_lock_emul_atomic (void)
{
int i;
if (mcommon_atomic_int8_compare_exchange_weak (&gEmulAtomicLock, 0, 1, mcommon_memory_order_acquire) == 0) {
/* Successfully took the spinlock */
return;
}
/* Failed. Try taking ten more times, then begin sleeping. */
for (i = 0; i < 10; ++i) {
if (mcommon_atomic_int8_compare_exchange_weak (&gEmulAtomicLock, 0, 1, mcommon_memory_order_acquire) == 0) {
/* Succeeded in taking the lock */
return;
}
}
/* Still don't have the lock. Spin and yield */
while (mcommon_atomic_int8_compare_exchange_weak (&gEmulAtomicLock, 0, 1, mcommon_memory_order_acquire) != 0) {
mcommon_thrd_yield ();
}
}
static void
_unlock_emul_atomic (void)
{
int64_t rv = mcommon_atomic_int8_exchange (&gEmulAtomicLock, 0, mcommon_memory_order_release);
BSON_ASSERT (rv == 1 && "Released atomic lock while not holding it");
}
int64_t
_mcommon_emul_atomic_int64_fetch_add (volatile int64_t *p, int64_t n, enum mcommon_memory_order _unused)
{
int64_t ret;
BSON_UNUSED (_unused);
_lock_emul_atomic ();
ret = *p;
*p += n;
_unlock_emul_atomic ();
return ret;
}
int64_t
_mcommon_emul_atomic_int64_exchange (volatile int64_t *p, int64_t n, enum mcommon_memory_order _unused)
{
int64_t ret;
BSON_UNUSED (_unused);
_lock_emul_atomic ();
ret = *p;
*p = n;
_unlock_emul_atomic ();
return ret;
}
int64_t
_mcommon_emul_atomic_int64_compare_exchange_strong (volatile int64_t *p,
int64_t expect_value,
int64_t new_value,
enum mcommon_memory_order _unused)
{
int64_t ret;
BSON_UNUSED (_unused);
_lock_emul_atomic ();
ret = *p;
if (ret == expect_value) {
*p = new_value;
}
_unlock_emul_atomic ();
return ret;
}
int64_t
_mcommon_emul_atomic_int64_compare_exchange_weak (volatile int64_t *p,
int64_t expect_value,
int64_t new_value,
enum mcommon_memory_order order)
{
/* We're emulating. We can't do a weak version. */
return _mcommon_emul_atomic_int64_compare_exchange_strong (p, expect_value, new_value, order);
}
int32_t
_mcommon_emul_atomic_int32_fetch_add (volatile int32_t *p, int32_t n, enum mcommon_memory_order _unused)
{
int32_t ret;
BSON_UNUSED (_unused);
_lock_emul_atomic ();
ret = *p;
*p += n;
_unlock_emul_atomic ();
return ret;
}
int32_t
_mcommon_emul_atomic_int32_exchange (volatile int32_t *p, int32_t n, enum mcommon_memory_order _unused)
{
int32_t ret;
BSON_UNUSED (_unused);
_lock_emul_atomic ();
ret = *p;
*p = n;
_unlock_emul_atomic ();
return ret;
}
int32_t
_mcommon_emul_atomic_int32_compare_exchange_strong (volatile int32_t *p,
int32_t expect_value,
int32_t new_value,
enum mcommon_memory_order _unused)
{
int32_t ret;
BSON_UNUSED (_unused);
_lock_emul_atomic ();
ret = *p;
if (ret == expect_value) {
*p = new_value;
}
_unlock_emul_atomic ();
return ret;
}
int32_t
_mcommon_emul_atomic_int32_compare_exchange_weak (volatile int32_t *p,
int32_t expect_value,
int32_t new_value,
enum mcommon_memory_order order)
{
/* We're emulating. We can't do a weak version. */
return _mcommon_emul_atomic_int32_compare_exchange_strong (p, expect_value, new_value, order);
}
int
_mcommon_emul_atomic_int_fetch_add (volatile int *p, int n, enum mcommon_memory_order _unused)
{
int ret;
BSON_UNUSED (_unused);
_lock_emul_atomic ();
ret = *p;
*p += n;
_unlock_emul_atomic ();
return ret;
}
int
_mcommon_emul_atomic_int_exchange (volatile int *p, int n, enum mcommon_memory_order _unused)
{
int ret;
BSON_UNUSED (_unused);
_lock_emul_atomic ();
ret = *p;
*p = n;
_unlock_emul_atomic ();
return ret;
}
int
_mcommon_emul_atomic_int_compare_exchange_strong (volatile int *p,
int expect_value,
int new_value,
enum mcommon_memory_order _unused)
{
int ret;
BSON_UNUSED (_unused);
_lock_emul_atomic ();
ret = *p;
if (ret == expect_value) {
*p = new_value;
}
_unlock_emul_atomic ();
return ret;
}
int
_mcommon_emul_atomic_int_compare_exchange_weak (volatile int *p,
int expect_value,
int new_value,
enum mcommon_memory_order order)
{
/* We're emulating. We can't do a weak version. */
return _mcommon_emul_atomic_int_compare_exchange_strong (p, expect_value, new_value, order);
}
void *
_mcommon_emul_atomic_ptr_exchange (void *volatile *p, void *n, enum mcommon_memory_order _unused)
{
void *ret;
BSON_UNUSED (_unused);
_lock_emul_atomic ();
ret = *p;
*p = n;
_unlock_emul_atomic ();
return ret;
}
mongodb-2.1.0/src/libmongoc/src/common/src/common-b64-private.h 0000644 0001751 0000166 00000004416 15014033047 021172 0 ustar /*
* Copyright 2009-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#ifndef MONGO_C_DRIVER_COMMON_B64_PRIVATE_H
#define MONGO_C_DRIVER_COMMON_B64_PRIVATE_H
#include
#define mcommon_b64_ntop_calculate_target_size COMMON_NAME (b64_ntop_calculate_target_size)
#define mcommon_b64_pton_calculate_target_size COMMON_NAME (b64_pton_calculate_target_size)
#define mcommon_b64_ntop COMMON_NAME (b64_ntop)
#define mcommon_b64_pton COMMON_NAME (b64_pton)
/**
* When encoding from "network" (raw data) to "presentation" (base64 encoded).
* Includes the trailing null byte. */
size_t
mcommon_b64_ntop_calculate_target_size (size_t raw_size);
/* When encoding from "presentation" (base64 encoded) to "network" (raw data).
* This may be an overestimate if the base64 data includes spaces. For a more
* accurate size, call b64_pton (src, NULL, 0), which will read the src
* data and return an exact size. */
size_t
mcommon_b64_pton_calculate_target_size (size_t base64_encoded_size);
/* Returns the number of bytes written (excluding NULL byte) to target on
* success or -1 on error. Adds a trailing NULL byte.
* Encodes from "network" (raw data) to "presentation" (base64 encoded),
* hence the obscure name "ntop".
*/
int
mcommon_b64_ntop (uint8_t const *src, size_t srclength, char *target, size_t targsize);
/** If target is not NULL, the number of bytes written to target on success or
* -1 on error. If target is NULL, returns the exact number of bytes that would
* be written to target on decoding. Encodes from "presentation" (base64
* encoded) to "network" (raw data), hence the obscure name "pton".
*/
int
mcommon_b64_pton (char const *src, uint8_t *target, size_t targsize);
#endif /* MONGO_C_DRIVER_COMMON_B64_PRIVATE_H */
mongodb-2.1.0/src/libmongoc/src/common/src/common-b64.c 0000644 0001751 0000166 00000045246 15014033047 017523 0 ustar /*
* Copyright (c) 1996, 1998 by Internet Software Consortium.
*
* Permission to use, copy, modify, and distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS
* ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE
* CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
* DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
* PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
* ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
* SOFTWARE.
*/
/*
* Portions Copyright (c) 1995 by International Business Machines, Inc.
*
* International Business Machines, Inc. (hereinafter called IBM) grants
* permission under its copyrights to use, copy, modify, and distribute this
* Software with or without fee, provided that the above copyright notice and
* all paragraphs of this notice appear in all copies, and that the name of IBM
* not be used in connection with the marketing of any product incorporating
* the Software or modifications thereof, without specific, written prior
* permission.
*
* To the extent it has a right to do so, IBM grants an immunity from suit
* under its patents, if any, for the use, sale or manufacture of products to
* the extent that such products are used for performing Domain Name System
* dynamic updates in TCP/IP networks by means of the Software. No immunity is
* granted for any product per se or for any other function of any product.
*
* THE SOFTWARE IS PROVIDED "AS IS", AND IBM DISCLAIMS ALL WARRANTIES,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL IBM BE LIABLE FOR ANY SPECIAL,
* DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER ARISING
* OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE, EVEN
* IF IBM IS APPRISED OF THE POSSIBILITY OF SUCH DAMAGES.
*/
#include
#include
#define Assert(Cond) \
if (!(Cond)) \
abort ()
static const char Base64[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
static const char Pad64 = '=';
/* (From RFC1521 and draft-ietf-dnssec-secext-03.txt)
* The following encoding technique is taken from RFC 1521 by Borenstein
* and Freed. It is reproduced here in a slightly edited form for
* convenience.
*
* A 65-character subset of US-ASCII is used, enabling 6 bits to be
* represented per printable character. (The extra 65th character, "=",
* is used to signify a special processing function.)
*
* The encoding process represents 24-bit groups of input bits as output
* strings of 4 encoded characters. Proceeding from left to right, a
* 24-bit input group is formed by concatenating 3 8-bit input groups.
* These 24 bits are then treated as 4 concatenated 6-bit groups, each
* of which is translated into a single digit in the base64 alphabet.
*
* Each 6-bit group is used as an index into an array of 64 printable
* characters. The character referenced by the index is placed in the
* output string.
*
* Table 1: The Base64 Alphabet
*
* Value Encoding Value Encoding Value Encoding Value Encoding
* 0 A 17 R 34 i 51 z
* 1 B 18 S 35 j 52 0
* 2 C 19 T 36 k 53 1
* 3 D 20 U 37 l 54 2
* 4 E 21 V 38 m 55 3
* 5 F 22 W 39 n 56 4
* 6 G 23 X 40 o 57 5
* 7 H 24 Y 41 p 58 6
* 8 I 25 Z 42 q 59 7
* 9 J 26 a 43 r 60 8
* 10 K 27 b 44 s 61 9
* 11 L 28 c 45 t 62 +
* 12 M 29 d 46 u 63 /
* 13 N 30 e 47 v
* 14 O 31 f 48 w (pad) =
* 15 P 32 g 49 x
* 16 Q 33 h 50 y
*
* Special processing is performed if fewer than 24 bits are available
* at the end of the data being encoded. A full encoding quantum is
* always completed at the end of a quantity. When fewer than 24 input
* bits are available in an input group, zero bits are added (on the
* right) to form an integral number of 6-bit groups. Padding at the
* end of the data is performed using the '=' character.
*
* Since all base64 input is an integral number of octets, only the
* following cases can arise:
*
* (1) the final quantum of encoding input is an integral
* multiple of 24 bits; here, the final unit of encoded
* output will be an integral multiple of 4 characters
* with no "=" padding,
* (2) the final quantum of encoding input is exactly 8 bits;
* here, the final unit of encoded output will be two
* characters followed by two "=" padding characters, or
* (3) the final quantum of encoding input is exactly 16 bits;
* here, the final unit of encoded output will be three
* characters followed by one "=" padding character.
*/
int
mcommon_b64_ntop (uint8_t const *src, size_t srclength, char *target, size_t targsize)
{
size_t datalength = 0;
uint8_t input[3];
uint8_t output[4];
size_t i;
if (!target) {
return -1;
}
while (2 < srclength) {
input[0] = *src++;
input[1] = *src++;
input[2] = *src++;
srclength -= 3;
output[0] = input[0] >> 2;
output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4);
output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6);
output[3] = input[2] & 0x3f;
Assert (output[0] < 64);
Assert (output[1] < 64);
Assert (output[2] < 64);
Assert (output[3] < 64);
if (datalength + 4 > targsize) {
return -1;
}
target[datalength++] = Base64[output[0]];
target[datalength++] = Base64[output[1]];
target[datalength++] = Base64[output[2]];
target[datalength++] = Base64[output[3]];
}
/* Now we worry about padding. */
if (0 != srclength) {
/* Get what's left. */
input[0] = input[1] = input[2] = '\0';
for (i = 0; i < srclength; i++) {
input[i] = *src++;
}
output[0] = input[0] >> 2;
output[1] = ((input[0] & 0x03) << 4) + (input[1] >> 4);
output[2] = ((input[1] & 0x0f) << 2) + (input[2] >> 6);
Assert (output[0] < 64);
Assert (output[1] < 64);
Assert (output[2] < 64);
if (datalength + 4 > targsize) {
return -1;
}
target[datalength++] = Base64[output[0]];
target[datalength++] = Base64[output[1]];
if (srclength == 1) {
target[datalength++] = Pad64;
} else {
target[datalength++] = Base64[output[2]];
}
target[datalength++] = Pad64;
}
if (datalength >= targsize) {
return -1;
}
target[datalength] = '\0'; /* Returned value doesn't count \0. */
return (int) datalength;
}
/* (From RFC1521 and draft-ietf-dnssec-secext-03.txt)
The following encoding technique is taken from RFC 1521 by Borenstein
and Freed. It is reproduced here in a slightly edited form for
convenience.
A 65-character subset of US-ASCII is used, enabling 6 bits to be
represented per printable character. (The extra 65th character, "=",
is used to signify a special processing function.)
The encoding process represents 24-bit groups of input bits as output
strings of 4 encoded characters. Proceeding from left to right, a
24-bit input group is formed by concatenating 3 8-bit input groups.
These 24 bits are then treated as 4 concatenated 6-bit groups, each
of which is translated into a single digit in the base64 alphabet.
Each 6-bit group is used as an index into an array of 64 printable
characters. The character referenced by the index is placed in the
output string.
Table 1: The Base64 Alphabet
Value Encoding Value Encoding Value Encoding Value Encoding
0 A 17 R 34 i 51 z
1 B 18 S 35 j 52 0
2 C 19 T 36 k 53 1
3 D 20 U 37 l 54 2
4 E 21 V 38 m 55 3
5 F 22 W 39 n 56 4
6 G 23 X 40 o 57 5
7 H 24 Y 41 p 58 6
8 I 25 Z 42 q 59 7
9 J 26 a 43 r 60 8
10 K 27 b 44 s 61 9
11 L 28 c 45 t 62 +
12 M 29 d 46 u 63 /
13 N 30 e 47 v
14 O 31 f 48 w (pad) =
15 P 32 g 49 x
16 Q 33 h 50 y
Special processing is performed if fewer than 24 bits are available
at the end of the data being encoded. A full encoding quantum is
always completed at the end of a quantity. When fewer than 24 input
bits are available in an input group, zero bits are added (on the
right) to form an integral number of 6-bit groups. Padding at the
end of the data is performed using the '=' character.
Since all base64 input is an integral number of octets, only the
following cases can arise:
(1) the final quantum of encoding input is an integral
multiple of 24 bits; here, the final unit of encoded
output will be an integral multiple of 4 characters
with no "=" padding,
(2) the final quantum of encoding input is exactly 8 bits;
here, the final unit of encoded output will be two
characters followed by two "=" padding characters, or
(3) the final quantum of encoding input is exactly 16 bits;
here, the final unit of encoded output will be three
characters followed by one "=" padding character.
*/
/* skips all whitespace anywhere.
converts characters, four at a time, starting at (or after)
src from base - 64 numbers into three 8 bit bytes in the target area.
it returns the number of data bytes stored at the target, or -1 on error.
*/
static uint8_t mongoc_b64rmap[256];
static const uint8_t mongoc_b64rmap_special = 0xf0;
static const uint8_t mongoc_b64rmap_end = 0xfd;
static const uint8_t mongoc_b64rmap_space = 0xfe;
static const uint8_t mongoc_b64rmap_invalid = 0xff;
/* initializing the reverse map isn't thread safe, do it in pthread_once */
#if defined(BSON_OS_UNIX)
#include
#define mongoc_common_once_t pthread_once_t
#define mongoc_common_once pthread_once
#define MONGOC_COMMON_ONCE_FUN(n) void n (void)
#define MONGOC_COMMON_ONCE_RETURN return
#define MONGOC_COMMON_ONCE_INIT PTHREAD_ONCE_INIT
#else
#define mongoc_common_once_t INIT_ONCE
#define MONGOC_COMMON_ONCE_INIT INIT_ONCE_STATIC_INIT
#define mongoc_common_once(o, c) InitOnceExecuteOnce (o, c, NULL, NULL)
#define MONGOC_COMMON_ONCE_FUN(n) BOOL CALLBACK n (PINIT_ONCE _ignored_a, PVOID _ignored_b, PVOID *_ignored_c)
#define MONGOC_COMMON_ONCE_RETURN return true
#endif
static MONGOC_COMMON_ONCE_FUN (bson_b64_initialize_rmap)
{
int i;
unsigned char ch;
/* Null: end of string, stop parsing */
mongoc_b64rmap[0] = mongoc_b64rmap_end;
for (i = 1; i < 256; ++i) {
ch = (unsigned char) i;
/* Whitespaces */
if (bson_isspace (ch))
mongoc_b64rmap[i] = mongoc_b64rmap_space;
/* Padding: stop parsing */
else if (ch == Pad64)
mongoc_b64rmap[i] = mongoc_b64rmap_end;
/* Non-base64 char */
else
mongoc_b64rmap[i] = mongoc_b64rmap_invalid;
}
/* Fill reverse mapping for base64 chars */
for (i = 0; Base64[i] != '\0'; ++i)
mongoc_b64rmap[(uint8_t) Base64[i]] = i;
MONGOC_COMMON_ONCE_RETURN;
}
static int
mongoc_b64_pton_do (char const *src, uint8_t *target, size_t targsize)
{
int tarindex, state;
uint8_t ch, ofs;
state = 0;
tarindex = 0;
while (1) {
ch = *src++;
ofs = mongoc_b64rmap[ch];
if (ofs >= mongoc_b64rmap_special) {
/* Ignore whitespaces */
if (ofs == mongoc_b64rmap_space)
continue;
/* End of base64 characters */
if (ofs == mongoc_b64rmap_end)
break;
/* A non-base64 character. */
return (-1);
}
switch (state) {
case 0:
if ((size_t) tarindex >= targsize)
return (-1);
target[tarindex] = ofs << 2;
state = 1;
break;
case 1:
if ((size_t) tarindex + 1 >= targsize)
return (-1);
target[tarindex] |= ofs >> 4;
target[tarindex + 1] = (ofs & 0x0f) << 4;
tarindex++;
state = 2;
break;
case 2:
if ((size_t) tarindex + 1 >= targsize)
return (-1);
target[tarindex] |= ofs >> 2;
target[tarindex + 1] = (ofs & 0x03) << 6;
tarindex++;
state = 3;
break;
case 3:
if ((size_t) tarindex >= targsize)
return (-1);
target[tarindex] |= ofs;
tarindex++;
state = 0;
break;
default:
abort ();
}
}
/*
* We are done decoding Base-64 chars. Let's see if we ended
* on a byte boundary, and/or with erroneous trailing characters.
*/
if (ch == Pad64) { /* We got a pad char. */
ch = *src++; /* Skip it, get next. */
switch (state) {
case 0: /* Invalid = in first position */
case 1: /* Invalid = in second position */
return (-1);
case 2: /* Valid, means one byte of info */
/* Skip any number of spaces. */
for ((void) NULL; ch != '\0'; ch = *src++)
if (mongoc_b64rmap[ch] != mongoc_b64rmap_space)
break;
/* Make sure there is another trailing = sign. */
if (ch != Pad64)
return (-1);
ch = *src++; /* Skip the = */
/* Fall through to "single trailing =" case. */
/* FALLTHROUGH */
case 3: /* Valid, means two bytes of info */
/*
* We know this char is an =. Is there anything but
* whitespace after it?
*/
for ((void) NULL; ch != '\0'; ch = *src++)
if (mongoc_b64rmap[ch] != mongoc_b64rmap_space)
return (-1);
/*
* Now make sure for cases 2 and 3 that the "extra"
* bits that slopped past the last full byte were
* zeros. If we don't check them, they become a
* subliminal channel.
*/
if (target[tarindex] != 0)
return (-1);
default:
break;
}
} else {
/*
* We ended by seeing the end of the string. Make sure we
* have no partial bytes lying around.
*/
if (state != 0)
return (-1);
}
return (tarindex);
}
static int
mongoc_b64_pton_len (char const *src)
{
int tarindex, state;
uint8_t ch, ofs;
state = 0;
tarindex = 0;
while (1) {
ch = *src++;
ofs = mongoc_b64rmap[ch];
if (ofs >= mongoc_b64rmap_special) {
/* Ignore whitespaces */
if (ofs == mongoc_b64rmap_space)
continue;
/* End of base64 characters */
if (ofs == mongoc_b64rmap_end)
break;
/* A non-base64 character. */
return (-1);
}
switch (state) {
case 0:
state = 1;
break;
case 1:
tarindex++;
state = 2;
break;
case 2:
tarindex++;
state = 3;
break;
case 3:
tarindex++;
state = 0;
break;
default:
abort ();
}
}
/*
* We are done decoding Base-64 chars. Let's see if we ended
* on a byte boundary, and/or with erroneous trailing characters.
*/
if (ch == Pad64) { /* We got a pad char. */
ch = *src++; /* Skip it, get next. */
switch (state) {
case 0: /* Invalid = in first position */
case 1: /* Invalid = in second position */
return (-1);
case 2: /* Valid, means one byte of info */
/* Skip any number of spaces. */
for ((void) NULL; ch != '\0'; ch = *src++)
if (mongoc_b64rmap[ch] != mongoc_b64rmap_space)
break;
/* Make sure there is another trailing = sign. */
if (ch != Pad64)
return (-1);
ch = *src++; /* Skip the = */
/* Fall through to "single trailing =" case. */
/* FALLTHROUGH */
case 3: /* Valid, means two bytes of info */
/*
* We know this char is an =. Is there anything but
* whitespace after it?
*/
for ((void) NULL; ch != '\0'; ch = *src++)
if (mongoc_b64rmap[ch] != mongoc_b64rmap_space)
return (-1);
default:
break;
}
} else {
/*
* We ended by seeing the end of the string. Make sure we
* have no partial bytes lying around.
*/
if (state != 0)
return (-1);
}
return (tarindex);
}
int
mcommon_b64_pton (char const *src, uint8_t *target, size_t targsize)
{
static mongoc_common_once_t once = MONGOC_COMMON_ONCE_INIT;
mongoc_common_once (&once, bson_b64_initialize_rmap);
if (!src) {
return -1;
}
if (target)
return mongoc_b64_pton_do (src, target, targsize);
else
return mongoc_b64_pton_len (src);
}
size_t
mcommon_b64_ntop_calculate_target_size (size_t raw_size)
{
size_t num_bits = raw_size * 8;
/* Calculate how many groups of six bits this contains, adding 5 to round up
* to the nearest group of 6. */
size_t num_b64_chars = (num_bits + 5) / 6;
/* Round to nearest set of four. */
size_t num_b64_chars_with_padding = 4 * ((num_b64_chars + 3) / 4);
/* Add one for NULL byte. */
return num_b64_chars_with_padding + 1;
}
size_t
mcommon_b64_pton_calculate_target_size (size_t base64_encoded_size)
{
/* Without inspecting the data, we don't know how many padding characters
* there are. Assuming none, that means each character represents 6 bits of
* data. */
size_t num_bits = base64_encoded_size * 6;
/* Round down to the nearest group of eight. */
return num_bits / 8;
}
mongodb-2.1.0/src/libmongoc/src/common/src/common-bits-private.h 0000644 0001751 0000166 00000002331 15014033047 021532 0 ustar /*
* Copyright 2009-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#ifndef MONGO_C_DRIVER_COMMON_BITS_PRIVATE_H
#define MONGO_C_DRIVER_COMMON_BITS_PRIVATE_H
#include
// Round up to the next power of two uint32_t value. Saturates on overflow.
static BSON_INLINE uint32_t
mcommon_next_power_of_two_u32 (uint32_t v)
{
if (v == 0) {
return 1;
}
// https://graphics.stanford.edu/%7Eseander/bithacks.html#RoundUpPowerOf2
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
if (v == 0) {
return UINT32_MAX;
} else {
return v;
}
}
#endif /* MONGO_C_DRIVER_COMMON_BITS_PRIVATE_H */
mongodb-2.1.0/src/libmongoc/src/common/src/common-bson-dsl-private.h 0000644 0001751 0000166 00000201206 15014033047 022314 0 ustar #include
#ifndef MONGO_C_DRIVER_COMMON_BSON_DSL_PRIVATE_H
#define MONGO_C_DRIVER_COMMON_BSON_DSL_PRIVATE_H
/**
* @file common-bson-dsl-private.h
* @brief Define a C-preprocessor DSL for working with BSON objects
*
* This file defines an embedded DSL for working with BSON objects consisely and
* correctly.
*
* For more information about using this DSL, refer to `bson-dsl.md`.
*/
#include
#include
enum {
/// Toggle this value to enable/disable debug output for all bsonDSL
/// operations (printed to stderr). You can also set a constant
/// BSON_DSL_DEBUG within the scope of a DSL command to selectively debug
/// only the commands within that scope.
BSON_DSL_DEBUG = 0
};
#define _bson_thread_local BSON_IF_GNU_LIKE (__thread) BSON_IF_MSVC (__declspec (thread))
#define _bson_comdat \
BSON_IF_WINDOWS (__declspec (selectany)) \
BSON_IF_POSIX (__attribute__ ((weak)))
#ifdef __GNUC__
// GCC has a bug handling pragma statements that disable warnings within complex
// nested macro expansions. If we're GCC, just disable -Wshadow outright:
BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic ignored \"-Wshadow\""))
#endif
#define _bsonDSL_disableWarnings() \
if (1) { \
BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic push");) \
BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic ignored \"-Wshadow\"");) \
} else \
((void) 0)
#define _bsonDSL_restoreWarnings() \
if (1) { \
BSON_IF_GNU_LIKE (_Pragma ("GCC diagnostic pop");) \
} else \
((void) 0)
/**
* @brief Parse the given BSON document.
*
* @param doc A bson_t object to walk. (Not a pointer)
*/
#define bsonParse(Document, ...) \
_bsonDSL_begin ("bsonParse(%s)", _bsonDSL_str (Document)); \
_bsonDSL_disableWarnings (); \
bsonParseError = NULL; \
BSON_MAYBE_UNUSED bool _bvHalt = false; \
BSON_MAYBE_UNUSED const bool _bvContinue = false; \
BSON_MAYBE_UNUSED const bool _bvBreak = false; \
_bsonDSL_eval (_bsonParse ((Document), __VA_ARGS__)); \
_bsonDSL_restoreWarnings (); \
_bsonDSL_end
/**
* @brief Visit each element of a BSON document
*/
#define bsonVisitEach(Document, ...) \
_bsonDSL_begin ("bsonVisitEach(%s)", _bsonDSL_str (Document)); \
_bsonDSL_disableWarnings (); \
BSON_MAYBE_UNUSED bool _bvHalt = false; \
_bsonDSL_eval (_bsonVisitEach ((Document), __VA_ARGS__)); \
_bsonDSL_restoreWarnings (); \
_bsonDSL_end
#define bsonBuildContext (*_bsonBuildContextThreadLocalPtr)
#define bsonVisitContext (*_bsonVisitContextThreadLocalPtr)
#define bsonVisitIter (bsonVisitContext.iter)
/// Begin any function-like macro by opening a new scope and writing a debug
/// message.
#define _bsonDSL_begin(Str, ...) \
if (true) { \
_bsonDSLDebug (Str, __VA_ARGS__); \
++_bson_dsl_indent
/// End a function-like macro scope.
#define _bsonDSL_end \
--_bson_dsl_indent; \
} \
else ((void) 0)
/**
* @brief Expands to a call to bson_append_{Kind}, with the three first
* arguments filled in by the DSL context variables.
*/
#define _bsonBuildAppendArgs bsonBuildContext.doc, bsonBuildContext.key, bsonBuildContext.key_len
/**
* The _bsonDocOperation_XYZ macros handle the top-level bsonBuild()
* items, and any nested doc() items, with XYZ being the doc-building
* subcommand.
*/
#define _bsonDocOperation(Command, _ignore, _count) \
if (!bsonBuildError) { \
_bsonDocOperation_##Command; \
if (bsonBuildError) { \
_bsonDSLDebug ("Stopping doc() due to bsonBuildError: [%s]", bsonBuildError); \
} \
}
#define _bsonValueOperation(P) _bsonValueOperation_##P
/// key-value pair with explicit key length
#define _bsonDocOperation_kvl(String, Len, Element) \
_bsonDSL_begin ("\"%s\" => [%s]", String, _bsonDSL_strElide (30, Element)); \
const char *_bbString = (String); \
const uint64_t length = (Len); \
if (mcommon_in_range_unsigned (int, length)) { \
_bbCtx.key = _bbString; \
_bbCtx.key_len = (int) length; \
_bsonValueOperation (Element); \
} else { \
bsonBuildError = "Out-of-range key string length value"; \
} \
_bsonDSL_end
/// Key-value pair with a C-string
#define _bsonDocOperation_kv(String, Element) _bsonDocOperation_kvl ((String), strlen ((String)), Element)
/// Execute arbitrary code
#define _bsonDocOperation_do(...) \
_bsonDSL_begin ("do(%s)", _bsonDSL_strElide (30, __VA_ARGS__)); \
do { \
__VA_ARGS__; \
} while (0); \
if (bsonBuildError) { \
_bsonDSLDebug ("do() set bsonBuildError: [%s]", bsonBuildError); \
} \
_bsonDSL_end
/// We must defer expansion of the nested doc() to allow "recursive" evaluation
#define _bsonValueOperation_doc _bsonValueOperationDeferred_doc _bsonDSL_nothing ()
#define _bsonArrayOperation_doc(...) _bsonArrayAppendValue (doc (__VA_ARGS__))
#define _bsonValueOperationDeferred_doc(...) \
_bsonDSL_begin ("doc(%s)", _bsonDSL_strElide (30, __VA_ARGS__)); \
/* Write to this variable as the child: */ \
bson_t _bbChildDoc = BSON_INITIALIZER; \
if (!bson_append_document_begin (_bsonBuildAppendArgs, &_bbChildDoc)) { \
bsonBuildError = "Error while initializing child document: " _bsonDSL_str (__VA_ARGS__); \
} else { \
_bsonBuildAppend (_bbChildDoc, __VA_ARGS__); \
if (!bsonBuildError) { \
if (!bson_append_document_end (bsonBuildContext.doc, &_bbChildDoc)) { \
bsonBuildError = "Error while finalizing document: " _bsonDSL_str (__VA_ARGS__); \
} \
} \
} \
_bsonDSL_end
/// We must defer expansion of the nested array() to allow "recursive"
/// evaluation
#define _bsonValueOperation_array _bsonValueOperationDeferred_array _bsonDSL_nothing ()
#define _bsonArrayOperation_array(...) _bsonArrayAppendValue (array (__VA_ARGS__))
#define _bsonValueOperationDeferred_array(...) \
_bsonDSL_begin ("array(%s)", _bsonDSL_strElide (30, __VA_ARGS__)); \
/* Write to this variable as the child array: */ \
bson_t _bbArray = BSON_INITIALIZER; \
if (!bson_append_array_begin (_bsonBuildAppendArgs, &_bbArray)) { \
bsonBuildError = "Error while initializing child array: " _bsonDSL_str (__VA_ARGS__); \
} else { \
_bsonBuildArray (_bbArray, __VA_ARGS__); \
if (!bsonBuildError) { \
if (!bson_append_array_end (bsonBuildContext.doc, &_bbArray)) { \
bsonBuildError = "Error while finalizing child array: " _bsonDSL_str (__VA_ARGS__); \
} \
} else { \
_bsonDSLDebug ("Got bsonBuildError: [%s]", bsonBuildError); \
} \
} \
_bsonDSL_end
/// Append a UTF-8 string with an explicit length
#define _bsonValueOperation_utf8_w_len(String, Len) \
if (!bson_append_utf8 (_bsonBuildAppendArgs, (String), (int) (Len))) { \
bsonBuildError = "Error while appending utf8 string: " _bsonDSL_str (String); \
} else \
((void) 0)
#define _bsonArrayOperation_utf8_w_len(X) _bsonArrayAppendValue (utf8_w_len (X))
/// Append a "cstr" as UTF-8
#define _bsonValueOperation_cstr(String) _bsonValueOperation_utf8_w_len ((String), strlen (String))
#define _bsonArrayOperation_cstr(X) _bsonArrayAppendValue (cstr (X))
/// Append an int32
#define _bsonValueOperation_int32(Integer) \
if (!bson_append_int32 (_bsonBuildAppendArgs, (Integer))) { \
bsonBuildError = "Error while appending int32(" _bsonDSL_str (Integer) ")"; \
} else \
((void) 0)
#define _bsonArrayOperation_int32(X) _bsonArrayAppendValue (int32 (X))
/// Append an int64
#define _bsonValueOperation_int64(Integer) \
if (!bson_append_int64 (_bsonBuildAppendArgs, (Integer))) { \
bsonBuildError = "Error while appending int64(" _bsonDSL_str (Integer) ")"; \
} else \
((void) 0)
#define _bsonArrayOperation_int64(X) _bsonArrayAppendValue (int64 (X))
/// Append the value referenced by a given iterator
#define _bsonValueOperation_iterValue(Iter) \
if (!bson_append_iter (_bsonBuildAppendArgs, &(Iter))) { \
bsonBuildError = "Error while appending iterValue(" _bsonDSL_str (Iter) ")"; \
} else \
((void) 0)
#define _bsonArrayOperation_iterValue(X) _bsonArrayAppendValue (iterValue (X))
/// Append the BSON document referenced by the given pointer
#define _bsonValueOperation_bson(Doc) \
if (!bson_append_document (_bsonBuildAppendArgs, &(Doc))) { \
bsonBuildError = "Error while appending subdocument: bson(" _bsonDSL_str (Doc) ")"; \
} else \
((void) 0)
#define _bsonArrayOperation_bson(X) _bsonArrayAppendValue (bson (X))
/// Append the BSON document referenced by the given pointer as an array
#define _bsonValueOperation_bsonArray(Arr) \
if (!bson_append_array (_bsonBuildAppendArgs, &(Arr))) { \
bsonBuildError = "Error while appending subdocument array: " \
"bsonArray(" _bsonDSL_str (Arr) ")"; \
} else \
((void) 0)
#define _bsonArrayOperation_bsonArray(X) _bsonArrayAppendValue (bsonArray (X))
#define _bsonValueOperation_bool(b) \
if (!bson_append_bool (_bsonBuildAppendArgs, (b))) { \
bsonBuildError = "Error while appending bool(" _bsonDSL_str (b) ")"; \
} else \
((void) 0)
#define _bsonArrayOperation_boolean(X) _bsonArrayAppendValue (boolean (X))
#define _bsonValueOperation_boolean(b) _bsonValueOperation_bool (b)
#define _bsonValueOperation_oid(o) \
if (!bson_append_oid (_bsonBuildAppendArgs, (o))) { \
bsonBuildError = "Error while appending oid(" _bsonDSL_str (o) ")"; \
} else \
((void) 0)
#define _bsonArrayOperation_oid(X) _bsonArrayAppendValue (oid (X))
#define _bsonValueOperation_null \
if (!bson_append_null (_bsonBuildAppendArgs)) { \
bsonBuildError = "Error while appending a null"; \
} else \
((void) 0)
#define _bsonArrayOperation_null _bsonValueOperation (null)
#define _bsonArrayOperation_value(X) _bsonArrayAppendValue (value (X))
#define _bsonValueOperation_value(Value) \
_bsonDSL_begin ("value(%s)", _bsonDSL_str (Value)); \
if (!bson_append_value (_bsonBuildAppendArgs, &(Value))) { \
bsonBuildError = "Error while appending value(" _bsonDSL_str (Value) ")"; \
} \
_bsonDSL_end
/// Insert the given BSON document into the parent document in-place
#define _bsonDocOperation_insert(OtherBSON, Pred) \
_bsonDSL_begin ("Insert other document: [%s]", _bsonDSL_str (OtherBSON)); \
const bool _bvHalt = false; /* Required for _bsonVisitEach() */ \
_bsonVisitEach (OtherBSON, if (Pred, then (do (_bsonDocOperation_iterElement (bsonVisitIter))))); \
_bsonDSL_end
#define _bsonDocOperation_insertFromIter(Iter, Pred) \
_bsonDSL_begin ("Insert document from iterator: [%s]", _bsonDSL_str (Iter)); \
bson_t _bbDocFromIter = _bson_dsl_iter_as_doc (&(Iter)); \
if (_bbDocFromIter.len == 0) { \
_bsonDSLDebug ("NOTE: Skipping insert of non-document value from iterator"); \
} else { \
_bsonDocOperation_insert (_bbDocFromIter, Pred); \
} \
_bsonDSL_end
#define _bsonDocOperation_iterElement(Iter) \
_bsonDSL_begin ("Insert element from bson_iter_t [%s]", _bsonDSL_str (Iter)); \
bson_iter_t _bbIter = (Iter); \
_bsonDocOperation_kvl (bson_iter_key (&_bbIter), bson_iter_key_len (&_bbIter), iterValue (_bbIter)); \
_bsonDSL_end
/// Insert the given BSON document into the parent array. Keys of the given
/// document are discarded and it is treated as an array of values.
#define _bsonArrayOperation_insert(OtherArr, Pred) \
_bsonDSL_begin ("Insert other array: [%s]", _bsonDSL_str (OtherArr)); \
_bsonVisitEach (OtherArr, if (Pred, then (do (_bsonArrayOperation_iterValue (bsonVisitIter))))); \
_bsonDSL_end
#define _bsonArrayAppendValue(ValueOperation) \
_bsonDSL_begin ("[%d] => [%s]", (int) bsonBuildContext.index, _bsonDSL_strElide (30, ValueOperation)); \
/* Set the doc key to the array index as a string: */ \
_bsonBuild_setKeyToArrayIndex (bsonBuildContext.index); \
/* Append a value: */ \
_bsonValueOperation_##ValueOperation; \
/* Increment the array index: */ \
++_bbCtx.index; \
_bsonDSL_end
#define _bsonDocOperationIfThen_then _bsonBuildAppendWithCurrentContext
#define _bsonDocOperationIfElse_else _bsonBuildAppendWithCurrentContext
#define _bsonDocOperationIfThenElse(Condition, Then, Else) \
if ((Condition)) { \
_bsonDSLDebug ("Taking TRUE branch: [%s]", _bsonDSL_str (Then)); \
_bsonDocOperationIfThen_##Then; \
} else { \
_bsonDSLDebug ("Taking FALSE branch: [%s]", _bsonDSL_str (Else)); \
_bsonDocOperationIfElse_##Else; \
}
#define _bsonDocOperationIfThen(Condition, Then) \
if ((Condition)) { \
_bsonDSLDebug ("Taking TRUE branch: [%s]", _bsonDSL_str (Then)); \
_bsonDocOperationIfThen_##Then; \
}
#define _bsonDocOperation_if(Condition, ...) \
_bsonDSL_begin ("Conditional append on [%s]", _bsonDSL_str (Condition)); \
/* Pick a sub-macro depending on if there are one or two args */ \
_bsonDSL_ifElse (_bsonDSL_hasComma (__VA_ARGS__), _bsonDocOperationIfThenElse, _bsonDocOperationIfThen) ( \
Condition, __VA_ARGS__); \
_bsonDSL_end
#define _bsonArrayOperationIfThen_then _bsonBuildArrayWithCurrentContext
#define _bsonArrayOperationIfElse_else _bsonBuildArrayWithCurrentContext
#define _bsonArrayOperationIfThenElse(Condition, Then, Else) \
if ((Condition)) { \
_bsonDSLDebug ("Taking TRUE branch: [%s]", _bsonDSL_str (Then)); \
_bsonArrayOperationIfThen_##Then; \
} else { \
_bsonDSLDebug ("Taking FALSE branch: [%s]", _bsonDSL_str (Else)); \
_bsonArrayOperationIfElse_##Else; \
}
#define _bsonArrayOperationIfThen(Condition, Then) \
if ((Condition)) { \
_bsonDSLDebug ("Taking TRUE branch: [%s]", _bsonDSL_str (Then)); \
_bsonArrayOperationIfThen_##Then; \
}
#define _bsonArrayOperation_if(Condition, ...) \
_bsonDSL_begin ("Conditional value on [%s]", _bsonDSL_str (Condition)); \
/* Pick a sub-macro depending on if there are one or two args */ \
_bsonDSL_ifElse (_bsonDSL_hasComma (__VA_ARGS__), _bsonArrayOperationIfThenElse, _bsonArrayOperationIfThen) ( \
Condition, __VA_ARGS__); \
_bsonDSL_end
#define _bsonValueOperationIf_then(X) _bsonValueOperation_##X
#define _bsonValueOperationIf_else(X) _bsonValueOperation_##X
#define _bsonValueOperation_if(Condition, Then, Else) \
if ((Condition)) { \
_bsonDSLDebug ("Taking TRUE branch: [%s]", _bsonDSL_str (Then)); \
_bsonValueOperationIf_##Then; \
} else { \
_bsonDSLDebug ("Taking FALSE branch: [%s]", _bsonDSL_str (Else)); \
_bsonValueOperationIf_##Else; \
}
#define _bsonBuild_setKeyToArrayIndex(Idx) \
_bbCtx.key_len = bson_snprintf (_bbCtx.index_key_str, sizeof _bbCtx.index_key_str, "%d", (int) _bbCtx.index); \
_bbCtx.key = _bbCtx.index_key_str
/// Handle an element of array()
#define _bsonArrayOperation(Element, _nil, _count) \
if (!bsonBuildError) { \
_bsonArrayOperation_##Element; \
}
#define _bsonBuildAppendWithCurrentContext(...) _bsonDSL_mapMacro (_bsonDocOperation, ~, __VA_ARGS__)
#define _bsonBuildArrayWithCurrentContext(...) _bsonDSL_mapMacro (_bsonArrayOperation, ~, __VA_ARGS__)
#define _bsonDSL_Type_double BSON_TYPE_DOUBLE
#define _bsonDSL_Type_utf8 BSON_TYPE_UTF8
#define _bsonDSL_Type_doc BSON_TYPE_DOCUMENT
#define _bsonDSL_Type_array BSON_TYPE_ARRAY
#define _bsonDSL_Type_binary BSON_TYPE_BINARY
#define _bsonDSL_Type_undefined BSON_TYPE_UNDEFINED
#define _bsonDSL_Type_oid BSON_TYPE_OID
// Use `boolean`, not `bool`. `bool` may be defined as a macro to `_Bool` or `int`:
#define _bsonDSL_Type_boolean BSON_TYPE_BOOL
#define _bsonDSL_Type_date_time BSON_TYPE_DATE_TIME
#define _bsonDSL_Type_null BSON_TYPE_NULL
#define _bsonDSL_Type_regex BSON_TYPE_REGEX
#define _bsonDSL_Type_dbpointer BSON_TYPE_DBPOINTER
#define _bsonDSL_Type_code BSON_TYPE_CODE
#define _bsonDSL_Type_codewscope BSON_TYPE_CODEWSCOPE
#define _bsonDSL_Type_int32 BSON_TYPE_INT32
#define _bsonDSL_Type_timestamp BSON_TYPE_TIMESTAMP
#define _bsonDSL_Type_int64 BSON_TYPE_INT64
#define _bsonDSL_Type_decimal128 BSON_TYPE_DECIMAL128
#define _bsonDSL_Type_string __NOTE__No_type_named__string__did_you_mean__utf8
#define _bsonVisitOperation_halt _bvHalt = true
#define _bsonVisitOperation_if(Predicate, ...) \
_bsonDSL_begin ("if(%s)", _bsonDSL_str (Predicate)); \
_bsonDSL_ifElse (_bsonDSL_hasComma (__VA_ARGS__), _bsonVisit_ifThenElse, _bsonVisit_ifThen) (Predicate, \
__VA_ARGS__); \
_bsonDSL_end
#define _bsonVisit_ifThenElse(Predicate, Then, Else) \
if (bsonPredicate (Predicate)) { \
_bsonDSLDebug ("then:"); \
_bsonVisit_ifThen_##Then; \
} else { \
_bsonDSLDebug ("else:"); \
_bsonVisit_ifElse_##Else; \
}
#define _bsonVisit_ifThen(Predicate, Then) \
if (bsonPredicate (Predicate)) { \
_bsonDSLDebug ("then:"); \
_bsonVisit_ifThen_##Then; \
} else { \
_bsonDSLDebug ("[else nothing]"); \
}
#define _bsonVisit_ifThen_then _bsonVisit_applyOps
#define _bsonVisit_ifElse_else _bsonVisit_applyOps
#define _bsonVisitOperation_storeBool(Dest) \
_bsonDSL_begin ("storeBool(%s)", _bsonDSL_str (Dest)); \
(Dest) = bson_iter_as_bool (&bsonVisitIter); \
_bsonDSL_end
#define _bsonVisitOperation_storeStrRef(Dest) \
_bsonDSL_begin ("storeStrRef(%s)", _bsonDSL_str (Dest)); \
(Dest) = bson_iter_utf8 (&bsonVisitIter, NULL); \
_bsonDSL_end
#define _bsonVisitOperation_storeStrDup(Dest) \
_bsonDSL_begin ("storeStrDup(%s)", _bsonDSL_str (Dest)); \
(Dest) = bson_iter_dup_utf8 (&bsonVisitIter, NULL); \
_bsonDSL_end
#define _bsonVisitOperation_storeDocDup(Dest) \
_bsonDSL_begin ("storeDocDup(%s)", _bsonDSL_str (Dest)); \
bson_t _bvDoc = BSON_INITIALIZER; \
_bson_dsl_iter_as_doc (&_bvDoc, &bsonVisitIter); \
if (_bvDoc.len) { \
bson_copy_to (&_bvDoc, &(Dest)); \
} \
_bsonDSL_end
#define _bsonVisitOperation_storeDocRef(Dest) \
_bsonDSL_begin ("storeDocRef(%s)", _bsonDSL_str (Dest)); \
_bson_dsl_iter_as_doc (&(Dest), &bsonVisitIter); \
_bsonDSL_end
#define _bsonVisitOperation_storeDocDupPtr(Dest) \
_bsonDSL_begin ("storeDocDupPtr(%s)", _bsonDSL_str (Dest)); \
bson_t _bvDoc = BSON_INITIALIZER; \
_bson_dsl_iter_as_doc (&_bvDoc, &bsonVisitIter); \
if (_bvDoc.len) { \
(Dest) = bson_copy (&_bvDoc); \
} \
_bsonDSL_end
#define _bsonVisitOperation_storeInt32(Dest) \
_bsonDSL_begin ("storeInt32(%s)", _bsonDSL_str (Dest)); \
(Dest) = bson_iter_int32 (&bsonVisitIter); \
_bsonDSL_end
#define _bsonVisitOperation_do(...) \
_bsonDSL_begin ("do: %s", _bsonDSL_strElide (30, __VA_ARGS__)); \
do { \
__VA_ARGS__; \
} while (0); \
_bsonDSL_end
#define _bsonVisitOperation_appendTo(BSON) \
_bsonDSL_begin ("appendTo(%s)", _bsonDSL_str (BSON)); \
if (!bson_append_iter ( \
&(BSON), bson_iter_key (&bsonVisitIter), (int) bson_iter_key_len (&bsonVisitIter), &bsonVisitIter)) { \
bsonParseError = "Error in appendTo(" _bsonDSL_str (BSON) ")"; \
} \
_bsonDSL_end
#define _bsonVisitCase_when(Pred, ...) \
_bsonDSL_begin ("when: [%s]", _bsonDSL_str (Pred)); \
_bvCaseMatched = _bsonPredicate (Pred); \
if (_bvCaseMatched) { \
_bsonVisit_applyOps (__VA_ARGS__); \
} \
_bsonDSL_end
#define _bsonVisitCase_else(...) \
_bsonDSL_begin ("else:%s", ""); \
_bvCaseMatched = true; \
_bsonVisit_applyOps (__VA_ARGS__); \
_bsonDSL_end
#define _bsonVisitCase(Pair, _nil, _count) \
if (!_bvCaseMatched) { \
_bsonVisitCase_##Pair; \
} else \
((void) 0);
#define _bsonVisitOperation_case(...) \
_bsonDSL_begin ("case:%s", ""); \
BSON_MAYBE_UNUSED bool _bvCaseMatched = false; \
_bsonDSL_mapMacro (_bsonVisitCase, ~, __VA_ARGS__); \
_bsonDSL_end
#define _bsonVisitOperation_append _bsonVisitOneApplyDeferred_append _bsonDSL_nothing ()
#define _bsonVisitOneApplyDeferred_append(Doc, ...) \
_bsonDSL_begin ("append to [%s] : %s", _bsonDSL_str (Doc), _bsonDSL_strElide (30, __VA_ARGS__)); \
_bsonBuildAppend (Doc, __VA_ARGS__); \
if (bsonBuildError) { \
bsonParseError = bsonBuildError; \
} \
_bsonDSL_end
#define _bsonVisitEach(Doc, ...) \
_bsonDSL_begin ("visitEach(%s)", _bsonDSL_str (Doc)); \
do { \
/* Reset the context */ \
struct _bsonVisitContext_t _bvCtx = { \
.doc = &(Doc), \
.parent = _bsonVisitContextThreadLocalPtr, \
.index = 0, \
}; \
_bsonVisitContextThreadLocalPtr = &_bvCtx; \
bsonParseError = NULL; \
/* Iterate over each element of the document */ \
if (!bson_iter_init (&_bvCtx.iter, &(Doc))) { \
bsonParseError = "Invalid BSON data [a]"; \
} \
BSON_MAYBE_UNUSED bool _bvBreak = false; \
BSON_MAYBE_UNUSED bool _bvContinue = false; \
while (bson_iter_next (&_bvCtx.iter) && !_bvHalt && !bsonParseError && !_bvBreak) { \
_bvContinue = false; \
_bsonVisit_applyOps (__VA_ARGS__); \
++_bvCtx.index; \
} \
if (bsonVisitIter.err_off) { \
bsonParseError = "Invalid BSON data [b]"; \
} \
/* Restore the dsl context */ \
_bsonVisitContextThreadLocalPtr = _bvCtx.parent; \
} while (0); \
_bsonDSL_end
#define _bsonVisitOperation_visitEach _bsonVisitOperation_visitEachDeferred _bsonDSL_nothing ()
#define _bsonVisitOperation_visitEachDeferred(...) \
_bsonDSL_begin ("visitEach:%s", ""); \
do { \
const uint8_t *data; \
uint32_t len; \
bson_type_t typ = bson_iter_type_unsafe (&bsonVisitIter); \
if (typ == BSON_TYPE_ARRAY) \
bson_iter_array (&bsonVisitIter, &len, &data); \
else if (typ == BSON_TYPE_DOCUMENT) \
bson_iter_document (&bsonVisitIter, &len, &data); \
else { \
_bsonDSLDebug ("(Skipping visitEach() of non-array/document value)"); \
break; \
} \
bson_t inner; \
BSON_ASSERT (bson_init_static (&inner, data, len)); \
_bsonVisitEach (inner, __VA_ARGS__); \
} while (0); \
_bsonDSL_end
#define _bsonVisitOperation_nop _bsonDSLDebug ("[nop]")
#define _bsonVisitOperation_parse(...) \
do { \
const uint8_t *data; \
uint32_t len; \
bson_type_t typ = bson_iter_type (&bsonVisitIter); \
if (typ == BSON_TYPE_ARRAY) \
bson_iter_array (&bsonVisitIter, &len, &data); \
else if (typ == BSON_TYPE_DOCUMENT) \
bson_iter_document (&bsonVisitIter, &len, &data); \
else { \
_bsonDSLDebug ("Ignoring parse() for non-document/array value"); \
break; \
} \
bson_t inner; \
BSON_ASSERT (bson_init_static (&inner, data, len)); \
_bsonParse (inner, __VA_ARGS__); \
} while (0);
#define _bsonVisitOperation_continue _bvContinue = true
#define _bsonVisitOperation_break _bvBreak = _bvContinue = true
#define _bsonVisitOperation_require(Predicate) \
_bsonDSL_begin ("require(%s)", _bsonDSL_str (Predicate)); \
if (!bsonPredicate (Predicate)) { \
bsonParseError = "Element requirement failed: " _bsonDSL_str (Predicate); \
} \
_bsonDSL_end
#define _bsonVisitOperation_error(S) bsonParseError = (S)
#define _bsonVisitOperation_errorf(S, ...) (bsonParseError = _bson_dsl_errorf (&(S), __VA_ARGS__))
#define _bsonVisitOperation_dupPath(S) \
_bsonDSL_begin ("dupPath(%s)", _bsonDSL_str (S)); \
_bson_dsl_dupPath (&(S)); \
_bsonDSL_end
#define _bsonVisit_applyOp(P, _const, _count) \
do { \
if (!_bvContinue && !_bvHalt && !bsonParseError) { \
_bsonVisitOperation_##P; \
} \
} while (0);
#define _bsonParse(Doc, ...) \
do { \
BSON_MAYBE_UNUSED const bson_t *_bpDoc = &(Doc); \
/* Keep track of which elements have been visited based on their index*/ \
uint64_t _bpVisitBits_static[4] = {0}; \
BSON_MAYBE_UNUSED uint64_t *_bpVisitBits = _bpVisitBits_static; \
BSON_MAYBE_UNUSED size_t _bpNumVisitBitInts = sizeof _bpVisitBits_static / sizeof (uint64_t); \
BSON_MAYBE_UNUSED bool _bpFoundElement = false; \
_bsonParse_applyOps (__VA_ARGS__); \
/* We may have allocated for visit bits */ \
if (_bpVisitBits != _bpVisitBits_static) { \
bson_free (_bpVisitBits); \
} \
} while (0)
#define _bsonParse_applyOps(...) _bsonDSL_mapMacro (_bsonParse_applyOp, ~, __VA_ARGS__)
/// Parse one entry referrenced by the context iterator
#define _bsonParse_applyOp(P, _nil, Counter) \
do { \
if (!_bvHalt && !bsonParseError) { \
_bsonParseOperation_##P; \
} \
} while (0);
#define _bsonParseMarkVisited(Index) \
if (1) { \
const size_t nth_int = Index / 64u; \
const size_t nth_bit = Index % 64u; \
while (nth_int >= _bpNumVisitBitInts) { \
/* Say that five times, fast: */ \
size_t new_num_visit_bit_ints = _bpNumVisitBitInts * 2u; \
uint64_t *new_visit_bit_ints = bson_malloc0 (sizeof (uint64_t) * new_num_visit_bit_ints); \
memcpy (new_visit_bit_ints, _bpVisitBits, sizeof (uint64_t) * _bpNumVisitBitInts); \
if (_bpVisitBits != _bpVisitBits_static) { \
bson_free (_bpVisitBits); \
} \
_bpVisitBits = new_visit_bit_ints; \
_bpNumVisitBitInts = new_num_visit_bit_ints; \
} \
\
_bpVisitBits[nth_int] |= (UINT64_C (1) << nth_bit); \
} else \
((void) 0)
#define _bsonParseDidVisitNth(Index) _bsonParseDidVisitNth_1 (Index / 64u, Index % 64u)
#define _bsonParseDidVisitNth_1(NthInt, NthBit) \
(NthInt < _bpNumVisitBitInts && (_bpVisitBits[NthInt] & (UINT64_C (1) << NthBit)))
#define _bsonParseOperation_find(Predicate, ...) \
_bsonDSL_begin ("find(%s)", _bsonDSL_str (Predicate)); \
_bpFoundElement = false; \
_bsonVisitEach ( \
*_bpDoc, \
if (Predicate, \
then (do (_bsonParseMarkVisited (bsonVisitContext.index); _bpFoundElement = true), __VA_ARGS__, break))); \
if (!_bpFoundElement && !bsonParseError) { \
_bsonDSLDebug ("[not found]"); \
} \
_bsonDSL_end
#define _bsonParseOperation_require(Predicate, ...) \
_bsonDSL_begin ("require(%s)", _bsonDSL_str (Predicate)); \
_bpFoundElement = false; \
_bsonVisitEach ( \
*_bpDoc, \
if (Predicate, \
then (do (_bsonParseMarkVisited (bsonVisitContext.index); _bpFoundElement = true), __VA_ARGS__, break))); \
if (!_bpFoundElement && !bsonParseError) { \
bsonParseError = "Failed to find a required element: " _bsonDSL_str (Predicate); \
} \
_bsonDSL_end
#define _bsonParseOperation_visitOthers(...) \
_bsonDSL_begin ("visitOthers(%s)", _bsonDSL_strElide (30, __VA_ARGS__)); \
_bsonVisitEach (*_bpDoc, if (not(eval (_bsonParseDidVisitNth (bsonVisitContext.index))), then (__VA_ARGS__))); \
_bsonDSL_end
#define bsonPredicate(P) _bsonPredicate _bsonDSL_nothing () (P)
#define _bsonPredicate(P) _bsonPredicate_Condition_##P
#define _bsonPredicate_Condition_ __NOTE__Missing_name_for_a_predicate_expression
#define _bsonPredicate_Condition_allOf(...) (1 _bsonDSL_mapMacro (_bsonPredicateAnd, ~, __VA_ARGS__))
#define _bsonPredicate_Condition_anyOf(...) (0 _bsonDSL_mapMacro (_bsonPredicateOr, ~, __VA_ARGS__))
#define _bsonPredicate_Condition_not(...) (!(0 _bsonDSL_mapMacro (_bsonPredicateOr, ~, __VA_ARGS__)))
#define _bsonPredicateAnd(Pred, _ignore, _ignore1) &&_bsonPredicate _bsonDSL_nothing () (Pred)
#define _bsonPredicateOr(Pred, _ignore, _ignore2) || _bsonPredicate _bsonDSL_nothing () (Pred)
#define _bsonPredicate_Condition_eval(X) (X)
#define _bsonPredicate_Condition_key(...) \
(_bson_dsl_key_is_anyof (bson_iter_key (&bsonVisitIter), \
bson_iter_key_len (&bsonVisitIter), \
true /* case senstive */, \
__VA_ARGS__, \
NULL))
#define _bsonPredicate_Condition_iKey(...) \
(_bson_dsl_key_is_anyof (bson_iter_key (&bsonVisitIter), \
bson_iter_key_len (&bsonVisitIter), \
false /* case insenstive */, \
__VA_ARGS__, \
NULL))
#define _bsonPredicate_Condition_type(Type) (bson_iter_type (&bsonVisitIter) == _bsonDSL_Type_##Type)
#define _bsonPredicate_Condition_keyWithType(Key, Type) \
(_bsonPredicate_Condition_allOf _bsonDSL_nothing () (key (Key), type (Type)))
#define _bsonPredicate_Condition_iKeyWithType(Key, Type) \
(_bsonPredicate_Condition_allOf _bsonDSL_nothing () (iKey (Key), type (Type)))
#define _bsonPredicate_Condition_lastElement (_bson_dsl_iter_is_last_element (&bsonVisitIter))
#define _bsonPredicate_Condition_isNumeric BSON_ITER_HOLDS_NUMBER (&bsonVisitIter)
#define _bsonPredicate_Condition_1 1
#define _bsonPredicate_Condition_0 0
#define _bsonPredicate_Condition_true true
#define _bsonPredicate_Condition_false false
#define _bsonPredicate_Condition_isTrue (bson_iter_as_bool (&bsonVisitIter))
#define _bsonPredicate_Condition_isFalse (!bson_iter_as_bool (&bsonVisitIter))
#define _bsonPredicate_Condition_empty (_bson_dsl_is_empty_bson (&bsonVisitIter))
#define _bsonPredicate_Condition_strEqual(S) (_bson_dsl_test_strequal (S, true))
#define _bsonPredicate_Condition_iStrEqual(S) (_bson_dsl_test_strequal (S, false))
#define _bsonPredicate_Condition_eq(Type, Value) (_bsonPredicate_Condition_type (Type) && bsonAs (Type) == Value)
#define _bsonParseOperation_else _bsonParse_deferredElse _bsonDSL_nothing ()
#define _bsonParse_deferredElse(...) \
if (!_bpFoundElement) { \
_bsonDSL_begin ("else:%s", ""); \
_bsonParse_applyOps (__VA_ARGS__); \
_bsonDSL_end; \
} else \
((void) 0)
#define _bsonParseOperation_do(...) \
_bsonDSL_begin ("do: %s", _bsonDSL_strElide (30, __VA_ARGS__)); \
do { \
__VA_ARGS__; \
} while (0); \
_bsonDSL_end
#define _bsonParseOperation_halt _bvHalt = true
#define _bsonParseOperation_error(S) bsonParseError = (S)
#define _bsonParseOperation_errorf(S, ...) (bsonParseError = _bson_dsl_errorf (&(S), __VA_ARGS__))
/// Perform conditional parsing
#define _bsonParseOperation_if(Condition, ...) \
_bsonDSL_begin ("if(%s)", _bsonDSL_str (Condition)); \
/* Pick a sub-macro depending on if there are one or two args */ \
_bsonDSL_ifElse (_bsonDSL_hasComma (__VA_ARGS__), _bsonParse_ifThenElse, _bsonParse_ifThen) (Condition, \
__VA_ARGS__); \
_bsonDSL_end
#define _bsonParse_ifThen_then _bsonParse_applyOps
#define _bsonParse_ifElse_else _bsonParse_applyOps
#define _bsonParse_ifThenElse(Condition, Then, Else) \
if ((Condition)) { \
_bsonDSLDebug ("then:"); \
_bsonParse_ifThen_##Then; \
} else { \
_bsonDSLDebug ("else:"); \
_bsonParse_ifElse_##Else; \
}
#define _bsonParse_ifThen(Condition, Then) \
if ((Condition)) { \
_bsonDSLDebug ("%s", _bsonDSL_str (Then)); \
_bsonParse_ifThen_##Then; \
} else { \
_bsonDSLDebug ("[else nothing]"); \
}
#define _bsonParseOperation_append _bsonParseOperationDeferred_append _bsonDSL_nothing ()
#define _bsonParseOperationDeferred_append(Doc, ...) \
_bsonDSL_begin ("append to [%s] : %s", _bsonDSL_str (Doc), _bsonDSL_strElide (30, __VA_ARGS__)); \
_bsonBuildAppend (Doc, __VA_ARGS__); \
if (bsonBuildError) { \
bsonParseError = bsonBuildError; \
} \
_bsonDSL_end
#define _bsonVisit_applyOps _bsonVisit_applyOpsDeferred _bsonDSL_nothing ()
#define _bsonVisit_applyOpsDeferred(...) \
do { \
_bsonDSL_mapMacro (_bsonVisit_applyOp, ~, __VA_ARGS__); \
} while (0);
#define bsonBuildArray(BSON, ...) \
_bsonDSL_begin ("bsonBuildArray(%s, %s)", _bsonDSL_str (BSON), _bsonDSL_strElide (30, __VA_ARGS__)); \
_bsonDSL_eval (_bsonBuildArray (BSON, __VA_ARGS__)); \
_bsonDSL_end
#define _bsonBuildArray(BSON, ...) \
do { \
_bsonDSL_disableWarnings (); \
struct _bsonBuildContext_t _bbCtx = { \
.doc = &(BSON), \
.parent = _bsonBuildContextThreadLocalPtr, \
.index = 0, \
}; \
_bsonBuildContextThreadLocalPtr = &_bbCtx; \
_bsonBuildArrayWithCurrentContext (__VA_ARGS__); \
_bsonBuildContextThreadLocalPtr = _bbCtx.parent; \
_bsonDSL_restoreWarnings (); \
} while (0)
/**
* @brief Build a BSON document by appending to an existing bson_t document
*
* @param Pointer The document upon which to append
* @param ... The Document elements to append to the document
*/
#define bsonBuildAppend(BSON, ...) _bsonDSL_eval (_bsonBuildAppend (BSON, __VA_ARGS__))
#define _bsonBuildAppend(BSON, ...) \
_bsonDSL_begin ("Appending to document '%s'", _bsonDSL_str (BSON)); \
_bsonDSL_disableWarnings (); \
/* Save the dsl context */ \
struct _bsonBuildContext_t _bbCtx = { \
.doc = &(BSON), \
.parent = _bsonBuildContextThreadLocalPtr, \
}; \
/* Reset the context */ \
_bsonBuildContextThreadLocalPtr = &_bbCtx; \
bsonBuildError = NULL; \
_bsonBuildAppendWithCurrentContext (__VA_ARGS__); \
/* Restore the dsl context */ \
_bsonBuildContextThreadLocalPtr = _bbCtx.parent; \
_bsonDSL_restoreWarnings (); \
_bsonDSL_end
/**
* @brief Build a new BSON document and assign the value into the given
* pointer.
*/
#define bsonBuild(BSON, ...) \
_bsonDSL_begin ("Build a new document for '%s'", _bsonDSL_str (BSON)); \
bson_t *_bbDest = &(BSON); \
bson_init (_bbDest); \
bsonBuildAppend (*_bbDest, __VA_ARGS__); \
_bsonDSL_end
/**
* @brief Declare a variable and build it with the BSON DSL @see bsonBuild
*/
#define bsonBuildDecl(Variable, ...) \
bson_t Variable = BSON_INITIALIZER; \
bsonBuild (Variable, __VA_ARGS__)
struct _bsonBuildContext_t {
/// The document that is being built
bson_t *doc;
/// The key that is pending an append
const char *key;
/// The length of the string given in 'key'
int key_len;
/// The index of the array being built (if applicable)
size_t index;
/// A buffer for formatting key strings
char index_key_str[16];
/// The parent context (if building a sub-document)
struct _bsonBuildContext_t *parent;
};
/// A pointer to the current thread's bsonBuild context
_bson_thread_local _bson_comdat struct _bsonBuildContext_t *_bsonBuildContextThreadLocalPtr = NULL;
struct _bsonVisitContext_t {
const bson_t *doc;
bson_iter_t iter;
const struct _bsonVisitContext_t *parent;
size_t index;
};
/// A pointer to the current thread's bsonVisit/bsonParse context
_bson_thread_local _bson_comdat struct _bsonVisitContext_t const *_bsonVisitContextThreadLocalPtr = NULL;
/**
* @brief The most recent error from a bsonBuild() DSL command.
*
* If NULL, no error occurred. Users can assign a value to this string to
* indicate failure.
*/
_bson_thread_local _bson_comdat const char *bsonBuildError = NULL;
/**
* @brief The most recent error from a buildVisit() or bsonParse() DSL command.
*
* If NULL, no error occurred. Users can assign a value to this string to
* indicate an error.
*
* If this string becomes non-NULL, the current bsonVisit()/bsonParse() will
* halt and return.
*
* Upon entering a new bsonVisit()/bsonParse(), this will be reset to NULL.
*/
_bson_thread_local _bson_comdat const char *bsonParseError = NULL;
#define _bsonDSLDebug(...) _bson_dsl_debug (BSON_DSL_DEBUG, __FILE__, __LINE__, BSON_FUNC, __VA_ARGS__)
static BSON_INLINE bool
_bson_dsl_test_strequal (const char *string, bool case_sensitive)
{
bson_iter_t it = bsonVisitIter;
if (bson_iter_type (&it) == BSON_TYPE_UTF8) {
uint32_t len;
const char *s = bson_iter_utf8 (&it, &len);
if (len != (uint32_t) strlen (string)) {
return false;
}
if (case_sensitive) {
return memcmp (string, s, len) == 0;
} else {
return bson_strcasecmp (string, s) == 0;
}
}
return false;
}
static BSON_INLINE bool
_bson_dsl_key_is_anyof (const char *key, const size_t keylen, int case_sensitive, ...)
{
va_list va;
va_start (va, case_sensitive);
const char *str;
while ((str = va_arg (va, const char *))) {
size_t str_len = strlen (str);
if (str_len != keylen) {
continue;
}
if (case_sensitive) {
if (memcmp (str, key, str_len) == 0) {
va_end (va);
return true;
}
} else {
if (bson_strcasecmp (str, key) == 0) {
va_end (va);
return true;
}
}
}
va_end (va);
return false;
}
static BSON_INLINE void
_bson_dsl_iter_as_doc (bson_t *into, const bson_iter_t *it)
{
uint32_t len = 0;
const uint8_t *dataptr = NULL;
if (BSON_ITER_HOLDS_ARRAY (it)) {
bson_iter_array (it, &len, &dataptr);
} else if (BSON_ITER_HOLDS_DOCUMENT (it)) {
bson_iter_document (it, &len, &dataptr);
}
if (dataptr) {
BSON_ASSERT (bson_init_static (into, dataptr, len));
}
}
static BSON_INLINE bool
_bson_dsl_is_empty_bson (const bson_iter_t *it)
{
bson_t d = BSON_INITIALIZER;
_bson_dsl_iter_as_doc (&d, it);
return d.len == 5; // Empty documents/arrays have byte-size of five
}
static BSON_INLINE bool
_bson_dsl_iter_is_last_element (const bson_iter_t *it)
{
bson_iter_t dup = *it;
return !bson_iter_next (&dup) && dup.err_off == 0;
}
_bson_thread_local _bson_comdat int _bson_dsl_indent = 0;
static BSON_INLINE void BSON_GNUC_PRINTF (5, 6)
_bson_dsl_debug (bool do_debug, const char *file, int line, const char *func, const char *string, ...)
{
if (do_debug) {
fprintf (stderr, "%s:%d: [%s] bson_dsl: ", file, line, func);
for (int i = 0; i < _bson_dsl_indent; ++i) {
fputs (" ", stderr);
}
va_list va;
va_start (va, string);
vfprintf (stderr, string, va);
va_end (va);
fputc ('\n', stderr);
fflush (stderr);
}
}
static BSON_INLINE char *BSON_GNUC_PRINTF (2, 3) _bson_dsl_errorf (char **const into, const char *const fmt, ...)
{
if (*into) {
bson_free (*into);
*into = NULL;
}
va_list args;
va_start (args, fmt);
*into = bson_strdupv_printf (fmt, args);
va_end (args);
return *into;
}
static BSON_INLINE void
_bson_dsl_dupPath (char **into)
{
if (*into) {
bson_free (*into);
*into = NULL;
}
char *acc = bson_strdup ("");
for (const struct _bsonVisitContext_t *ctx = &bsonVisitContext; ctx; ctx = ctx->parent) {
char *prev = acc;
if (ctx->parent && BSON_ITER_HOLDS_ARRAY (&ctx->parent->iter)) {
// We're an array element
acc = bson_strdup_printf ("[%d]%s", (int) ctx->index, prev);
} else {
// We're a document element
acc = bson_strdup_printf (".%s%s", bson_iter_key (&ctx->iter), prev);
}
bson_free (prev);
}
*into = bson_strdup_printf ("$%s", acc);
bson_free (acc);
}
static BSON_INLINE const char *
_bsonVisitIterAs_cstr (void)
{
return bson_iter_utf8 (&bsonVisitIter, NULL);
}
static BSON_INLINE int32_t
_bsonVisitIterAs_int32 (void)
{
return bson_iter_int32 (&bsonVisitIter);
}
static BSON_INLINE bool
_bsonVisitIterAs_boolean (void)
{
return bson_iter_as_bool (&bsonVisitIter);
}
#define bsonAs(Type) _bsonDSL_paste (_bsonVisitIterAs_, Type) ()
/// Convert the given argument into a string without inhibitting macro expansion
#define _bsonDSL_str(...) _bsonDSL_str_1 (__VA_ARGS__)
// Empty quotes "" are to ensure a string appears. Old MSVC has a bug
// where empty #__VA_ARGS__ just vanishes.
#define _bsonDSL_str_1(...) "" #__VA_ARGS__
#define _bsonDSL_strElide(MaxLen, ...) \
(strlen (_bsonDSL_str (__VA_ARGS__)) > (MaxLen) ? "[...]" : _bsonDSL_str (__VA_ARGS__))
/// Paste two tokens:
#define _bsonDSL_paste(a, ...) _bsonDSL_paste_impl (a, __VA_ARGS__)
#define _bsonDSL_paste_impl(a, ...) a##__VA_ARGS__
/// Paste three tokens:
#define _bsonDSL_paste3(a, b, c) _bsonDSL_paste (a, _bsonDSL_paste (b, c))
/// Paste four tokens:
#define _bsonDSL_paste4(a, b, c, d) _bsonDSL_paste (a, _bsonDSL_paste3 (b, c, d))
// clang-format off
/// Now we need a MAP() macro. This idiom is common, but fairly opaque. Below is
/// some crazy preprocessor trickery to implement it. Fortunately, once we have
/// MAP(), the remainder of this file is straightforward. This implementation
/// isn't the simplest one possible, but is one that supports the old
/// non-compliant MSVC preprocessor.
/* Expands to nothing. Used to defer a function-like macro and to ignore arguments */
#define _bsonDSL_nothing(...)
/// Expand to the 64th argument. See below for why this is useful.
#define _bsonDSL_pick64th(\
_0, _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, ...) \
_63
/**
* @brief Expands to 1 if the given arguments contain any top-level commas, zero otherwise.
*
* There is an expansion of __VA_ARGS__, followed by 62 '1' arguments, followed
* by single '0'. If __VA_ARGS__ contains no commas, pick64th() will return the
* single zero. If __VA_ARGS__ contains any top-level commas, the series of ones
* will shift to the right and pick64th will return one of those ones. (This only
* works __VA_ARGS__ contains fewer than 62 commas, which is a somewhat reasonable
* limit.) The _bsonDSL_nothing() is a workaround for MSVC's bad preprocessor that
* expands __VA_ARGS__ incorrectly.
*
* If we have __VA_OPT__, this can be a lot simpler.
*/
#define _bsonDSL_hasComma(...) \
_bsonDSL_pick64th \
_bsonDSL_nothing() (__VA_ARGS__, \
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, \
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, ~)
/**
* Expands to a single comma if "invoked" as a function-like macro.
* (This will make sense, I promise.)
*/
#define _bsonDSL_commaIfRHSHasParens(...) ,
/**
* @brief Expand to 1 if given no arguments, otherwise 0.
*
* This could be done much more simply using __VA_OPT__, but we need to work on
* older compilers.
*/
#define _bsonDSL_isEmpty(...) \
_bsonDSL_isEmpty_1(\
/* Expands to '1' if __VA_ARGS__ contains any top-level commas */ \
_bsonDSL_hasComma(__VA_ARGS__), \
/* Expands to '1' if __VA_ARGS__ begins with a parenthesis, because \
* that will cause an "invocation" of _bsonDSL_commaIfRHSHasParens, \
* which immediately expands to a single comma. */ \
_bsonDSL_hasComma(_bsonDSL_commaIfRHSHasParens __VA_ARGS__), \
/* Expands to '1' if __VA_ARGS__ expands to a function-like macro name \
* that then expands to anything containing a top-level comma */ \
_bsonDSL_hasComma(__VA_ARGS__ ()), \
/* Expands to '1' if __VA_ARGS__ expands to nothing. */ \
_bsonDSL_hasComma(_bsonDSL_commaIfRHSHasParens __VA_ARGS__ ()))
/**
* A helper for isEmpty(): If given (0, 0, 0, 1), expands as:
* - first: _bsonDSL_hasComma(_bsonDSL_isEmpty_CASE_0001)
* - then: _bsonDSL_hasComma(,)
* - then: 1
* Given any other aruments:
* - first: _bsonDSL_hasComma(_bsonDSL_isEmpty_CASE_)
* - then: 0
*/
#define _bsonDSL_isEmpty_1(_1, _2, _3, _4) \
_bsonDSL_hasComma(_bsonDSL_paste(_bsonDSL_isEmpty_CASE_, _bsonDSL_paste4(_1, _2, _3, _4)))
#define _bsonDSL_isEmpty_CASE_0001 ,
/**
* @brief Expand to the first argument if `Cond` is 1, the second argument if `Cond` is 0
*/
#define _bsonDSL_ifElse(Cond, IfTrue, IfFalse) \
/* Suppress expansion of the two branches by using the '#' operator */ \
_bsonDSL_nothing(#IfTrue, #IfFalse) \
/* Concat the cond 1/0 with a prefix macro: */ \
_bsonDSL_paste(_bsonDSL_ifElse_PICK_, Cond)(IfTrue, IfFalse)
#define _bsonDSL_ifElse_PICK_1(IfTrue, IfFalse) \
/* Expand the first operand, throw away the second */ \
IfTrue _bsonDSL_nothing(#IfFalse)
#define _bsonDSL_ifElse_PICK_0(IfTrue, IfFalse) \
/* Expand to the second operand, throw away the first */ \
IfFalse _bsonDSL_nothing(#IfTrue)
#ifdef _MSC_VER
// MSVC's "traditional" preprocessor requires many more expansion passes,
// but GNU and Clang are very slow when evaluating hugely nested expansions
// and generate massive macro expansion backtraces.
#define _bsonDSL_eval_1(...) __VA_ARGS__
#define _bsonDSL_eval_2(...) _bsonDSL_eval_1(_bsonDSL_eval_1(_bsonDSL_eval_1(_bsonDSL_eval_1(_bsonDSL_eval_1(__VA_ARGS__)))))
#define _bsonDSL_eval_4(...) _bsonDSL_eval_2(_bsonDSL_eval_2(_bsonDSL_eval_2(_bsonDSL_eval_2(_bsonDSL_eval_2(__VA_ARGS__)))))
#define _bsonDSL_eval_8(...) _bsonDSL_eval_4(_bsonDSL_eval_4(_bsonDSL_eval_4(_bsonDSL_eval_4(_bsonDSL_eval_4(__VA_ARGS__)))))
#define _bsonDSL_eval_16(...) _bsonDSL_eval_8(_bsonDSL_eval_8(_bsonDSL_eval_8(_bsonDSL_eval_8(_bsonDSL_eval_8(__VA_ARGS__)))))
#define _bsonDSL_eval(...) _bsonDSL_eval_16(_bsonDSL_eval_16(_bsonDSL_eval_16(_bsonDSL_eval_16(_bsonDSL_eval_16(__VA_ARGS__)))))
#else
// Each level of "eval" applies double the expansions of the previous level.
#define _bsonDSL_eval_1(...) __VA_ARGS__
#define _bsonDSL_eval_2(...) _bsonDSL_eval_1(_bsonDSL_eval_1(__VA_ARGS__))
#define _bsonDSL_eval_4(...) _bsonDSL_eval_2(_bsonDSL_eval_2(__VA_ARGS__))
#define _bsonDSL_eval_8(...) _bsonDSL_eval_4(_bsonDSL_eval_4(__VA_ARGS__))
#define _bsonDSL_eval_16(...) _bsonDSL_eval_8(_bsonDSL_eval_8(__VA_ARGS__))
#define _bsonDSL_eval_32(...) _bsonDSL_eval_16(_bsonDSL_eval_16(__VA_ARGS__))
#define _bsonDSL_eval(...) _bsonDSL_eval_32(__VA_ARGS__)
#endif
/**
* Finally, the Map() macro that allows us to do the magic, which we've been
* building up to all along.
*
* The dance with mapMacro_first, mapMacro_final, and _bsonDSL_nothing
* conditional on argument count is to prevent warnings from pre-C99 about
* passing no arguments to the '...' parameters. Yet again, if we had C99 and
* __VA_OPT__ this would be simpler.
*/
#define _bsonDSL_mapMacro(Action, Constant, ...) \
/* Pick our first action based on the content of '...': */ \
_bsonDSL_ifElse( \
/* If given no arguments: */\
_bsonDSL_isEmpty(__VA_ARGS__), \
/* expand to _bsonDSL_nothing */ \
_bsonDSL_nothing, \
/* Otherwise, expand to mapMacro_first: */ \
_bsonDSL_mapMacro_first) \
/* Now "invoke" the chosen macro: */ \
_bsonDSL_nothing() (Action, Constant, __VA_ARGS__)
#define _bsonDSL_mapMacro_first(Action, Constant, ...) \
/* Select our next step based on whether we have one or more arguments: */ \
_bsonDSL_ifElse( \
/* If '...' contains more than one argument (has a top-level comma): */ \
_bsonDSL_hasComma(__VA_ARGS__), \
/* Begin the mapMacro loop with mapMacro_A: */ \
_bsonDSL_mapMacro_A, \
/* Otherwise skip to the final step of the loop: */ \
_bsonDSL_mapMacro_final) \
/* Invoke the chosen macro, setting the counter to zero: */ \
_bsonDSL_nothing() (Action, Constant, 0, __VA_ARGS__)
/// Handle the last expansion in a mapMacro sequence.
#define _bsonDSL_mapMacro_final(Action, Constant, Counter, FinalElement) \
Action(FinalElement, Constant, Counter)
/**
* mapMacro_A and mapMacro_B are identical and just invoke each other.
*/
#define _bsonDSL_mapMacro_A(Action, Constant, Counter, Head, ...) \
/* First evaluate the action once: */ \
Action(Head, Constant, Counter) \
/* Pick our next step: */ \
_bsonDSL_ifElse( \
/* If '...' contains more than one argument (has a top-level comma): */ \
_bsonDSL_hasComma(__VA_ARGS__), \
/* Jump to the other mapMacro: */ \
_bsonDSL_mapMacro_B, \
/* Otherwise go to mapMacro_final */ \
_bsonDSL_mapMacro_final) \
/* Invoke the next step of the map: */ \
_bsonDSL_nothing() (Action, Constant, Counter + 1, __VA_ARGS__)
#define _bsonDSL_mapMacro_B(Action, Constant, Counter, Head, ...) \
Action(Head, Constant, Counter) \
_bsonDSL_ifElse(_bsonDSL_hasComma(__VA_ARGS__), _bsonDSL_mapMacro_A, _bsonDSL_mapMacro_final) \
_bsonDSL_nothing() (Action, Constant, Counter + 1, __VA_ARGS__)
// clang-format on
#endif // MONGO_C_DRIVER_COMMON_BSON_DSL_PRIVATE_H
mongodb-2.1.0/src/libmongoc/src/common/src/common-cmp-private.h 0000644 0001751 0000166 00000020502 15014033047 021350 0 ustar /*
* Copyright 2009-present MongoDB, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include
#ifndef MONGO_C_DRIVER_COMMON_CMP_PRIVATE_H
#define MONGO_C_DRIVER_COMMON_CMP_PRIVATE_H
#include /* ssize_t, BSON_CONCAT */
#include
#include
#include