package.xml 0000644 0001751 0001751 00001356117 15264101572 010136 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.
Jérôme Tamarelle
gromnan
jerome.tamarelle@mongodb.com
yes
Pauline Vos
synon
info@pauline-vos.nl
yes
Kevin Albertson
kevinalbs
kevin.albertson@mongodb.com
yes
Andreas Braun
alcaeus
alcaeus@php.net
no
Jeremy Mikola
jmikola
jmikola@php.net
no
Derick Rethans
derick
derick@php.net
no
Hannes Magnusson
bjori
bjori@php.net
no
Katherine Walker
kvwalker
kvwalker@php.net
no
2026-10-15
2.5.5
2.5.5
stable
stable
Apache License
<!-- Release notes generated using configuration in .github/release.yml at 2.5.5 -->
## What's Changed
### Fixed
* PHPC-276: Prevent stack exhaustion when decoding deeply nested BSON by @GromNaN in https://github.com/mongodb/mongo-php-driver/pull/2158
### Other Changes
* PHPC-276: Enforce the decode nesting limit for CodeWScope scopes by @GromNaN in https://github.com/mongodb/mongo-php-driver/pull/2166
**Full Changelog**: https://github.com/mongodb/mongo-php-driver/compare/2.5.4...2.5.5
8.1.0
8.99.99
1.4.8
mongodb
mongodb-2.5.5/scripts/autotools/libbson/CheckHeaders.m4 0000644 0001751 0001751 00000000421 15264101572 020015 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.5.5/scripts/autotools/libbson/Endian.m4 0000644 0001751 0001751 00000000276 15264101572 016712 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.5.5/scripts/autotools/libbson/FindDependencies.m4 0000644 0001751 0001751 00000003732 15264101572 020703 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.5.5/scripts/autotools/libbson/Versions.m4 0000644 0001751 0001751 00000001252 15264101572 017317 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.5.5/scripts/autotools/libmongoc/CheckCompression.m4 0000644 0001751 0001751 00000012274 15264101572 021275 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.5.5/scripts/autotools/libmongoc/CheckResolv.m4 0000644 0001751 0001751 00000005621 15264101572 020244 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.5.5/scripts/autotools/libmongoc/CheckSSL.m4 0000644 0001751 0001751 00000016172 15264101572 017436 0 ustar PHP_ARG_WITH([mongodb-ssl],
[whether to enable crypto and TLS],
[AS_HELP_STRING([--with-mongodb-ssl=@<:@auto/openssl/darwin/no@:>@],
[MongoDB: Enable TLS connections and SCRAM-SHA-1 authentication [default=auto]])],
[auto],
[no])
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
dnl TODO 3.0: Remove libressl from valid options
PHP_MONGODB_VALIDATE_ARG([PHP_MONGODB_SSL], [auto openssl libressl darwin no])
if test "$PHP_MONGODB_SSL" = "libressl"; then
dnl libressl is a valid option, but it is not supported by libmongoc
dnl Warn users that it is not supported and treat it like "auto"
PHP_MONGODB_SSL="auto"
AC_MSG_WARN([Building with libressl is not supported by libmongoc. Falling back to "auto".])
fi
if test "$PHP_MONGODB_SSL" = "auto" -o "$PHP_MONGODB_SSL" = "no"; then
crypto_required="no"
else
crypto_required="yes"
fi
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" = "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" = "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_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_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_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.5.5/scripts/autotools/libmongoc/CheckSasl.m4 0000644 0001751 0001751 00000004566 15264101572 017703 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.5.5/scripts/autotools/libmongoc/CheckUtf8Proc.m4 0000644 0001751 0001751 00000003062 15264101572 020441 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.5.5/scripts/autotools/libmongoc/Endian.m4 0000644 0001751 0001751 00000000451 15264101572 017226 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.5.5/scripts/autotools/libmongoc/FindDependencies.m4 0000644 0001751 0001751 00000003057 15264101572 021224 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.5.5/scripts/autotools/libmongoc/Versions.m4 0000644 0001751 0001751 00000001431 15264101572 017637 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)
AC_SUBST(MONGOC_CXX_COMPILER_ID, "")
AC_SUBST(MONGOC_CXX_COMPILER_VERSION, "")
mongodb-2.5.5/scripts/autotools/libmongocrypt/CheckSSL.m4 0000644 0001751 0001751 00000002124 15264101572 020345 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"; 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.5.5/scripts/autotools/libmongocrypt/Endian.m4 0000644 0001751 0001751 00000000570 15264101572 020147 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.5.5/scripts/autotools/libmongocrypt/Version.m4 0000644 0001751 0001751 00000000370 15264101572 020374 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.5.5/scripts/autotools/m4/ax_check_compile_flag.m4 0000644 0001751 0001751 00000004070 15264101572 020646 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.5.5/scripts/autotools/m4/ax_prototype.m4 0000644 0001751 0001751 00000020112 15264101572 017130 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.5.5/scripts/autotools/m4/ax_prototype_accept.m4 0000644 0001751 0001751 00000004673 15264101572 020465 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.5.5/scripts/autotools/m4/ax_pthread.m4 0000644 0001751 0001751 00000054122 15264101572 016522 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.5.5/scripts/autotools/m4/php_mongodb.m4 0000644 0001751 0001751 00000005665 15264101572 016707 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_INCLUDE(path)
dnl
dnl Adds an include path relative to the extension build directory (i.e.
dnl PHP_EXT_BUILDDIR). Use this for directories containing generated files
dnl (e.g. config headers written by AC_CONFIG_FILES).
dnl
dnl PHP_EXT_BUILDDIR returns a path relative to the configure invocation
dnl directory (e.g. "." for phpize builds, "ext/mongodb" for in-tree builds).
dnl The subdirectory passed as $1 does not exist at configure time (build dirs
dnl are created in AC_CONFIG_COMMANDS_PRE), so passing the full relative path
dnl to PHP_ADD_INCLUDE would cause PHP_EXPAND_PATH to silently discard it when
dnl the "cd $path && pwd" probe fails. To avoid this, we resolve only the base
dnl (PHP_EXT_BUILDDIR, which always exists at configure time) to an absolute
dnl path first, then append $1. PHP_ADD_INCLUDE skips the cd-probe for paths
dnl that already start with "/".
dnl
AC_DEFUN([PHP_MONGODB_ADD_BUILD_INCLUDE],[
PHP_EXPAND_PATH(PHP_EXT_BUILDDIR(mongodb), php_mongodb_abs_builddir)
PHP_ADD_INCLUDE([$php_mongodb_abs_builddir/$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.5.5/scripts/autotools/m4/pkg.m4 0000644 0001751 0001751 00000024250 15264101572 015163 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.5.5/scripts/autotools/CheckCompiler.m4 0000644 0001751 0001751 00000003270 15264101572 016571 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.5.5/scripts/autotools/CheckHost.m4 0000644 0001751 0001751 00000001774 15264101572 015743 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.5.5/scripts/autotools/PlatformFlags.m4 0000644 0001751 0001751 00000002313 15264101572 016617 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.5.5/scripts/clang-format.sh 0000755 0001751 0001751 00000002366 15264101572 014504 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.5.5/scripts/convert-bson-binary-vector-tests.php 0000644 0001751 0001751 00000021341 15264101572 020637 0 ustar 'Document memory leak (PHPC-2648)',
'Tests of Binary subtype 9, Vectors, with dtype FLOAT32: Insufficient vector data with 3 bytes FLOAT32' => 'Document memory leak (PHPC-2648)',
'Tests of Binary subtype 9, Vectors, with dtype FLOAT32: Insufficient vector data with 5 bytes FLOAT32' => 'Document memory leak (PHPC-2648)',
'Tests of Binary subtype 9, Vectors, with dtype INT8: INT8 with padding' => 'Document memory leak (PHPC-2648)',
'Tests of Binary subtype 9, Vectors, with dtype PACKED_BIT: Padding specified with no vector data PACKED_BIT' => 'Document memory leak (PHPC-2648)',
'Tests of Binary subtype 9, Vectors, with dtype PACKED_BIT: Exceeding maximum padding PACKED_BIT' => 'Document memory leak (PHPC-2648)',
];
$outputPath = realpath(__DIR__ . '/../tests') . '/bson-binary-vector/';
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;
}
try {
$test = Document::fromJSON(file_get_contents($inputFile))->toPHP(['root' => 'array', 'document' => 'array']);
} catch (UnexpectedValueException $e) {
printf("Error decoding %s: %s\n", $inputFile, $e->getMessage());
continue;
}
if ( ! isset($test['description'])) {
printf("Skipping test file without \"description\" field: %s\n", $inputFile);
continue;
}
if ( ! isset($test['test_key'])) {
printf("Skipping test file without \"test_key\" field: %s\n", $inputFile);
continue;
}
if ( ! empty($test['tests'])) {
foreach ($test['tests'] as $i => $case) {
$outputFile = sprintf('%s-%03d.phpt', pathinfo($inputFile, PATHINFO_FILENAME), $i + 1);
try {
$output = renderPhpt(getParamsForTestCase($test, $case), $expectedFailures);
} catch (Exception $e) {
printf("Error processing tests[%d] in %s: %s\n", $i, $inputFile, $e->getMessage());
continue;
}
if (false === file_put_contents($outputPath . '/' . $outputFile, $output)) {
printf("Error writing tests[%d] in %s\n", $i, $inputFile);
continue;
}
}
}
}
function convertVector(array $input, VectorType $vectorType, int $padding): array
{
if (!array_is_list($input)) {
throw new InvalidArgumentException('Vector is not a list');
}
if ($vectorType != VectorType::PackedBit) {
if ($padding !== 0) {
throw new InvalidArgumentException(sprintf('Vector type %s does not support padding: %d', $vectorType->name, $padding));
}
return $input;
}
if ($padding < 0 || $padding > 7) {
throw new InvalidArgumentException(sprintf('Expected padding [0..7], %d given', $padding));
}
if (count($input) === 0 && $padding > 0) {
throw new InvalidArgumentException(sprintf('Non-zero padding (%d) given for empty vector', $padding));
}
$vector = [];
foreach ($input as $i => $byte) {
if (!is_int($byte)) {
throw new InvalidArgumentException(sprintf('Expected vector[%d] to be an int, %s given', $i, get_debug_type($byte)));
}
if ($byte < 0 || $byte > 255) {
throw new InvalidArgumentException(sprintf('Expected vector[%d] to be an unsigned int8, %d given', $i, $byte));
}
// decbin() may return fewer than 8 binary digits, so left-pad its output with zeroes
$digits = str_pad(decbin($byte), 8, '0', STR_PAD_LEFT);
$bits = array_map(intval(...), str_split($digits));
array_push($vector, ...$bits);
}
// Remove trailing zeroes from the final byte's digits according to padding
if ($padding > 0) {
$removed = array_splice($vector, -$padding);
// Assert that only zeroes were removed
if ($removed !== array_fill(0, $padding, 0)) {
throw new InvalidArgumentException(sprintf('Application of padding %d would remove non-zero digits: %s', $padding, json_encode($removed)));
}
}
return $vector;
}
function getParamsForTestCase(array $test, array $case): array
{
foreach (['description', 'valid', 'dtype_hex'] as $field) {
if (!isset($case[$field])) {
throw new InvalidArgumentException(sprintf('Missing "%s" field', $field));
}
}
$code = '';
$expect = '';
$vectorType = match ($case['dtype_hex']) {
'0x27' => VectorType::Float32,
'0x03' => VectorType::Int8,
'0x10' => VectorType::PackedBit,
};
$padding = $case['padding'] ?? 0;
if ($case['valid']) {
$code .= sprintf('// Vector %s with padding %d', json_encode($case['vector']), $padding) . "\n";
/* encode a document from the numeric values, dtype, and padding, along
* with the "test_key", and assert this matches the canonical_bson
* string. */
$vector = convertVector($case['vector'], $vectorType, $padding);
$code .= sprintf('$vector = %s;', var_export($vector, true)) . "\n\n";
$code .= sprintf('$binary = MongoDB\BSON\Binary::fromVector($vector, %s);', var_export($vectorType, true)) . "\n";
$code .= sprintf('echo bin2hex((string) MongoDB\BSON\Document::fromPHP([%s => $binary])), "\n";', var_export($test['test_key'], true)) . "\n\n";
$expect .= strtolower($case['canonical_bson']) . "\n";
/* decode the canonical_bson into its binary form, and then assert that
* the numeric values, dtype, and padding all match those provided in
* the JSON. */
$code .= sprintf('$bson = MongoDB\BSON\Document::fromBSON(hex2bin(%s));', var_export($case['canonical_bson'], true)) . "\n";
$code .= sprintf('var_dump($binary == $bson[%s]);', var_export($test['test_key'], true)) . "\n";
$expect .= 'bool(true)' . "\n";
} else /* not valid */ {
/* if the vector field is present, raise an exception when attempting
* to encode a document from the numeric values, dtype, and padding. */
if (isset($case['vector'])) {
$code .= sprintf('// Vector %s with padding %d', json_encode($case['vector']), $padding) . "\n";
try {
$vector = convertVector($case['vector'], $vectorType, $padding);
$code .= sprintf('$vector = %s;', var_export($vector, true)) . "\n\n";
$code .= "throws(function() use (\$vector) {\n";
$code .= sprintf(" var_dump(MongoDB\BSON\Binary::fromVector(\$vector, %s));\n", var_export($vectorType, true));
$code .= "}, 'MongoDB\Driver\Exception\InvalidArgumentException');" . "\n\n";
$expect .= 'OK: Got MongoDB\Driver\Exception\InvalidArgumentException' . "\n";
} catch (InvalidArgumentException $e) {
$code .= sprintf('echo %s, "\n";', var_export($e->getMessage(), true)) . "\n\n";
$expect .= $e->getMessage() . "\n";
}
}
/* if the canonical_bson field is present, raise an exception when
* attempting to deserialize it into the corresponding numeric values,
* as the field contains corrupted data. */
if (isset($case['canonical_bson'])) {
$code .= "throws(function() {\n";
$code .= sprintf(' var_dump(MongoDB\BSON\Document::fromBSON(hex2bin(%s)));', var_export($case['canonical_bson'], true)) . "\n";
$code .= "}, 'MongoDB\Driver\Exception\InvalidArgumentException');";
$expect .= 'OK: Got MongoDB\Driver\Exception\InvalidArgumentException' . "\n";
}
}
return [
'%NAME%' => sprintf('%s: %s', trim($test['description']), trim($case['description'])),
'%CODE%' => trim($code),
'%EXPECT%' => trim($expect),
];
}
function renderPhpt(array $params, array $expectedFailures): string
{
$params['%XFAIL%'] = isset($expectedFailures[$params['%NAME%']])
? "--XFAIL--\n" . $expectedFailures[$params['%NAME%']] . "\n"
: '';
$params['%SKIPIF%'] = '';
$template = <<< 'TEMPLATE'
--TEST--
%NAME%
%XFAIL%%SKIPIF%--DESCRIPTION--
Generated by scripts/convert-bson-binary-vector-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.5.5/scripts/convert-bson-corpus-tests.php 0000644 0001751 0001751 00000027713 15264101572 017377 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.5.5/scripts/generate-functionmap.php 0000644 0001751 0001751 00000010542 15264101572 016412 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.5.5/scripts/generate-purls.sh 0000755 0001751 0001751 00000001303 15264101572 015055 0 ustar #!/usr/bin/env bash
# Writes the purls for the bundled dependencies to stdout, derived from the
# version files that accompany the submodules. Shared by update-sbom.sh, which
# feeds them to silkbomb, and by the check-sbom workflow, which compares them
# against the committed sbom.json.
set -euo pipefail
SCRIPT_DIR=$(dirname "${BASH_SOURCE[0]}")
ROOT_DIR=$(realpath "${SCRIPT_DIR}/../")
LIBMONGOC_VERSION=$(cat "${ROOT_DIR}/src/libmongoc/VERSION_CURRENT" | tr -d '[:space:]')
LIBMONGOCRYPT_VERSION=$(cat "${ROOT_DIR}/src/LIBMONGOCRYPT_VERSION_CURRENT" | tr -d '[:space:]')
echo "pkg:github/mongodb/mongo-c-driver@${LIBMONGOC_VERSION}"
echo "pkg:github/mongodb/libmongocrypt@${LIBMONGOCRYPT_VERSION}"
mongodb-2.5.5/scripts/update-sbom.sh 0000755 0001751 0001751 00000002043 15264101572 014342 0 ustar #!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR=$(dirname "${BASH_SOURCE[0]}")
ROOT_DIR=$(realpath "${SCRIPT_DIR}/../")
PURLS_FILE="${ROOT_DIR}/purls.txt"
registry="901841024863.dkr.ecr.us-east-1.amazonaws.com"
trap 'rm -f "$PURLS_FILE"' EXIT
# Generate purls file from stored versions
"${SCRIPT_DIR}/generate-purls.sh" > "$PURLS_FILE"
# Log in to the DevProd Platforms ECR registry that hosts silkbomb. Requires membership in the
# devprod-platforms-ecr-users Okta group and an AWS SSO profile for the account; see
# https://docs.devprod.prod.corp.mongodb.com/devprod-platforms-ecr#from-your-laptop
profile="${DEVPROD_PLATFORMS_ECR_AWS_PROFILE:-ECRScopedAccess-901841024863}"
aws ecr get-login-password --region us-east-1 --profile "$profile" | docker login --username AWS --password-stdin "$registry"
# Use silkbomb to update the sbom.json file
docker run --platform="linux/amd64" -i --rm -v "${ROOT_DIR}:/pwd" \
"${registry}/release-infrastructure/silkbomb:2.0" \
update --sbom-in /pwd/sbom.json --purls /pwd/purls.txt --sbom-out /pwd/sbom.json
mongodb-2.5.5/scripts/update-submodule-sources.php 0000644 0001751 0001751 00000005535 15264101572 017245 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.11.3',
'PHP_MONGODB_ZLIB_SOURCES' => 'src/libmongoc/src/zlib-1.3.1',
// Note: src/libmongoc/src/common/src/mlib does not contain source files (as of libmongoc 2.0.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_UNICODE_SOURCES' => 'src/libmongocrypt/src/unicode',
'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.14.0)
];
$patterns = [];
$replacements = [];
// Paths are relative to the project root directory
chdir(__DIR__ . '/..');
foreach ($vars as $var => $path) {
$files = glob($path . '/*.c');
if ($files === false) {
$files = [];
}
// Keep only the file names (drop the directory prefix) and sort them.
// Compare only alphanumeric characters to match "LC_ALL=C sort -d" so the
// generated lists keep the same order without relying on GNU coreutils.
$basenames = array_map('basename', $files);
usort($basenames, static function (string $a, string $b): int {
return preg_replace('/[^A-Za-z0-9]/', '', $a) <=> preg_replace('/[^A-Za-z0-9]/', '', $b) ?: $a <=> $b;
});
$files = implode(' ', $basenames);
// 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.5.5/src/BSON/Binary.c 0000644 0001751 0001751 00000047265 15264101572 013033 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 "phongo.h"
#include "phongo_bson_encode.h"
#include "phongo_error.h"
#include "Binary.h"
#include "Binary_arginfo.h"
#include "VectorType.h"
zend_class_entry* phongo_binary_ce;
static phongo_bson_vector_type_t phongo_binary_get_vector_type_from_data(const uint8_t* data, uint32_t data_len);
static phongo_bson_vector_type_t phongo_binary_get_vector_type(const phongo_binary_t* intern);
static void phongo_binary_get_vector_as_array(const phongo_binary_t* intern, zval* return_value);
/* Initialize the object and return whether it was successful. An exception will
* be thrown on error. */
static bool phongo_binary_init(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 (data_len > PHONGO_BSON_MAX_LENGTH) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected data length to be <= %" PRId32 " bytes, %zu given", (int32_t) PHONGO_BSON_MAX_LENGTH, data_len);
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, %zu given", PHONGO_BINARY_UUID_SIZE, data_len);
return false;
}
if ((type == BSON_SUBTYPE_VECTOR) && phongo_binary_get_vector_type_from_data((const uint8_t*) data, data_len) == PHONGO_BSON_VECTOR_TYPE_UNKNOWN) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Binary vector data is invalid");
return false;
}
if (intern->data) {
efree(intern->data);
}
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 phongo_binary_init_from_hash(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 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(phongo_binary_ce->name));
return false;
}
static HashTable* phongo_binary_get_properties_hash(zend_object* object, bool is_temp, bool is_debug)
{
PHONGO_INTERN_FROM_Z_OBJ(binary, object);
HashTable* props;
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_temp, intern, props, 2);
if (!intern->data) {
return props;
}
{
zval data, type;
if (is_debug) {
ZVAL_NEW_STR(&data, php_base64_encode((unsigned char*) intern->data, intern->data_len));
} else {
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)
{
PHONGO_INTERN_FROM_THIS(binary);
char* data;
size_t data_len;
zend_long type = BSON_SUBTYPE_BINARY;
PHONGO_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_STRING(data, data_len)
Z_PARAM_OPTIONAL
Z_PARAM_LONG(type)
PHONGO_PARSE_PARAMETERS_END();
phongo_binary_init(intern, data, data_len, type);
}
static PHP_METHOD(MongoDB_BSON_Binary, __set_state)
{
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
PHONGO_INTERN_INIT_EX(binary, return_value);
props = Z_ARRVAL_P(array);
phongo_binary_init_from_hash(intern, props);
}
/* Return the Binary's data string. */
static PHP_METHOD(MongoDB_BSON_Binary, __toString)
{
PHONGO_INTERN_FROM_THIS(binary);
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_STRINGL(intern->data, intern->data_len);
}
static PHP_METHOD(MongoDB_BSON_Binary, getData)
{
PHONGO_INTERN_FROM_THIS(binary);
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_STRINGL(intern->data, intern->data_len);
}
static PHP_METHOD(MongoDB_BSON_Binary, getType)
{
PHONGO_INTERN_FROM_THIS(binary);
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_LONG(intern->type);
}
static PHP_METHOD(MongoDB_BSON_Binary, jsonSerialize)
{
PHONGO_INTERN_FROM_THIS(binary);
char type[3];
int type_len;
PHONGO_PARSE_PARAMETERS_NONE();
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(phongo_binary_get_properties_hash(Z_OBJ_P(getThis()), true, false));
}
static PHP_METHOD(MongoDB_BSON_Binary, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
phongo_binary_init_from_hash(Z_BINARY_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\Binary object handlers */
static zend_object_handlers phongo_handler_binary;
static void phongo_binary_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(binary, object);
zend_object_std_dtor(&intern->std);
if (intern->data) {
efree(intern->data);
}
if (intern->properties) {
zend_hash_release(intern->properties);
}
}
static zend_object* phongo_binary_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(binary, class_type);
intern->std.handlers = &phongo_handler_binary;
return &intern->std;
}
static zend_object* phongo_binary_clone_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(binary, object);
phongo_binary_t* new_intern;
zend_object* new_object;
new_object = phongo_binary_create_object(object->ce);
new_intern = Z_OBJ_BINARY(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
phongo_binary_init(new_intern, intern->data, intern->data_len, intern->type);
return new_object;
}
static int phongo_binary_compare_objects(zval* o1, zval* o2)
{
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* phongo_binary_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
HashTable* props = phongo_binary_get_properties_hash(object, true, true);
PHONGO_INTERN_FROM_Z_OBJ(binary, object);
if (intern->type == BSON_SUBTYPE_VECTOR) {
zval vector;
phongo_binary_get_vector_as_array(intern, &vector);
if (EG(exception)) {
return props;
}
zend_hash_str_update(props, "vector", sizeof("vector") - 1, &vector);
zval vector_type;
zend_object* vector_type_case = phongo_bson_vector_type_to_case(phongo_binary_get_vector_type(intern));
// The vector should always be valid by this point, but check for an error
if (!vector_type_case) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "Binary vector data is invalid");
return props;
}
ZVAL_OBJ_COPY(&vector_type, vector_type_case);
zend_hash_str_update(props, "vectorType", sizeof("vectorType") - 1, &vector_type);
}
return props;
}
static HashTable* phongo_binary_get_properties(zend_object* object)
{
return phongo_binary_get_properties_hash(object, false, false);
}
void phongo_binary_init_ce(INIT_FUNC_ARGS)
{
phongo_binary_ce = register_class_MongoDB_BSON_Binary(phongo_binary_interface_ce, phongo_json_serializable_ce, phongo_type_ce, zend_ce_stringable);
phongo_binary_ce->create_object = phongo_binary_create_object;
memcpy(&phongo_handler_binary, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_binary.compare = phongo_binary_compare_objects;
phongo_handler_binary.clone_obj = phongo_binary_clone_object;
phongo_handler_binary.get_debug_info = phongo_binary_get_debug_info;
phongo_handler_binary.get_properties = phongo_binary_get_properties;
phongo_handler_binary.free_obj = phongo_binary_free_object;
phongo_handler_binary.offset = offsetof(phongo_binary_t, std);
}
bool phongo_binary_new(zval* object, const char* data, size_t data_len, bson_subtype_t type)
{
object_init_ex(object, phongo_binary_ce);
return phongo_binary_init(Z_BINARY_OBJ_P(object), data, data_len, type);
}
static inline void phongo_binary_init_vector_from_bson_key(phongo_binary_t* intern, const bson_t* doc, const char* key)
{
bson_iter_t iter;
if (!(bson_iter_init_find(&iter, doc, key) && BSON_ITER_HOLDS_VECTOR(&iter))) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "bson_iter_init_find failed to find binary vector in key \"%s\"", key);
return;
}
uint32_t data_len;
const uint8_t* data;
bson_iter_binary(&iter, NULL, &data_len, &data);
phongo_binary_init(intern, (const char*) data, data_len, BSON_SUBTYPE_VECTOR);
}
static void phongo_binary_init_vector_from_float32_array(phongo_binary_t* intern, HashTable* vector)
{
if (!zend_array_is_list(vector)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected vector to be a list");
return;
}
const size_t vector_len = zend_array_count(vector);
bson_t doc = BSON_INITIALIZER;
bson_vector_float32_view_t view;
if (!BSON_APPEND_VECTOR_FLOAT32_UNINIT(&doc, "vector", vector_len, &view)) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "BSON_APPEND_VECTOR_FLOAT32_UNINIT failed for vector of size %zu", vector_len);
goto cleanup;
}
zval* val;
size_t i = 0;
ZEND_HASH_FOREACH_VAL_IND(vector, val)
{
if (Z_TYPE_P(val) != IS_DOUBLE) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected vector[%zu] to be a float, %s given", i, zend_zval_type_name(val));
goto cleanup;
}
float v = (float) Z_DVAL_P(val);
if (!bson_vector_float32_view_write(view, &v, 1, i)) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "bson_vector_float32_view_write failed to write vector[%zu]", i);
goto cleanup;
}
i += 1;
}
ZEND_HASH_FOREACH_END();
phongo_binary_init_vector_from_bson_key(intern, &doc, "vector");
cleanup:
bson_destroy(&doc);
}
static void phongo_binary_init_vector_from_int8_array(phongo_binary_t* intern, HashTable* vector)
{
if (!zend_array_is_list(vector)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected vector to be a list");
return;
}
const size_t vector_len = zend_array_count(vector);
bson_t doc = BSON_INITIALIZER;
bson_vector_int8_view_t view;
if (!BSON_APPEND_VECTOR_INT8_UNINIT(&doc, "vector", vector_len, &view)) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "BSON_APPEND_VECTOR_INT8_UNINIT failed for vector of size %zu", vector_len);
goto cleanup;
}
zval* val;
size_t i = 0;
ZEND_HASH_FOREACH_VAL_IND(vector, val)
{
if (Z_TYPE_P(val) != IS_LONG) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected vector[%zu] to be an integer, %s given", i, zend_zval_type_name(val));
goto cleanup;
}
if (Z_LVAL_P(val) < INT8_MIN || Z_LVAL_P(val) > INT8_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected vector[%zu] to be a signed 8-bit integer, %" PHONGO_LONG_FORMAT " given", i, Z_LVAL_P(val));
goto cleanup;
}
int8_t v = (int8_t) Z_LVAL_P(val);
if (!bson_vector_int8_view_write(view, &v, 1, i)) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "bson_vector_int8_view_write failed to write vector[%zu]", i);
goto cleanup;
}
i += 1;
}
ZEND_HASH_FOREACH_END();
phongo_binary_init_vector_from_bson_key(intern, &doc, "vector");
cleanup:
bson_destroy(&doc);
}
static void phongo_binary_init_vector_from_packed_bit_array(phongo_binary_t* intern, HashTable* vector)
{
if (!zend_array_is_list(vector)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected vector to be a list");
return;
}
const size_t vector_len = zend_array_count(vector);
bson_t doc = BSON_INITIALIZER;
bson_vector_packed_bit_view_t view;
if (!BSON_APPEND_VECTOR_PACKED_BIT_UNINIT(&doc, "vector", vector_len, &view)) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "BSON_APPEND_VECTOR_PACKED_BIT_UNINIT failed for vector of size %zu", vector_len);
goto cleanup;
}
zval* val;
size_t i = 0;
ZEND_HASH_FOREACH_VAL_IND(vector, val)
{
if (Z_TYPE_P(val) != IS_LONG && Z_TYPE_P(val) != IS_TRUE && Z_TYPE_P(val) != IS_FALSE) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected vector[%zu] to be 0, 1, or a boolean, %s given", i, zend_zval_type_name(val));
goto cleanup;
}
if (Z_TYPE_P(val) == IS_LONG && Z_LVAL_P(val) != 0 && Z_LVAL_P(val) != 1) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected vector[%zu] to be 0 or 1, %" PHONGO_LONG_FORMAT " given", i, Z_LVAL_P(val));
goto cleanup;
}
bool v = zend_is_true(val);
if (!bson_vector_packed_bit_view_pack_bool(view, &v, 1, i)) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "bson_vector_packed_bit_view_pack_bool failed to write vector[%zu]", i);
goto cleanup;
}
i += 1;
}
ZEND_HASH_FOREACH_END();
phongo_binary_init_vector_from_bson_key(intern, &doc, "vector");
cleanup:
bson_destroy(&doc);
}
static PHP_METHOD(MongoDB_BSON_Binary, fromVector)
{
HashTable* vector;
zend_object* type;
object_init_ex(return_value, phongo_binary_ce);
PHONGO_INTERN_FROM_ZVAL(binary, return_value);
PHONGO_PARSE_PARAMETERS_START(2, 2)
Z_PARAM_ARRAY_HT(vector)
Z_PARAM_OBJ_OF_CLASS(type, phongo_vectortype_ce)
PHONGO_PARSE_PARAMETERS_END();
switch (phongo_bson_vector_type_from_case(type)) {
case PHONGO_BSON_VECTOR_TYPE_FLOAT32:
phongo_binary_init_vector_from_float32_array(intern, vector);
return;
case PHONGO_BSON_VECTOR_TYPE_INT8:
phongo_binary_init_vector_from_int8_array(intern, vector);
return;
case PHONGO_BSON_VECTOR_TYPE_PACKED_BIT:
phongo_binary_init_vector_from_packed_bit_array(intern, vector);
return;
default:
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Unsupported binary vector type: %s", Z_STRVAL_P(zend_enum_fetch_case_name(type)));
RETURN_THROWS();
}
}
static phongo_bson_vector_type_t phongo_binary_get_vector_type_from_data(const uint8_t* data, uint32_t data_len)
{
if (bson_vector_int8_const_view_init(NULL, data, data_len)) {
return PHONGO_BSON_VECTOR_TYPE_INT8;
}
if (bson_vector_float32_const_view_init(NULL, data, data_len)) {
return PHONGO_BSON_VECTOR_TYPE_FLOAT32;
}
if (bson_vector_packed_bit_const_view_init(NULL, data, data_len)) {
return PHONGO_BSON_VECTOR_TYPE_PACKED_BIT;
}
return PHONGO_BSON_VECTOR_TYPE_UNKNOWN;
}
static phongo_bson_vector_type_t phongo_binary_get_vector_type(const phongo_binary_t* intern)
{
return phongo_binary_get_vector_type_from_data((const uint8_t*) intern->data, intern->data_len);
}
static PHP_METHOD(MongoDB_BSON_Binary, getVectorType)
{
PHONGO_INTERN_FROM_THIS(binary);
PHONGO_PARSE_PARAMETERS_NONE();
if (intern->type != BSON_SUBTYPE_VECTOR) {
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Expected Binary of type vector (%" PRId8 ") but it is %" PHONGO_LONG_FORMAT, BSON_SUBTYPE_VECTOR, intern->type);
RETURN_THROWS();
}
const char* type_case = phongo_bson_vector_type_to_name(phongo_binary_get_vector_type(intern));
// The vector should always be valid by this point, but check for an error
if (!type_case) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "Binary vector data is invalid");
RETURN_THROWS();
}
RETVAL_OBJ_COPY(zend_enum_get_case_cstr(phongo_vectortype_ce, type_case));
}
static void phongo_binary_get_vector_as_array(const phongo_binary_t* intern, zval* return_value)
{
bson_t tmp_doc = BSON_INITIALIZER;
switch (phongo_binary_get_vector_type(intern)) {
case PHONGO_BSON_VECTOR_TYPE_INT8: {
bson_vector_int8_const_view_t view;
if (!bson_vector_int8_const_view_init(&view, (const uint8_t*) intern->data, intern->data_len) ||
!BSON_APPEND_ARRAY_FROM_VECTOR_INT8(&tmp_doc, "vector", view)) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "Failed to convert binary vector data to an array");
bson_destroy(&tmp_doc);
RETURN_THROWS();
}
break;
}
case PHONGO_BSON_VECTOR_TYPE_FLOAT32: {
bson_vector_float32_const_view_t view;
if (!bson_vector_float32_const_view_init(&view, (const uint8_t*) intern->data, intern->data_len) ||
!BSON_APPEND_ARRAY_FROM_VECTOR_FLOAT32(&tmp_doc, "vector", view)) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "Failed to convert binary vector data to an array");
bson_destroy(&tmp_doc);
RETURN_THROWS();
}
break;
}
case PHONGO_BSON_VECTOR_TYPE_PACKED_BIT: {
bson_vector_packed_bit_const_view_t view;
if (!bson_vector_packed_bit_const_view_init(&view, (const uint8_t*) intern->data, intern->data_len) ||
!BSON_APPEND_ARRAY_FROM_VECTOR_PACKED_BIT(&tmp_doc, "vector", view)) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "Failed to convert binary vector data to an array");
bson_destroy(&tmp_doc);
RETURN_THROWS();
}
break;
}
default:
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "Binary vector data is invalid");
RETURN_THROWS();
}
bson_iter_t iter;
if (!(bson_iter_init_find(&iter, &tmp_doc, "vector") && BSON_ITER_HOLDS_ARRAY(&iter))) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "bson_iter_init_find failed for appended vector");
bson_destroy(&tmp_doc);
RETURN_THROWS();
}
uint32_t data_len;
const uint8_t* data;
bson_iter_array(&iter, &data_len, &data);
bson_t tmp_vector = BSON_INITIALIZER;
if (!bson_init_static(&tmp_vector, data, data_len)) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "bson_init_static failed for appended vector");
bson_destroy(&tmp_doc);
RETURN_THROWS();
}
phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
state.is_visiting_array = true;
if (!phongo_bson_to_zval_ex(&tmp_vector, &state)) {
// Exception already thrown
bson_destroy(&tmp_doc);
zval_ptr_dtor(&state.zchild);
phongo_bson_typemap_dtor(&state.map);
RETURN_THROWS();
}
bson_destroy(&tmp_doc);
phongo_bson_typemap_dtor(&state.map);
RETURN_ZVAL(&state.zchild, 0, 1);
}
static PHP_METHOD(MongoDB_BSON_Binary, toArray)
{
PHONGO_INTERN_FROM_THIS(binary);
PHONGO_PARSE_PARAMETERS_NONE();
if (intern->type != BSON_SUBTYPE_VECTOR) {
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Expected Binary of type vector (%" PRId8 ") but it is %" PHONGO_LONG_FORMAT, BSON_SUBTYPE_VECTOR, intern->type);
RETURN_THROWS();
}
phongo_binary_get_vector_as_array(intern, return_value);
}
mongodb-2.5.5/src/BSON/Binary.h 0000644 0001751 0001751 00000001474 15264101572 013030 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.5.5/src/BSON/BinaryInterface.c 0000644 0001751 0001751 00000001535 15264101572 014642 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 "phongo.h"
#include "BinaryInterface_arginfo.h"
zend_class_entry* phongo_binary_interface_ce;
void phongo_binary_interface_init_ce(INIT_FUNC_ARGS)
{
phongo_binary_interface_ce = register_class_MongoDB_BSON_BinaryInterface();
}
mongodb-2.5.5/src/BSON/BinaryInterface_arginfo.h 0000644 0001751 0001751 00000003410 15264101572 016346 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 6bfe5c53bac9804fdb1498594a81962cf1b6c6c7 */
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[] = {
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("getData", NULL, arginfo_class_MongoDB_BSON_BinaryInterface_getData, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("getData", NULL, arginfo_class_MongoDB_BSON_BinaryInterface_getData, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("getType", NULL, arginfo_class_MongoDB_BSON_BinaryInterface_getType, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("getType", NULL, arginfo_class_MongoDB_BSON_BinaryInterface_getType, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("__toString", NULL, arginfo_class_MongoDB_BSON_BinaryInterface___toString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("__toString", NULL, arginfo_class_MongoDB_BSON_BinaryInterface___toString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
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.5.5/src/BSON/Binary_arginfo.h 0000644 0001751 0001751 00000021173 15264101572 014533 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 897b6b28554999a55d29f4fa299a210c608b400e */
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_OBJ_INFO_EX(arginfo_class_MongoDB_BSON_Binary_fromVector, 0, 2, MongoDB\\BSON\\Binary, 0)
ZEND_ARG_TYPE_INFO(0, vector, IS_ARRAY, 0)
ZEND_ARG_OBJ_INFO(0, vectorType, MongoDB\\BSON\\VectorType, 0)
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_getVectorType, 0, 0, MongoDB\\BSON\\VectorType, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_class_MongoDB_BSON_Binary_toArray, 0, 0, IS_ARRAY, 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()
#define arginfo_class_MongoDB_BSON_Binary___serialize arginfo_class_MongoDB_BSON_Binary_toArray
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, fromVector);
static ZEND_METHOD(MongoDB_BSON_Binary, getData);
static ZEND_METHOD(MongoDB_BSON_Binary, getType);
static ZEND_METHOD(MongoDB_BSON_Binary, getVectorType);
static ZEND_METHOD(MongoDB_BSON_Binary, toArray);
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, fromVector, arginfo_class_MongoDB_BSON_Binary_fromVector, ZEND_ACC_PUBLIC|ZEND_ACC_STATIC|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, getVectorType, arginfo_class_MongoDB_BSON_Binary_getVectorType, ZEND_ACC_PUBLIC|ZEND_ACC_FINAL)
ZEND_ME(MongoDB_BSON_Binary, toArray, arginfo_class_MongoDB_BSON_Binary_toArray, 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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
#endif
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_VECTOR_value;
ZVAL_LONG(&const_TYPE_VECTOR_value, BSON_SUBTYPE_VECTOR);
zend_string *const_TYPE_VECTOR_name = zend_string_init_interned("TYPE_VECTOR", sizeof("TYPE_VECTOR") - 1, 1);
zend_declare_class_constant_ex(class_entry, const_TYPE_VECTOR_name, &const_TYPE_VECTOR_value, ZEND_ACC_PUBLIC, NULL);
zend_string_release(const_TYPE_VECTOR_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.5.5/src/BSON/DBPointer.c 0000644 0001751 0001751 00000016314 15264101572 013424 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 "phongo.h"
#include "phongo_error.h"
#include "DBPointer_arginfo.h"
zend_class_entry* phongo_dbpointer_ce;
/* Initialize the object and return whether it was successful. An exception will
* be thrown on error. */
static bool phongo_dbpointer_init(phongo_dbpointer_t* intern, const char* ref, size_t ref_len, const char* id, size_t id_len)
{
if (ref_len > PHONGO_BSON_MAX_LENGTH) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected ref length to be <= %" PRId32 " bytes, %zu given", (int32_t) PHONGO_BSON_MAX_LENGTH, ref_len);
return false;
}
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 phongo_dbpointer_init_from_hash(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 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(phongo_dbpointer_ce->name));
return false;
}
HashTable* phongo_dbpointer_get_properties_hash(zend_object* object, bool is_temp)
{
PHONGO_INTERN_FROM_Z_OBJ(dbpointer, object);
HashTable* props;
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)
{
PHONGO_INTERN_FROM_THIS(dbpointer);
char* retval;
int retval_len;
PHONGO_PARSE_PARAMETERS_NONE();
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)
{
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
PHONGO_INTERN_INIT_EX(dbpointer, return_value);
props = Z_ARRVAL_P(array);
phongo_dbpointer_init_from_hash(intern, props);
}
static PHP_METHOD(MongoDB_BSON_DBPointer, jsonSerialize)
{
PHONGO_INTERN_FROM_THIS(dbpointer);
zval zdb_pointer;
zval zoid;
PHONGO_PARSE_PARAMETERS_NONE();
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(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();
phongo_dbpointer_init_from_hash(Z_DBPOINTER_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\DBPointer object handlers */
static zend_object_handlers phongo_handler_dbpointer;
static void phongo_dbpointer_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(dbpointer, object);
zend_object_std_dtor(&intern->std);
if (intern->ref) {
efree(intern->ref);
}
if (intern->properties) {
zend_hash_release(intern->properties);
}
}
zend_object* phongo_dbpointer_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(dbpointer, class_type);
intern->std.handlers = &phongo_handler_dbpointer;
return &intern->std;
}
static zend_object* phongo_dbpointer_clone_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(dbpointer, object);
phongo_dbpointer_t* new_intern;
zend_object* new_object;
new_object = phongo_dbpointer_create_object(object->ce);
new_intern = Z_OBJ_DBPOINTER(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
phongo_dbpointer_init(new_intern, intern->ref, intern->ref_len, intern->id, 24);
return new_object;
}
static int phongo_dbpointer_compare_objects(zval* o1, zval* o2)
{
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* phongo_dbpointer_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return phongo_dbpointer_get_properties_hash(object, true);
}
static HashTable* phongo_dbpointer_get_properties(zend_object* object)
{
return phongo_dbpointer_get_properties_hash(object, false);
}
void phongo_dbpointer_init_ce(INIT_FUNC_ARGS)
{
phongo_dbpointer_ce = register_class_MongoDB_BSON_DBPointer(phongo_json_serializable_ce, phongo_type_ce, zend_ce_stringable);
phongo_dbpointer_ce->create_object = phongo_dbpointer_create_object;
memcpy(&phongo_handler_dbpointer, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_dbpointer.compare = phongo_dbpointer_compare_objects;
phongo_handler_dbpointer.clone_obj = phongo_dbpointer_clone_object;
phongo_handler_dbpointer.get_debug_info = phongo_dbpointer_get_debug_info;
phongo_handler_dbpointer.get_properties = phongo_dbpointer_get_properties;
phongo_handler_dbpointer.free_obj = phongo_dbpointer_free_object;
phongo_handler_dbpointer.offset = offsetof(phongo_dbpointer_t, std);
}
bool phongo_dbpointer_new(zval* object, const char* ref, size_t ref_len, const bson_oid_t* oid)
{
PHONGO_INTERN_INIT_EX(dbpointer, object);
intern->ref = estrndup(ref, ref_len);
intern->ref_len = ref_len;
bson_oid_to_string(oid, intern->id);
return true;
}
mongodb-2.5.5/src/BSON/DBPointer.h 0000644 0001751 0001751 00000001444 15264101572 013427 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.5.5/src/BSON/DBPointer_arginfo.h 0000644 0001751 0001751 00000005553 15264101572 015141 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: d47b4fcf2b42ddd4e11d899123e6354403466a4b */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
#endif
zend_class_implements(class_entry, 3, class_entry_JsonSerializable, class_entry_MongoDB_BSON_Type, class_entry_Stringable);
return class_entry;
}
mongodb-2.5.5/src/BSON/Decimal128.c 0000644 0001751 0001751 00000014333 15264101572 013366 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 "phongo.h"
#include "phongo_error.h"
#include "Decimal128_arginfo.h"
zend_class_entry* phongo_decimal128_ce;
/* Initialize the object and return whether it was successful. An exception will
* be thrown on error. */
static bool phongo_decimal128_init(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 phongo_decimal128_init_from_hash(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 phongo_decimal128_init(intern, Z_STRVAL_P(dec));
}
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"dec\" string field", ZSTR_VAL(phongo_decimal128_ce->name));
return false;
}
static HashTable* phongo_decimal128_get_properties_hash(zend_object* object, bool is_temp)
{
PHONGO_INTERN_FROM_Z_OBJ(decimal128, object);
HashTable* props;
char outbuf[BSON_DECIMAL128_STRING] = "";
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)
{
PHONGO_INTERN_FROM_THIS(decimal128);
char* value;
size_t value_len;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STRING(value, value_len)
PHONGO_PARSE_PARAMETERS_END();
phongo_decimal128_init(intern, value);
}
static PHP_METHOD(MongoDB_BSON_Decimal128, __set_state)
{
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
PHONGO_INTERN_INIT_EX(decimal128, return_value);
props = Z_ARRVAL_P(array);
phongo_decimal128_init_from_hash(intern, props);
}
static PHP_METHOD(MongoDB_BSON_Decimal128, __toString)
{
PHONGO_INTERN_FROM_THIS(decimal128);
char outbuf[BSON_DECIMAL128_STRING];
PHONGO_PARSE_PARAMETERS_NONE();
bson_decimal128_to_string(&intern->decimal, outbuf);
RETURN_STRING(outbuf);
}
static PHP_METHOD(MongoDB_BSON_Decimal128, jsonSerialize)
{
PHONGO_INTERN_FROM_THIS(decimal128);
char outbuf[BSON_DECIMAL128_STRING] = "";
PHONGO_PARSE_PARAMETERS_NONE();
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(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();
phongo_decimal128_init_from_hash(Z_DECIMAL128_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\Decimal128 object handlers */
static zend_object_handlers phongo_handler_decimal128;
static void phongo_decimal128_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(decimal128, object);
zend_object_std_dtor(&intern->std);
if (intern->properties) {
zend_hash_release(intern->properties);
}
}
static zend_object* phongo_decimal128_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(decimal128, class_type);
intern->std.handlers = &phongo_handler_decimal128;
return &intern->std;
}
static zend_object* phongo_decimal128_clone_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(decimal128, object);
phongo_decimal128_t* new_intern;
zend_object* new_object;
new_object = 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* phongo_decimal128_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return phongo_decimal128_get_properties_hash(object, true);
}
static HashTable* phongo_decimal128_get_properties(zend_object* object)
{
return phongo_decimal128_get_properties_hash(object, false);
}
void phongo_decimal128_init_ce(INIT_FUNC_ARGS)
{
phongo_decimal128_ce = register_class_MongoDB_BSON_Decimal128(phongo_decimal128_interface_ce, phongo_json_serializable_ce, phongo_type_ce, zend_ce_stringable);
phongo_decimal128_ce->create_object = phongo_decimal128_create_object;
memcpy(&phongo_handler_decimal128, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_decimal128.clone_obj = phongo_decimal128_clone_object;
phongo_handler_decimal128.get_debug_info = phongo_decimal128_get_debug_info;
phongo_handler_decimal128.get_properties = phongo_decimal128_get_properties;
phongo_handler_decimal128.free_obj = phongo_decimal128_free_object;
phongo_handler_decimal128.offset = offsetof(phongo_decimal128_t, std);
}
bool phongo_decimal128_new(zval* object, const bson_decimal128_t* decimal)
{
PHONGO_INTERN_INIT_EX(decimal128, object);
memcpy(&intern->decimal, decimal, sizeof(bson_decimal128_t));
intern->initialized = true;
return true;
}
mongodb-2.5.5/src/BSON/Decimal128.h 0000644 0001751 0001751 00000001422 15264101572 013366 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.5.5/src/BSON/Decimal128Interface.c 0000644 0001751 0001751 00000001561 15264101572 015206 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 "phongo.h"
#include "Decimal128Interface_arginfo.h"
zend_class_entry* phongo_decimal128_interface_ce;
void phongo_decimal128_interface_init_ce(INIT_FUNC_ARGS)
{
phongo_decimal128_interface_ce = register_class_MongoDB_BSON_Decimal128Interface();
}
mongodb-2.5.5/src/BSON/Decimal128Interface_arginfo.h 0000644 0001751 0001751 00000001740 15264101572 016717 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: fd63ec36126fe9b35fb30affbcd4a0861b5c85f8 */
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[] = {
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("__toString", NULL, arginfo_class_MongoDB_BSON_Decimal128Interface___toString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("__toString", NULL, arginfo_class_MongoDB_BSON_Decimal128Interface___toString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
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.5.5/src/BSON/Decimal128_arginfo.h 0000644 0001751 0001751 00000006041 15264101572 015075 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: c547ea884b494f5e317844066b582294843dd903 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
#endif
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.5.5/src/BSON/Document.c 0000644 0001751 0001751 00000037201 15264101572 013352 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 "phongo.h"
#include "phongo_error.h"
#include "phongo_bson_encode.h"
#include "BSON/Document_arginfo.h"
#include "BSON/Iterator.h"
zend_class_entry* phongo_document_ce;
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool phongo_document_init_from_hash(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(phongo_document_ce->name));
return false;
}
return true;
}
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"data\" string field", ZSTR_VAL(phongo_document_ce->name));
return false;
}
static HashTable* phongo_document_get_properties_hash(zend_object* object, bool is_temp, int size)
{
PHONGO_INTERN_FROM_Z_OBJ(document, object);
HashTable* props;
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;
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;
}
PHONGO_INTERN_INIT_EX(document, &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;
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;
}
PHONGO_INTERN_INIT_EX(document, &zv);
intern->bson = bson;
RETURN_ZVAL(&zv, 1, 1);
}
static PHP_METHOD(MongoDB_BSON_Document, fromPHP)
{
zval zv;
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY_OR_OBJECT(data)
PHONGO_PARSE_PARAMETERS_END();
PHONGO_INTERN_INIT_EX(document, &zv);
intern->bson = bson_new();
// Explicitly allow constructing a Document from a PackedArray
phongo_zval_to_bson(data, PHONGO_BSON_ALLOW_ROOT_ARRAY, intern->bson, NULL);
RETURN_ZVAL(&zv, 1, 1);
}
static bool phongo_document_get(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 phongo_document_get_by_zval(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 (!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)
{
PHONGO_INTERN_FROM_THIS(document);
char* key;
size_t key_len;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STRING(key, key_len)
PHONGO_PARSE_PARAMETERS_END();
// May throw, in which case we do nothing
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 phongo_document_has(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 phongo_document_has_by_zval(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 (!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)
{
PHONGO_INTERN_FROM_THIS(document);
char* key;
size_t key_len;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_STRING(key, key_len)
PHONGO_PARSE_PARAMETERS_END();
RETURN_BOOL(phongo_document_has(intern, key, key_len));
}
static PHP_METHOD(MongoDB_BSON_Document, toCanonicalExtendedJSON)
{
PHONGO_INTERN_FROM_THIS(document);
PHONGO_PARSE_PARAMETERS_NONE();
phongo_bson_to_json(return_value, intern->bson, PHONGO_JSON_MODE_CANONICAL);
}
static PHP_METHOD(MongoDB_BSON_Document, toRelaxedExtendedJSON)
{
PHONGO_INTERN_FROM_THIS(document);
PHONGO_PARSE_PARAMETERS_NONE();
phongo_bson_to_json(return_value, intern->bson, PHONGO_JSON_MODE_RELAXED);
}
static PHP_METHOD(MongoDB_BSON_Document, toPHP)
{
PHONGO_INTERN_FROM_THIS(document);
zval* typemap = NULL;
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 (!phongo_bson_typemap_to_state(typemap, &state.map)) {
return;
}
state.map.int64_as_object = true;
if (!phongo_bson_to_zval_ex(intern->bson, &state)) {
zval_ptr_dtor(&state.zchild);
phongo_bson_typemap_dtor(&state.map);
RETURN_NULL();
}
phongo_bson_typemap_dtor(&state.map);
RETURN_ZVAL(&state.zchild, 0, 1);
}
static PHP_METHOD(MongoDB_BSON_Document, offsetExists)
{
PHONGO_INTERN_FROM_THIS(document);
zval* offset;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ZVAL(offset)
PHONGO_PARSE_PARAMETERS_END();
RETURN_BOOL(phongo_document_has_by_zval(intern, offset));
}
static PHP_METHOD(MongoDB_BSON_Document, offsetGet)
{
PHONGO_INTERN_FROM_THIS(document);
zval* offset;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ZVAL(offset)
PHONGO_PARSE_PARAMETERS_END();
// May throw, in which case we do nothing
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(phongo_document_ce->name));
}
static PHP_METHOD(MongoDB_BSON_Document, offsetUnset)
{
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Cannot unset %s property", ZSTR_VAL(phongo_document_ce->name));
}
static PHP_METHOD(MongoDB_BSON_Document, __toString)
{
PHONGO_INTERN_FROM_THIS(document);
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRINGL((const char*) bson_get_data(intern->bson), intern->bson->len);
}
static PHP_METHOD(MongoDB_BSON_Document, __set_state)
{
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
PHONGO_INTERN_INIT_EX(document, return_value);
props = Z_ARRVAL_P(array);
phongo_document_init_from_hash(intern, props);
}
static PHP_METHOD(MongoDB_BSON_Document, __serialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_ARR(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();
phongo_document_init_from_hash(Z_DOCUMENT_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\BSON object handlers */
static zend_object_handlers phongo_handler_document;
static void phongo_document_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(document, object);
zend_object_std_dtor(&intern->std);
if (intern->bson) {
bson_destroy(intern->bson);
}
if (intern->properties) {
zend_hash_release(intern->properties);
}
}
static zend_object* phongo_document_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(document, class_type);
intern->std.handlers = &phongo_handler_document;
return &intern->std;
}
static zend_object* phongo_document_clone_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(document, object);
phongo_document_t* new_intern;
zend_object* new_object;
new_object = 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 phongo_document_compare_objects(zval* o1, zval* o2)
{
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* phongo_document_get_debug_info(zend_object* object, int* is_temp)
{
PHONGO_INTERN_FROM_Z_OBJ(document, object);
HashTable* props;
*is_temp = 1;
/* This get_debug_info handler reports an additional property. This does not
* conflict with other uses of phongo_document_get_properties_hash since
* we always allocated a new HashTable with is_temp=true. */
props = phongo_document_get_properties_hash(object, true, 2);
{
phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
state.map.array.type = PHONGO_TYPEMAP_BSON;
state.map.document.type = PHONGO_TYPEMAP_BSON;
if (!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* phongo_document_get_properties(zend_object* object)
{
return phongo_document_get_properties_hash(object, false, 1);
}
zval* phongo_document_read_property(zend_object* object, zend_string* member, int type, void** cache_slot, zval* rv)
{
PHONGO_INTERN_FROM_Z_OBJ(document, object);
if (!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* 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(phongo_document_ce->name));
return value;
}
int phongo_document_has_property(zend_object* object, zend_string* member, int has_set_exists, void** cache_slot)
{
PHONGO_INTERN_FROM_Z_OBJ(document, object);
return phongo_document_has(intern, ZSTR_VAL(member), ZSTR_LEN(member));
}
void 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(phongo_document_ce->name));
}
zval* phongo_document_read_dimension(zend_object* object, zval* offset, int type, zval* rv)
{
PHONGO_INTERN_FROM_Z_OBJ(document, object);
if (!phongo_document_get_by_zval(intern, offset, rv, type == BP_VAR_IS)) {
// Exception already thrown
return &EG(uninitialized_zval);
}
return rv;
}
void phongo_document_write_dimension(zend_object* object, zval* offset, zval* value)
{
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Cannot write to %s property", ZSTR_VAL(phongo_document_ce->name));
}
int phongo_document_has_dimension(zend_object* object, zval* member, int check_empty)
{
PHONGO_INTERN_FROM_Z_OBJ(document, object);
return phongo_document_has_by_zval(intern, member);
}
void phongo_document_unset_dimension(zend_object* object, zval* offset)
{
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Cannot unset %s property", ZSTR_VAL(phongo_document_ce->name));
}
void phongo_document_init_ce(INIT_FUNC_ARGS)
{
phongo_document_ce = register_class_MongoDB_BSON_Document(zend_ce_aggregate, zend_ce_arrayaccess, phongo_type_ce, zend_ce_stringable);
phongo_document_ce->create_object = phongo_document_create_object;
memcpy(&phongo_handler_document, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_document.compare = phongo_document_compare_objects;
phongo_handler_document.clone_obj = phongo_document_clone_object;
phongo_handler_document.get_debug_info = phongo_document_get_debug_info;
phongo_handler_document.get_properties = phongo_document_get_properties;
phongo_handler_document.free_obj = phongo_document_free_object;
phongo_handler_document.read_property = phongo_document_read_property;
phongo_handler_document.write_property = phongo_document_write_property;
phongo_handler_document.has_property = phongo_document_has_property;
phongo_handler_document.unset_property = phongo_document_unset_property;
phongo_handler_document.read_dimension = phongo_document_read_dimension;
phongo_handler_document.write_dimension = phongo_document_write_dimension;
phongo_handler_document.has_dimension = phongo_document_has_dimension;
phongo_handler_document.unset_dimension = phongo_document_unset_dimension;
phongo_handler_document.offset = offsetof(phongo_document_t, std);
}
bool phongo_document_new(zval* object, bson_t* bson, bool copy)
{
PHONGO_INTERN_INIT_EX(document, object);
intern->bson = copy ? bson_copy(bson) : bson;
return true;
}
mongodb-2.5.5/src/BSON/Document.h 0000644 0001751 0001751 00000001401 15264101572 013350 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.5.5/src/BSON/Document_arginfo.h 0000644 0001751 0001751 00000016013 15264101572 015062 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 0855bcff12d1a521f0a433754675b7e1e316523c */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
#endif
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.5.5/src/BSON/Int64.c 0000644 0001751 0001751 00000037603 15264101572 012506 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 "phongo.h"
#include "phongo_error.h"
#include "phongo_util.h"
#include "Int64_arginfo.h"
zend_class_entry* phongo_int64_ce;
/* Initialize the object and return whether it was successful. */
static bool phongo_int64_init(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 phongo_int64_init_from_string(phongo_int64_t* intern, const char* s_integer, size_t s_integer_len)
{
int64_t integer;
if (!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(phongo_int64_ce->name));
return false;
}
return 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 phongo_int64_init_from_hash(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 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(phongo_int64_ce->name));
return false;
}
HashTable* phongo_int64_get_properties_hash(zend_object* object, bool is_temp)
{
PHONGO_INTERN_FROM_Z_OBJ(int64, object);
HashTable* props;
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)
{
PHONGO_INTERN_FROM_THIS(int64);
zval* value;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ZVAL(value);
PHONGO_PARSE_PARAMETERS_END();
if (Z_TYPE_P(value) == IS_STRING) {
phongo_int64_init_from_string(intern, Z_STRVAL_P(value), Z_STRLEN_P(value));
} else if (Z_TYPE_P(value) == IS_LONG) {
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)
{
PHONGO_INTERN_FROM_THIS(int64);
PHONGO_PARSE_PARAMETERS_NONE();
ZVAL_INT64_STRING(return_value, intern->integer);
}
static PHP_METHOD(MongoDB_BSON_Int64, __set_state)
{
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
PHONGO_INTERN_INIT_EX(int64, return_value);
props = Z_ARRVAL_P(array);
phongo_int64_init_from_hash(intern, props);
}
static PHP_METHOD(MongoDB_BSON_Int64, jsonSerialize)
{
PHONGO_INTERN_FROM_THIS(int64);
PHONGO_PARSE_PARAMETERS_NONE();
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(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();
phongo_int64_init_from_hash(Z_INT64_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\Int64 object handlers */
static zend_object_handlers phongo_handler_int64;
static void phongo_int64_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(int64, object);
zend_object_std_dtor(&intern->std);
if (intern->properties) {
zend_hash_release(intern->properties);
}
}
zend_object* phongo_int64_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(int64, class_type);
intern->std.handlers = &phongo_handler_int64;
return &intern->std;
}
static zend_object* phongo_int64_clone_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(int64, object);
phongo_int64_t* new_intern;
zend_object* new_object;
new_object = phongo_int64_create_object(object->ce);
new_intern = Z_OBJ_INT64(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
phongo_int64_init(new_intern, intern->integer);
return new_object;
}
static bool phongo_int64_is_int64_object(zval* object)
{
if (Z_TYPE_P(object) != IS_OBJECT) {
return false;
}
return Z_OBJ_P(object)->ce == phongo_int64_ce;
}
static bool phongo_int64_is_long_or_double(zval* value)
{
return Z_TYPE_P(value) == IS_LONG || Z_TYPE_P(value) == IS_DOUBLE;
}
static int phongo_int64_compare_int64_objects(zval* o1, zval* o2)
{
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 phongo_int64_compare_with_long_or_float(zval* object, zval* value)
{
PHONGO_INTERN_FROM_ZVAL(int64, object);
int64_t long_value;
double double_value;
assert(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 phongo_int64_compare_objects(zval* o1, zval* o2)
{
if (phongo_int64_is_int64_object(o1) && phongo_int64_is_int64_object(o2)) {
return phongo_int64_compare_int64_objects(o1, o2);
}
if (phongo_int64_is_int64_object(o1) && phongo_int64_is_long_or_double(o2)) {
return phongo_int64_compare_with_long_or_float(o1, o2);
}
if (phongo_int64_is_long_or_double(o1) && phongo_int64_is_int64_object(o2)) {
// Invert the result as we're flipping the values used for comparison
return -1 * phongo_int64_compare_with_long_or_float(o2, o1);
}
ZEND_COMPARE_OBJECTS_FALLBACK(o1, o2);
return 0;
}
static zend_result phongo_int64_cast_object(zend_object* readobj, zval* retval, int type)
{
PHONGO_INTERN_FROM_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 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)) == 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 phongo_int64_t
* results in a 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 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);
if (value2 < 0) {
zend_throw_exception(zend_ce_arithmetic_error, "Bit shift by negative number", 0);
return FAILURE;
}
OPERATION_RESULT_INT64(value2 >= 64 ? 0 : (int64_t) ((uint64_t) value1 << value2));
return SUCCESS;
case ZEND_SR:
PHONGO_GET_INT64(value2, op2);
if (value2 < 0) {
zend_throw_exception(zend_ce_arithmetic_error, "Bit shift by negative number", 0);
return FAILURE;
}
OPERATION_RESULT_INT64(value2 >= 64 ? (value1 < 0 ? -1 : 0) : 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 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 = 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* phongo_int64_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return phongo_int64_get_properties_hash(object, true);
}
static HashTable* phongo_int64_get_properties(zend_object* object)
{
return phongo_int64_get_properties_hash(object, false);
}
void phongo_int64_init_ce(INIT_FUNC_ARGS)
{
phongo_int64_ce = register_class_MongoDB_BSON_Int64(phongo_json_serializable_ce, phongo_type_ce, zend_ce_stringable);
phongo_int64_ce->create_object = phongo_int64_create_object;
memcpy(&phongo_handler_int64, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_int64.compare = phongo_int64_compare_objects;
phongo_handler_int64.clone_obj = phongo_int64_clone_object;
phongo_handler_int64.get_debug_info = phongo_int64_get_debug_info;
phongo_handler_int64.get_properties = phongo_int64_get_properties;
phongo_handler_int64.free_obj = phongo_int64_free_object;
phongo_handler_int64.offset = offsetof(phongo_int64_t, std);
phongo_handler_int64.cast_object = phongo_int64_cast_object;
phongo_handler_int64.do_operation = phongo_int64_do_operation;
}
bool phongo_int64_new(zval* object, int64_t integer)
{
PHONGO_INTERN_INIT_EX(int64, object);
intern->integer = integer;
intern->initialized = true;
return true;
}
mongodb-2.5.5/src/BSON/Int64.h 0000644 0001751 0001751 00000001355 15264101572 012506 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.5.5/src/BSON/Int64_arginfo.h 0000644 0001751 0001751 00000005465 15264101572 014221 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: e86cafa03de91adfee42f656658188da9cc9b973 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
#endif
zend_class_implements(class_entry, 3, class_entry_JsonSerializable, class_entry_MongoDB_BSON_Type, class_entry_Stringable);
return class_entry;
}
mongodb-2.5.5/src/BSON/Iterator.c 0000644 0001751 0001751 00000022613 15264101572 013366 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 "phongo.h"
#include "phongo_error.h"
#include "BSON/Iterator.h"
#include "BSON/Iterator_arginfo.h"
zend_class_entry* phongo_iterator_ce;
static const bson_t* phongo_iterator_get_bson_from_zval(zval* zbson)
{
if (Z_TYPE_P(zbson) != IS_OBJECT) {
return NULL;
}
if (instanceof_function(Z_OBJCE_P(zbson), phongo_document_ce)) {
return Z_DOCUMENT_OBJ_P(zbson)->bson;
} else if (instanceof_function(Z_OBJCE_P(zbson), phongo_packedarray_ce)) {
return Z_PACKEDARRAY_OBJ_P(zbson)->bson;
} else {
return NULL;
}
}
static bool phongo_iterator_init_with_zval(phongo_iterator_t* iterator, zval* zbson)
{
const bson_t* bson;
bson = 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), phongo_packedarray_ce)) {
iterator->is_array = true;
}
iterator->valid = bson_iter_next(&iterator->iter);
return true;
}
static void phongo_iterator_free_current(phongo_iterator_t* intern)
{
if (Z_ISUNDEF(intern->current)) {
return;
}
zval_ptr_dtor(&intern->current);
ZVAL_UNDEF(&intern->current);
}
static void phongo_iterator_build_current(phongo_iterator_t* intern)
{
phongo_iterator_free_current(intern);
phongo_bson_value_to_zval(bson_iter_value(&intern->iter), &intern->current);
}
static zval* phongo_iterator_get_current(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)) {
phongo_iterator_build_current(intern);
}
return &intern->current;
}
static void phongo_iterator_next(phongo_iterator_t* intern)
{
intern->valid = bson_iter_next(&intern->iter);
intern->key++;
phongo_iterator_free_current(intern);
}
static bool phongo_iterator_key(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 phongo_iterator_rewind(phongo_iterator_t* intern)
{
/* Don't re-initialise iterator if we're still on the first item */
if (intern->key == 0) {
return;
}
phongo_iterator_free_current(intern);
bson_iter_init(&intern->iter, phongo_iterator_get_bson_from_zval(&intern->bson));
intern->key = 0;
intern->valid = bson_iter_next(&intern->iter);
}
static HashTable* phongo_iterator_get_properties_hash(zend_object* object, bool is_temp)
{
PHONGO_INTERN_FROM_Z_OBJ(iterator, object);
HashTable* props;
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)
{
PHONGO_INTERN_FROM_THIS(iterator);
zval* data;
PHONGO_PARSE_PARAMETERS_NONE();
data = 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)
{
PHONGO_INTERN_FROM_THIS(iterator);
PHONGO_PARSE_PARAMETERS_NONE();
if (!phongo_iterator_key(intern, return_value)) {
// Exception already thrown
return;
}
}
static PHP_METHOD(MongoDB_BSON_Iterator, next)
{
PHONGO_INTERN_FROM_THIS(iterator);
PHONGO_PARSE_PARAMETERS_NONE();
phongo_iterator_next(intern);
}
static PHP_METHOD(MongoDB_BSON_Iterator, valid)
{
PHONGO_INTERN_FROM_THIS(iterator);
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_BOOL(intern->valid);
}
static PHP_METHOD(MongoDB_BSON_Iterator, rewind)
{
PHONGO_INTERN_FROM_THIS(iterator);
PHONGO_PARSE_PARAMETERS_NONE();
phongo_iterator_rewind(intern);
}
void phongo_iterator_init(zval* return_value, zval* document_or_packedarray)
{
PHONGO_INTERN_INIT_EX(iterator, return_value);
phongo_iterator_init_with_zval(intern, document_or_packedarray);
}
/* MongoDB\BSON\Iterator object handlers */
static zend_object_handlers phongo_handler_iterator;
static void phongo_iterator_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(iterator, object);
zend_object_std_dtor(&intern->std);
if (intern->properties) {
zend_hash_release(intern->properties);
}
phongo_iterator_free_current(intern);
zval_ptr_dtor(&intern->bson);
}
static zend_object* phongo_iterator_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(iterator, class_type);
intern->std.handlers = &phongo_handler_iterator;
return &intern->std;
}
static zend_object* phongo_iterator_clone_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(iterator, object);
phongo_iterator_t* new_intern;
zend_object* new_object;
new_object = phongo_iterator_create_object(object->ce);
new_intern = Z_OBJ_ITERATOR(new_object);
phongo_iterator_init_with_zval(new_intern, &intern->bson);
zend_objects_clone_members(&new_intern->std, &intern->std);
return new_object;
}
static HashTable* phongo_iterator_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return phongo_iterator_get_properties_hash(object, true);
}
static HashTable* phongo_iterator_get_properties(zend_object* object)
{
return phongo_iterator_get_properties_hash(object, false);
}
/* Iterator handlers */
static void phongo_iterator_it_dtor(zend_object_iterator* iter)
{
zval_ptr_dtor(&iter->data);
}
static PHONGO_ITERATOR_VALID_RESULT phongo_iterator_it_valid(zend_object_iterator* iter)
{
PHONGO_INTERN_FROM_ZVAL(iterator, &iter->data);
return intern->valid ? SUCCESS : FAILURE;
}
static zval* phongo_iterator_it_get_current_data(zend_object_iterator* iter)
{
PHONGO_INTERN_FROM_ZVAL(iterator, &iter->data);
return phongo_iterator_get_current(intern);
}
static void phongo_iterator_it_get_current_key(zend_object_iterator* iter, zval* key)
{
PHONGO_INTERN_FROM_ZVAL(iterator, &iter->data);
if (!phongo_iterator_key(intern, key)) {
// Exception already thrown
return;
}
}
static void phongo_iterator_it_move_forward(zend_object_iterator* iter)
{
PHONGO_INTERN_FROM_ZVAL(iterator, &iter->data);
phongo_iterator_next(intern);
}
static void phongo_iterator_it_rewind(zend_object_iterator* iter)
{
PHONGO_INTERN_FROM_ZVAL(iterator, &iter->data);
phongo_iterator_rewind(intern);
}
static HashTable* 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 phongo_iterator_it_funcs = {
phongo_iterator_it_dtor,
phongo_iterator_it_valid,
phongo_iterator_it_get_current_data,
phongo_iterator_it_get_current_key,
phongo_iterator_it_move_forward,
phongo_iterator_it_rewind,
NULL, /* invalidate_current */
phongo_iterator_it_get_gc
};
static zend_object_iterator* 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 = &phongo_iterator_it_funcs;
return iterator;
}
void phongo_iterator_init_ce(INIT_FUNC_ARGS)
{
phongo_iterator_ce = register_class_MongoDB_BSON_Iterator(zend_ce_iterator);
phongo_iterator_ce->create_object = phongo_iterator_create_object;
phongo_iterator_ce->get_iterator = phongo_iterator_get_iterator;
memcpy(&phongo_handler_iterator, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_iterator.clone_obj = phongo_iterator_clone_object;
phongo_handler_iterator.get_debug_info = phongo_iterator_get_debug_info;
phongo_handler_iterator.get_properties = phongo_iterator_get_properties;
phongo_handler_iterator.free_obj = phongo_iterator_free_object;
phongo_handler_iterator.offset = offsetof(phongo_iterator_t, std);
}
mongodb-2.5.5/src/BSON/Iterator.h 0000644 0001751 0001751 00000001403 15264101572 013365 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.5.5/src/BSON/Iterator_arginfo.h 0000644 0001751 0001751 00000004722 15264101572 015101 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 316ef74b784437b102af498e22dae771b85866d9 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
zend_class_implements(class_entry, 1, class_entry_Iterator);
return class_entry;
}
mongodb-2.5.5/src/BSON/Javascript.c 0000644 0001751 0001751 00000023350 15264101572 013702 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 "phongo.h"
#include "phongo_bson_encode.h"
#include "phongo_error.h"
#include "Javascript_arginfo.h"
zend_class_entry* phongo_javascript_ce;
/* Initialize the object and return whether it was successful. An exception will
* be thrown on error. */
static bool phongo_javascript_init(phongo_javascript_t* intern, const char* code, size_t code_len, zval* scope)
{
char* new_code = NULL;
bson_t* new_scope = NULL;
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 (code_len > PHONGO_BSON_MAX_LENGTH) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected code length to be <= %" PRId32 " bytes, %zu given", (int32_t) PHONGO_BSON_MAX_LENGTH, code_len);
return false;
}
if (strlen(code) != (size_t) code_len) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Code cannot contain null bytes");
return false;
}
new_code = estrndup(code, code_len);
if (scope && (Z_TYPE_P(scope) == IS_OBJECT || Z_TYPE_P(scope) == IS_ARRAY)) {
new_scope = bson_new();
phongo_zval_to_bson(scope, PHONGO_BSON_NONE, new_scope, NULL);
if (EG(exception)) {
efree(new_code);
bson_destroy(new_scope);
return false;
}
}
/* Commit the new state only after all fallible steps have succeeded so a
* failure leaves the object's previous contents untouched. */
if (intern->code) {
efree(intern->code);
}
if (intern->scope) {
bson_destroy(intern->scope);
}
intern->code = new_code;
intern->code_len = code_len;
intern->scope = new_scope;
return true;
}
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool phongo_javascript_init_from_hash(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 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(phongo_javascript_ce->name));
return false;
}
HashTable* phongo_javascript_get_properties_hash(zend_object* object, bool is_temp)
{
PHONGO_INTERN_FROM_Z_OBJ(javascript, object);
HashTable* props;
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) {
phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
if (!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)
{
PHONGO_INTERN_FROM_THIS(javascript);
char* code;
size_t code_len;
zval* scope = NULL;
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();
phongo_javascript_init(intern, code, code_len, scope);
}
static PHP_METHOD(MongoDB_BSON_Javascript, __set_state)
{
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
PHONGO_INTERN_INIT_EX(javascript, return_value);
props = Z_ARRVAL_P(array);
phongo_javascript_init_from_hash(intern, props);
}
/* Return the Javascript's code string. */
static PHP_METHOD(MongoDB_BSON_Javascript, __toString)
{
PHONGO_INTERN_FROM_THIS(javascript);
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_STRINGL(intern->code, intern->code_len);
}
static PHP_METHOD(MongoDB_BSON_Javascript, getCode)
{
PHONGO_INTERN_FROM_THIS(javascript);
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_STRINGL(intern->code, intern->code_len);
}
static PHP_METHOD(MongoDB_BSON_Javascript, getScope)
{
PHONGO_INTERN_FROM_THIS(javascript);
PHONGO_PARSE_PARAMETERS_NONE();
if (!intern->scope) {
RETURN_NULL();
}
if (intern->scope->len) {
phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
if (!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)
{
PHONGO_INTERN_FROM_THIS(javascript);
PHONGO_PARSE_PARAMETERS_NONE();
array_init_size(return_value, 2);
ADD_ASSOC_STRINGL(return_value, "$code", intern->code, intern->code_len);
if (intern->scope && intern->scope->len) {
phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
if (!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(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();
phongo_javascript_init_from_hash(Z_JAVASCRIPT_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\Javascript object handlers */
static zend_object_handlers phongo_handler_javascript;
static void phongo_javascript_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_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_release(intern->properties);
}
}
zend_object* phongo_javascript_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(javascript, class_type);
intern->std.handlers = &phongo_handler_javascript;
return &intern->std;
}
static zend_object* phongo_javascript_clone_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(javascript, object);
phongo_javascript_t* new_intern;
zend_object* new_object;
new_object = phongo_javascript_create_object(object->ce);
new_intern = Z_OBJ_JAVASCRIPT(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
phongo_javascript_init(new_intern, intern->code, intern->code_len, NULL);
new_intern->scope = intern->scope ? bson_copy(intern->scope) : NULL;
return new_object;
}
static int phongo_javascript_compare_objects(zval* o1, zval* o2)
{
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* phongo_javascript_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return phongo_javascript_get_properties_hash(object, true);
}
static HashTable* phongo_javascript_get_properties(zend_object* object)
{
return phongo_javascript_get_properties_hash(object, false);
}
void phongo_javascript_init_ce(INIT_FUNC_ARGS)
{
phongo_javascript_ce = register_class_MongoDB_BSON_Javascript(phongo_javascript_interface_ce, phongo_json_serializable_ce, phongo_type_ce, zend_ce_stringable);
phongo_javascript_ce->create_object = phongo_javascript_create_object;
memcpy(&phongo_handler_javascript, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_javascript.compare = phongo_javascript_compare_objects;
phongo_handler_javascript.clone_obj = phongo_javascript_clone_object;
phongo_handler_javascript.get_debug_info = phongo_javascript_get_debug_info;
phongo_handler_javascript.get_properties = phongo_javascript_get_properties;
phongo_handler_javascript.free_obj = phongo_javascript_free_object;
phongo_handler_javascript.offset = offsetof(phongo_javascript_t, std);
}
bool phongo_javascript_new(zval* object, const char* code, size_t code_len, const bson_t* scope, size_t nesting_depth)
{
if (scope) {
phongo_bson_state state;
bool valid_scope;
PHONGO_BSON_INIT_STATE(state);
state.nesting_depth = nesting_depth;
valid_scope = phongo_bson_to_zval_ex(scope, &state);
zval_ptr_dtor(&state.zchild);
if (!valid_scope) {
return false;
}
}
PHONGO_INTERN_INIT_EX(javascript, object);
intern->code = estrndup(code, code_len);
intern->code_len = code_len;
intern->scope = scope ? bson_copy(scope) : NULL;
return true;
}
mongodb-2.5.5/src/BSON/Javascript.h 0000644 0001751 0001751 00000001476 15264101572 013714 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, size_t nesting_depth);
#endif /* PHONGO_BSON_JAVASCRIPT_H */
mongodb-2.5.5/src/BSON/JavascriptInterface.c 0000644 0001751 0001751 00000001561 15264101572 015523 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 "phongo.h"
#include "JavascriptInterface_arginfo.h"
zend_class_entry* phongo_javascript_interface_ce;
void phongo_javascript_interface_init_ce(INIT_FUNC_ARGS)
{
phongo_javascript_interface_ce = register_class_MongoDB_BSON_JavascriptInterface();
}
mongodb-2.5.5/src/BSON/JavascriptInterface_arginfo.h 0000644 0001751 0001751 00000003507 15264101572 017237 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 58512a88fdb87ca50ced15fb3509ec1bbdfd137d */
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[] = {
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("getCode", NULL, arginfo_class_MongoDB_BSON_JavascriptInterface_getCode, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("getCode", NULL, arginfo_class_MongoDB_BSON_JavascriptInterface_getCode, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("getScope", NULL, arginfo_class_MongoDB_BSON_JavascriptInterface_getScope, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("getScope", NULL, arginfo_class_MongoDB_BSON_JavascriptInterface_getScope, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("__toString", NULL, arginfo_class_MongoDB_BSON_JavascriptInterface___toString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("__toString", NULL, arginfo_class_MongoDB_BSON_JavascriptInterface___toString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
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.5.5/src/BSON/Javascript_arginfo.h 0000644 0001751 0001751 00000007267 15264101572 015425 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 5bf645c9a3fc1bccb4d6a6cfa8e5f3e4956a9835 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
#endif
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.5.5/src/BSON/MaxKey.c 0000644 0001751 0001751 00000003126 15264101572 012771 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 "phongo.h"
#include "phongo_error.h"
#include "MaxKey_arginfo.h"
zend_class_entry* 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, 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();
}
void phongo_maxkey_init_ce(INIT_FUNC_ARGS)
{
phongo_maxkey_ce = register_class_MongoDB_BSON_MaxKey(phongo_maxkey_interface_ce, phongo_json_serializable_ce, phongo_type_ce);
}
mongodb-2.5.5/src/BSON/MaxKeyInterface.c 0000644 0001751 0001751 00000001535 15264101572 014614 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 "phongo.h"
#include "MaxKeyInterface_arginfo.h"
zend_class_entry* phongo_maxkey_interface_ce;
void phongo_maxkey_interface_init_ce(INIT_FUNC_ARGS)
{
phongo_maxkey_interface_ce = register_class_MongoDB_BSON_MaxKeyInterface();
}
mongodb-2.5.5/src/BSON/MaxKeyInterface_arginfo.h 0000644 0001751 0001751 00000000575 15264101572 016331 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: e7e08a9c8203cc7ea8c5669442dbe0bc0607eee6 */
static zend_class_entry *register_class_MongoDB_BSON_MaxKeyInterface(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "MaxKeyInterface", NULL);
class_entry = zend_register_internal_interface(&ce);
return class_entry;
}
mongodb-2.5.5/src/BSON/MaxKey_arginfo.h 0000644 0001751 0001751 00000004367 15264101572 014513 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: a62a947a0884e0f9709e923cd22d203b61781c87 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
#endif
zend_class_implements(class_entry, 3, class_entry_MongoDB_BSON_MaxKeyInterface, class_entry_JsonSerializable, class_entry_MongoDB_BSON_Type);
return class_entry;
}
mongodb-2.5.5/src/BSON/MinKey.c 0000644 0001751 0001751 00000003126 15264101572 012767 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 "phongo.h"
#include "phongo_error.h"
#include "MinKey_arginfo.h"
zend_class_entry* 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, 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();
}
void phongo_minkey_init_ce(INIT_FUNC_ARGS)
{
phongo_minkey_ce = register_class_MongoDB_BSON_MinKey(phongo_minkey_interface_ce, phongo_json_serializable_ce, phongo_type_ce);
}
mongodb-2.5.5/src/BSON/MinKeyInterface.c 0000644 0001751 0001751 00000001535 15264101572 014612 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 "phongo.h"
#include "MinKeyInterface_arginfo.h"
zend_class_entry* phongo_minkey_interface_ce;
void phongo_minkey_interface_init_ce(INIT_FUNC_ARGS)
{
phongo_minkey_interface_ce = register_class_MongoDB_BSON_MinKeyInterface();
}
mongodb-2.5.5/src/BSON/MinKeyInterface_arginfo.h 0000644 0001751 0001751 00000000575 15264101572 016327 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 598f048ec627ac0df4af6941b0e598772908c7cb */
static zend_class_entry *register_class_MongoDB_BSON_MinKeyInterface(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "MinKeyInterface", NULL);
class_entry = zend_register_internal_interface(&ce);
return class_entry;
}
mongodb-2.5.5/src/BSON/MinKey_arginfo.h 0000644 0001751 0001751 00000004367 15264101572 014511 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 8f783511e88c42df9c57abac6738d31937d65928 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
#endif
zend_class_implements(class_entry, 3, class_entry_MongoDB_BSON_MinKeyInterface, class_entry_JsonSerializable, class_entry_MongoDB_BSON_Type);
return class_entry;
}
mongodb-2.5.5/src/BSON/ObjectId.c 0000644 0001751 0001751 00000016114 15264101572 013257 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 "phongo.h"
#include "phongo_error.h"
#include "ObjectId_arginfo.h"
#define PHONGO_OID_SIZE sizeof(((phongo_objectid_t*) 0)->oid)
#define PHONGO_OID_LEN (PHONGO_OID_SIZE - 1)
zend_class_entry* phongo_objectid_ce;
/* Initialize the object with a generated value and return whether it was
* successful. */
static bool phongo_objectid_init(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 phongo_objectid_init_from_hex_string(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 phongo_objectid_init_from_hash(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 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(phongo_objectid_ce->name));
return false;
}
static HashTable* phongo_objectid_get_properties_hash(zend_object* object, bool is_temp)
{
PHONGO_INTERN_FROM_Z_OBJ(objectid, object);
HashTable* props;
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)
{
PHONGO_INTERN_FROM_THIS(objectid);
char* id = NULL;
size_t id_len;
PHONGO_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_STRING_OR_NULL(id, id_len)
PHONGO_PARSE_PARAMETERS_END();
if (id) {
phongo_objectid_init_from_hex_string(intern, id, id_len);
} else {
phongo_objectid_init(intern);
}
}
static PHP_METHOD(MongoDB_BSON_ObjectId, getTimestamp)
{
PHONGO_INTERN_FROM_THIS(objectid);
bson_oid_t tmp_oid;
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)
{
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
PHONGO_INTERN_INIT_EX(objectid, return_value);
props = Z_ARRVAL_P(array);
phongo_objectid_init_from_hash(intern, props);
}
static PHP_METHOD(MongoDB_BSON_ObjectId, __toString)
{
PHONGO_INTERN_FROM_THIS(objectid);
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_STRINGL(intern->oid, PHONGO_OID_LEN);
}
static PHP_METHOD(MongoDB_BSON_ObjectId, jsonSerialize)
{
PHONGO_INTERN_FROM_THIS(objectid);
PHONGO_PARSE_PARAMETERS_NONE();
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(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();
phongo_objectid_init_from_hash(Z_OBJECTID_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\ObjectId object handlers */
static zend_object_handlers phongo_handler_objectid;
static void phongo_objectid_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(objectid, object);
zend_object_std_dtor(&intern->std);
if (intern->properties) {
zend_hash_release(intern->properties);
}
}
static zend_object* phongo_objectid_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(objectid, class_type);
intern->std.handlers = &phongo_handler_objectid;
return &intern->std;
}
static zend_object* phongo_objectid_clone_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(objectid, object);
phongo_objectid_t* new_intern;
zend_object* new_object;
new_object = 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 phongo_objectid_compare_objects(zval* o1, zval* o2)
{
phongo_objectid_t* intern1;
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* phongo_objectid_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return phongo_objectid_get_properties_hash(object, true);
}
static HashTable* phongo_objectid_get_properties(zend_object* object)
{
return phongo_objectid_get_properties_hash(object, false);
}
void phongo_objectid_init_ce(INIT_FUNC_ARGS)
{
phongo_objectid_ce = register_class_MongoDB_BSON_ObjectId(phongo_objectid_interface_ce, phongo_json_serializable_ce, phongo_type_ce, zend_ce_stringable);
phongo_objectid_ce->create_object = phongo_objectid_create_object;
memcpy(&phongo_handler_objectid, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_objectid.compare = phongo_objectid_compare_objects;
phongo_handler_objectid.clone_obj = phongo_objectid_clone_object;
phongo_handler_objectid.get_debug_info = phongo_objectid_get_debug_info;
phongo_handler_objectid.get_properties = phongo_objectid_get_properties;
phongo_handler_objectid.free_obj = phongo_objectid_free_object;
phongo_handler_objectid.offset = offsetof(phongo_objectid_t, std);
}
bool phongo_objectid_new(zval* return_value, const bson_oid_t* oid)
{
PHONGO_INTERN_INIT_EX(objectid, return_value);
bson_oid_to_string(oid, intern->oid);
intern->initialized = true;
return true;
}
mongodb-2.5.5/src/BSON/ObjectId.h 0000644 0001751 0001751 00000001457 15264101572 013270 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.5.5/src/BSON/ObjectIdInterface.c 0000644 0001751 0001751 00000001547 15264101572 015104 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 "phongo.h"
#include "ObjectIdInterface_arginfo.h"
zend_class_entry* phongo_objectid_interface_ce;
void phongo_objectid_interface_init_ce(INIT_FUNC_ARGS)
{
phongo_objectid_interface_ce = register_class_MongoDB_BSON_ObjectIdInterface();
}
mongodb-2.5.5/src/BSON/ObjectIdInterface_arginfo.h 0000644 0001751 0001751 00000002635 15264101572 016615 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: f82341700fba9fcf48096873075b17a810e5f448 */
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[] = {
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("getTimestamp", NULL, arginfo_class_MongoDB_BSON_ObjectIdInterface_getTimestamp, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("getTimestamp", NULL, arginfo_class_MongoDB_BSON_ObjectIdInterface_getTimestamp, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("__toString", NULL, arginfo_class_MongoDB_BSON_ObjectIdInterface___toString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("__toString", NULL, arginfo_class_MongoDB_BSON_ObjectIdInterface___toString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
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.5.5/src/BSON/ObjectId_arginfo.h 0000644 0001751 0001751 00000006465 15264101572 015001 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 6498d9a4685323f610d5673621b43cb5362bd49d */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
#endif
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.5.5/src/BSON/PackedArray.c 0000644 0001751 0001751 00000035167 15264101572 013773 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 "phongo.h"
#include "phongo_error.h"
#include "phongo_bson_encode.h"
#include "BSON/PackedArray_arginfo.h"
#include "BSON/Iterator.h"
zend_class_entry* phongo_packedarray_ce;
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool phongo_packedarray_init_from_hash(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(phongo_packedarray_ce->name));
return false;
}
return true;
}
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"data\" string field", ZSTR_VAL(phongo_packedarray_ce->name));
return false;
}
static HashTable* phongo_packedarray_get_properties_hash(zend_object* object, bool is_temp, int size)
{
PHONGO_INTERN_FROM_Z_OBJ(packedarray, object);
HashTable* props;
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 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)
{
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++;
}
}
PHONGO_INTERN_INIT_EX(packedarray, return_value);
intern->bson = bson;
}
static PHP_METHOD(MongoDB_BSON_PackedArray, fromPHP)
{
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;
}
PHONGO_INTERN_INIT_EX(packedarray, return_value);
intern->bson = bson_new();
phongo_zval_to_bson(data, PHONGO_BSON_NONE, intern->bson, NULL);
}
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 phongo_packedarray_get(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)
{
PHONGO_INTERN_FROM_THIS(packedarray);
zend_long index;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_LONG(index)
PHONGO_PARSE_PARAMETERS_END();
if (!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 phongo_packedarray_has(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)
{
PHONGO_INTERN_FROM_THIS(packedarray);
zend_long index;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_LONG(index)
PHONGO_PARSE_PARAMETERS_END();
RETURN_BOOL(phongo_packedarray_has(intern, index));
}
static PHP_METHOD(MongoDB_BSON_PackedArray, toCanonicalExtendedJSON)
{
PHONGO_INTERN_FROM_THIS(packedarray);
PHONGO_PARSE_PARAMETERS_NONE();
phongo_packedarray_to_json(return_value, BSON_JSON_MODE_CANONICAL, intern->bson);
}
static PHP_METHOD(MongoDB_BSON_PackedArray, toRelaxedExtendedJSON)
{
PHONGO_INTERN_FROM_THIS(packedarray);
PHONGO_PARSE_PARAMETERS_NONE();
phongo_packedarray_to_json(return_value, BSON_JSON_MODE_RELAXED, intern->bson);
}
static PHP_METHOD(MongoDB_BSON_PackedArray, toPHP)
{
PHONGO_INTERN_FROM_THIS(packedarray);
zval* typemap = NULL;
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 (!phongo_bson_typemap_to_state(typemap, &state.map)) {
return;
}
state.is_visiting_array = true;
state.map.int64_as_object = true;
if (!phongo_bson_to_zval_ex(intern->bson, &state)) {
zval_ptr_dtor(&state.zchild);
phongo_bson_typemap_dtor(&state.map);
RETURN_NULL();
}
phongo_bson_typemap_dtor(&state.map);
RETURN_ZVAL(&state.zchild, 0, 1);
}
static PHP_METHOD(MongoDB_BSON_PackedArray, offsetExists)
{
PHONGO_INTERN_FROM_THIS(packedarray);
zval* key;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ZVAL(key)
PHONGO_PARSE_PARAMETERS_END();
if (Z_TYPE_P(key) != IS_LONG) {
RETURN_FALSE;
}
RETURN_BOOL(phongo_packedarray_has(intern, Z_LVAL_P(key)));
}
static PHP_METHOD(MongoDB_BSON_PackedArray, offsetGet)
{
PHONGO_INTERN_FROM_THIS(packedarray);
zval* key;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ZVAL(key)
PHONGO_PARSE_PARAMETERS_END();
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
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(phongo_packedarray_ce->name));
}
static PHP_METHOD(MongoDB_BSON_PackedArray, offsetUnset)
{
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Cannot unset %s offset", ZSTR_VAL(phongo_packedarray_ce->name));
}
static PHP_METHOD(MongoDB_BSON_PackedArray, __toString)
{
PHONGO_INTERN_FROM_THIS(packedarray);
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRINGL((const char*) bson_get_data(intern->bson), intern->bson->len);
}
static PHP_METHOD(MongoDB_BSON_PackedArray, __set_state)
{
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
PHONGO_INTERN_INIT_EX(packedarray, return_value);
props = Z_ARRVAL_P(array);
phongo_packedarray_init_from_hash(intern, props);
}
static PHP_METHOD(MongoDB_BSON_PackedArray, __serialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_ARR(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();
phongo_packedarray_init_from_hash(Z_PACKEDARRAY_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\PackedArray object handlers */
static zend_object_handlers phongo_handler_packedarray;
static void phongo_packedarray_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(packedarray, object);
zend_object_std_dtor(&intern->std);
if (intern->bson) {
bson_destroy(intern->bson);
}
if (intern->properties) {
zend_hash_release(intern->properties);
}
}
static zend_object* phongo_packedarray_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(packedarray, class_type);
intern->std.handlers = &phongo_handler_packedarray;
return &intern->std;
}
static zend_object* phongo_packedarray_clone_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(packedarray, object);
phongo_packedarray_t* new_intern;
zend_object* new_object;
new_object = 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 phongo_packedarray_compare_objects(zval* o1, zval* o2)
{
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* phongo_packedarray_get_debug_info(zend_object* object, int* is_temp)
{
PHONGO_INTERN_FROM_Z_OBJ(packedarray, object);
HashTable* props;
*is_temp = 1;
/* This get_debug_info handler reports an additional property. This does not
* conflict with other uses of phongo_document_get_properties_hash since
* we always allocated a new HashTable with is_temp=true. */
props = phongo_packedarray_get_properties_hash(object, true, 2);
{
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 (!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* phongo_packedarray_get_properties(zend_object* object)
{
return phongo_packedarray_get_properties_hash(object, false, 1);
}
zval* phongo_packedarray_read_dimension(zend_object* object, zval* offset, int type, zval* rv)
{
PHONGO_INTERN_FROM_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 (!phongo_packedarray_get(intern, Z_LVAL_P(offset), rv, type == BP_VAR_IS)) {
// Exception already thrown
return &EG(uninitialized_zval);
}
return rv;
}
void phongo_packedarray_write_dimension(zend_object* object, zval* offset, zval* value)
{
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Cannot write to %s offset", ZSTR_VAL(phongo_packedarray_ce->name));
}
int phongo_packedarray_has_dimension(zend_object* object, zval* member, int check_empty)
{
PHONGO_INTERN_FROM_Z_OBJ(packedarray, object);
if (Z_TYPE_P(member) != IS_LONG) {
return false;
}
return phongo_packedarray_has(intern, Z_LVAL_P(member));
}
void phongo_packedarray_unset_dimension(zend_object* object, zval* offset)
{
phongo_throw_exception(PHONGO_ERROR_LOGIC, "Cannot unset %s offset", ZSTR_VAL(phongo_packedarray_ce->name));
}
void phongo_packedarray_init_ce(INIT_FUNC_ARGS)
{
phongo_packedarray_ce = register_class_MongoDB_BSON_PackedArray(zend_ce_aggregate, zend_ce_arrayaccess, phongo_type_ce, zend_ce_stringable);
phongo_packedarray_ce->create_object = phongo_packedarray_create_object;
memcpy(&phongo_handler_packedarray, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_packedarray.compare = phongo_packedarray_compare_objects;
phongo_handler_packedarray.clone_obj = phongo_packedarray_clone_object;
phongo_handler_packedarray.get_debug_info = phongo_packedarray_get_debug_info;
phongo_handler_packedarray.get_properties = phongo_packedarray_get_properties;
phongo_handler_packedarray.free_obj = phongo_packedarray_free_object;
phongo_handler_packedarray.read_dimension = phongo_packedarray_read_dimension;
phongo_handler_packedarray.write_dimension = phongo_packedarray_write_dimension;
phongo_handler_packedarray.has_dimension = phongo_packedarray_has_dimension;
phongo_handler_packedarray.unset_dimension = phongo_packedarray_unset_dimension;
phongo_handler_packedarray.offset = offsetof(phongo_packedarray_t, std);
}
bool phongo_packedarray_new(zval* object, bson_t* bson, bool copy)
{
PHONGO_INTERN_INIT_EX(packedarray, object);
intern->bson = copy ? bson_copy(bson) : bson;
return true;
}
mongodb-2.5.5/src/BSON/PackedArray.h 0000644 0001751 0001751 00000001415 15264101572 013765 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.5.5/src/BSON/PackedArray_arginfo.h 0000644 0001751 0001751 00000015551 15264101572 015500 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: b104bf91975f87a360e8ee756f948bf83bffae50 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
#endif
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.5.5/src/BSON/Persistable.c 0000644 0001751 0001751 00000001566 15264101572 014056 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 "phongo.h"
#include "Persistable_arginfo.h"
zend_class_entry* phongo_persistable_ce;
void phongo_persistable_init_ce(INIT_FUNC_ARGS)
{
phongo_persistable_ce = register_class_MongoDB_BSON_Persistable(phongo_serializable_ce, phongo_unserializable_ce);
}
mongodb-2.5.5/src/BSON/Persistable_arginfo.h 0000644 0001751 0001751 00000002303 15264101572 015556 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 0f9f27e9007f9bf08fe83bdaa3896f333f03af6b */
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[] = {
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("bsonSerialize", NULL, arginfo_class_MongoDB_BSON_Persistable_bsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("bsonSerialize", NULL, arginfo_class_MongoDB_BSON_Persistable_bsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
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.5.5/src/BSON/Regex.c 0000644 0001751 0001751 00000021262 15264101572 012646 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 "phongo.h"
#include "phongo_error.h"
#include "Regex_arginfo.h"
zend_class_entry* phongo_regex_ce;
/* qsort() compare callback for alphabetizing regex flags upon initialization */
static int 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 phongo_regex_init(phongo_regex_t* intern, const char* pattern, size_t pattern_len, const char* flags, size_t flags_len)
{
if (pattern_len > PHONGO_BSON_MAX_LENGTH) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected pattern length to be <= %" PRId32 " bytes, %zu given", (int32_t) PHONGO_BSON_MAX_LENGTH, pattern_len);
return false;
}
if (flags_len > PHONGO_BSON_MAX_LENGTH) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected flags length to be <= %" PRId32 " bytes, %zu given", (int32_t) PHONGO_BSON_MAX_LENGTH, flags_len);
return false;
}
if (strlen(pattern) != (size_t) pattern_len) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Pattern cannot contain null bytes");
return false;
}
if (flags && strlen(flags) != (size_t) flags_len) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Flags cannot contain null bytes");
return false;
}
if (intern->pattern) {
efree(intern->pattern);
}
if (intern->flags) {
efree(intern->flags);
}
intern->pattern = estrndup(pattern, pattern_len);
intern->pattern_len = pattern_len;
if (flags) {
intern->flags = estrndup(flags, flags_len);
intern->flags_len = flags_len;
/* Ensure flags are alphabetized upon initialization */
qsort((void*) intern->flags, flags_len, 1, 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 phongo_regex_init_from_hash(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 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(phongo_regex_ce->name));
return false;
}
static HashTable* phongo_regex_get_properties_hash(zend_object* object, bool is_temp)
{
PHONGO_INTERN_FROM_Z_OBJ(regex, object);
HashTable* props;
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)
{
PHONGO_INTERN_FROM_THIS(regex);
char* pattern;
size_t pattern_len;
char* flags = NULL;
size_t flags_len = 0;
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();
phongo_regex_init(intern, pattern, pattern_len, flags, flags_len);
}
static PHP_METHOD(MongoDB_BSON_Regex, getPattern)
{
PHONGO_INTERN_FROM_THIS(regex);
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_STRINGL(intern->pattern, intern->pattern_len);
}
static PHP_METHOD(MongoDB_BSON_Regex, getFlags)
{
PHONGO_INTERN_FROM_THIS(regex);
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_STRINGL(intern->flags, intern->flags_len);
}
static PHP_METHOD(MongoDB_BSON_Regex, __set_state)
{
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
PHONGO_INTERN_INIT_EX(regex, return_value);
props = Z_ARRVAL_P(array);
phongo_regex_init_from_hash(intern, props);
}
/* Returns a string in the form: /pattern/flags */
static PHP_METHOD(MongoDB_BSON_Regex, __toString)
{
PHONGO_INTERN_FROM_THIS(regex);
char* regex;
int regex_len;
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)
{
PHONGO_INTERN_FROM_THIS(regex);
PHONGO_PARSE_PARAMETERS_NONE();
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(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();
phongo_regex_init_from_hash(Z_REGEX_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\Regex object handlers */
static zend_object_handlers phongo_handler_regex;
static void phongo_regex_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_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_release(intern->properties);
}
}
static zend_object* phongo_regex_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(regex, class_type);
intern->std.handlers = &phongo_handler_regex;
return &intern->std;
}
static zend_object* phongo_regex_clone_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(regex, object);
phongo_regex_t* new_intern;
zend_object* new_object;
new_object = phongo_regex_create_object(object->ce);
new_intern = Z_OBJ_REGEX(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
phongo_regex_init(new_intern, intern->pattern, intern->pattern_len, intern->flags, intern->flags_len);
return new_object;
}
static int phongo_regex_compare_objects(zval* o1, zval* o2)
{
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* phongo_regex_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return phongo_regex_get_properties_hash(object, true);
}
static HashTable* phongo_regex_get_properties(zend_object* object)
{
return phongo_regex_get_properties_hash(object, false);
}
void phongo_regex_init_ce(INIT_FUNC_ARGS)
{
phongo_regex_ce = register_class_MongoDB_BSON_Regex(phongo_regex_interface_ce, phongo_json_serializable_ce, phongo_type_ce, zend_ce_stringable);
phongo_regex_ce->create_object = phongo_regex_create_object;
memcpy(&phongo_handler_regex, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_regex.compare = phongo_regex_compare_objects;
phongo_handler_regex.clone_obj = phongo_regex_clone_object;
phongo_handler_regex.get_debug_info = phongo_regex_get_debug_info;
phongo_handler_regex.get_properties = phongo_regex_get_properties;
phongo_handler_regex.free_obj = phongo_regex_free_object;
phongo_handler_regex.offset = offsetof(phongo_regex_t, std);
}
bool phongo_regex_new(zval* object, const char* pattern, const char* flags)
{
PHONGO_INTERN_INIT_EX(regex, object);
return phongo_regex_init(intern, pattern, strlen(pattern), flags, strlen(flags));
}
mongodb-2.5.5/src/BSON/Regex.h 0000644 0001751 0001751 00000001404 15264101572 012647 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.5.5/src/BSON/RegexInterface.c 0000644 0001751 0001751 00000001530 15264101572 014463 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 "phongo.h"
#include "RegexInterface_arginfo.h"
zend_class_entry* phongo_regex_interface_ce;
void phongo_regex_interface_init_ce(INIT_FUNC_ARGS)
{
phongo_regex_interface_ce = register_class_MongoDB_BSON_RegexInterface();
}
mongodb-2.5.5/src/BSON/RegexInterface_arginfo.h 0000644 0001751 0001751 00000003377 15264101572 016210 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 0207382679445e7ccb3f0eed665dc2820472df41 */
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[] = {
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("getPattern", NULL, arginfo_class_MongoDB_BSON_RegexInterface_getPattern, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("getPattern", NULL, arginfo_class_MongoDB_BSON_RegexInterface_getPattern, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("getFlags", NULL, arginfo_class_MongoDB_BSON_RegexInterface_getFlags, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("getFlags", NULL, arginfo_class_MongoDB_BSON_RegexInterface_getFlags, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("__toString", NULL, arginfo_class_MongoDB_BSON_RegexInterface___toString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("__toString", NULL, arginfo_class_MongoDB_BSON_RegexInterface___toString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
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.5.5/src/BSON/Regex_arginfo.h 0000644 0001751 0001751 00000006735 15264101572 014370 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: fc23b5f166d4e4ffe43ffe15b4b4b16dcfdba2b9 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
#endif
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.5.5/src/BSON/Serializable.c 0000644 0001751 0001751 00000001531 15264101572 014177 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 "phongo.h"
#include "Serializable_arginfo.h"
zend_class_entry* phongo_serializable_ce;
void phongo_serializable_init_ce(INIT_FUNC_ARGS)
{
phongo_serializable_ce = register_class_MongoDB_BSON_Serializable(phongo_type_ce);
}
mongodb-2.5.5/src/BSON/Serializable_arginfo.h 0000644 0001751 0001751 00000002161 15264101572 015711 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 21b68b053b081dce111f72a9db8f4e64a2b57113 */
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[] = {
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("bsonSerialize", NULL, arginfo_class_MongoDB_BSON_Serializable_bsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("bsonSerialize", NULL, arginfo_class_MongoDB_BSON_Serializable_bsonSerialize, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
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.5.5/src/BSON/Symbol.c 0000644 0001751 0001751 00000014104 15264101572 013036 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 "phongo.h"
#include "phongo_error.h"
#include "Symbol_arginfo.h"
zend_class_entry* phongo_symbol_ce;
/* Initialize the object and return whether it was successful. An exception will
* be thrown on error. */
static bool phongo_symbol_init(phongo_symbol_t* intern, const char* symbol, size_t symbol_len)
{
if (symbol_len > PHONGO_BSON_MAX_LENGTH) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected symbol length to be <= %" PRId32 " bytes, %zu given", (int32_t) PHONGO_BSON_MAX_LENGTH, symbol_len);
return false;
}
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 phongo_symbol_init_from_hash(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 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(phongo_symbol_ce->name));
return false;
}
HashTable* phongo_symbol_get_properties_hash(zend_object* object, bool is_temp)
{
PHONGO_INTERN_FROM_Z_OBJ(symbol, object);
HashTable* props;
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)
{
PHONGO_INTERN_FROM_THIS(symbol);
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_STRINGL(intern->symbol, intern->symbol_len);
}
static PHP_METHOD(MongoDB_BSON_Symbol, __set_state)
{
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
PHONGO_INTERN_INIT_EX(symbol, return_value);
props = Z_ARRVAL_P(array);
phongo_symbol_init_from_hash(intern, props);
}
static PHP_METHOD(MongoDB_BSON_Symbol, jsonSerialize)
{
PHONGO_INTERN_FROM_THIS(symbol);
PHONGO_PARSE_PARAMETERS_NONE();
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, 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();
phongo_symbol_init_from_hash(Z_SYMBOL_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\Symbol object handlers */
static zend_object_handlers phongo_handler_symbol;
static void phongo_symbol_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(symbol, object);
zend_object_std_dtor(&intern->std);
if (intern->symbol) {
efree(intern->symbol);
}
if (intern->properties) {
zend_hash_release(intern->properties);
}
}
zend_object* phongo_symbol_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(symbol, class_type);
intern->std.handlers = &phongo_handler_symbol;
return &intern->std;
}
static zend_object* phongo_symbol_clone_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(symbol, object);
phongo_symbol_t* new_intern;
zend_object* new_object;
new_object = phongo_symbol_create_object(object->ce);
new_intern = Z_OBJ_SYMBOL(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
phongo_symbol_init(new_intern, intern->symbol, intern->symbol_len);
return new_object;
}
static int phongo_symbol_compare_objects(zval* o1, zval* o2)
{
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* phongo_symbol_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return phongo_symbol_get_properties_hash(object, true);
}
static HashTable* phongo_symbol_get_properties(zend_object* object)
{
return phongo_symbol_get_properties_hash(object, false);
}
void phongo_symbol_init_ce(INIT_FUNC_ARGS)
{
phongo_symbol_ce = register_class_MongoDB_BSON_Symbol(phongo_json_serializable_ce, phongo_type_ce, zend_ce_stringable);
phongo_symbol_ce->create_object = phongo_symbol_create_object;
memcpy(&phongo_handler_symbol, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_symbol.compare = phongo_symbol_compare_objects;
phongo_handler_symbol.clone_obj = phongo_symbol_clone_object;
phongo_handler_symbol.get_debug_info = phongo_symbol_get_debug_info;
phongo_handler_symbol.get_properties = phongo_symbol_get_properties;
phongo_handler_symbol.free_obj = phongo_symbol_free_object;
phongo_handler_symbol.offset = offsetof(phongo_symbol_t, std);
}
bool phongo_symbol_new(zval* object, const char* symbol, size_t symbol_len)
{
PHONGO_INTERN_INIT_EX(symbol, object);
intern->symbol = estrndup(symbol, symbol_len);
intern->symbol_len = symbol_len;
return true;
}
mongodb-2.5.5/src/BSON/Symbol.h 0000644 0001751 0001751 00000001407 15264101572 013045 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.5.5/src/BSON/Symbol_arginfo.h 0000644 0001751 0001751 00000005424 15264101572 014555 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 0942ac0771228198f4d4247d5825e0d865fe2098 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
#endif
zend_class_implements(class_entry, 3, class_entry_JsonSerializable, class_entry_MongoDB_BSON_Type, class_entry_Stringable);
return class_entry;
}
mongodb-2.5.5/src/BSON/Timestamp.c 0000644 0001751 0001751 00000024463 15264101572 013545 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 "phongo.h"
#include "phongo_error.h"
#include "phongo_util.h"
#include "Timestamp_arginfo.h"
zend_class_entry* phongo_timestamp_ce;
/* Initialize the object and return whether it was successful. An exception will
* be thrown on error. */
static bool phongo_timestamp_init(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 phongo_timestamp_init_from_string(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 (!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(phongo_timestamp_ce->name));
return false;
}
if (!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(phongo_timestamp_ce->name));
return false;
}
return 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 phongo_timestamp_init_from_hash(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 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 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(phongo_timestamp_ce->name));
return false;
}
static HashTable* phongo_timestamp_get_properties_hash(zend_object* object, bool is_temp)
{
PHONGO_INTERN_FROM_Z_OBJ(timestamp, object);
HashTable* props;
char s_increment[24];
char s_timestamp[24];
int s_increment_len;
int s_timestamp_len;
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)
{
PHONGO_INTERN_FROM_THIS(timestamp);
zval *increment = NULL, *timestamp = NULL;
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) {
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;
}
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)
{
PHONGO_INTERN_FROM_THIS(timestamp);
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_LONG(intern->increment);
}
static PHP_METHOD(MongoDB_BSON_Timestamp, getTimestamp)
{
PHONGO_INTERN_FROM_THIS(timestamp);
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_LONG(intern->timestamp);
}
static PHP_METHOD(MongoDB_BSON_Timestamp, __set_state)
{
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
PHONGO_INTERN_INIT_EX(timestamp, return_value);
props = Z_ARRVAL_P(array);
phongo_timestamp_init_from_hash(intern, props);
}
/* Returns a string in the form: [increment:timestamp] */
static PHP_METHOD(MongoDB_BSON_Timestamp, __toString)
{
PHONGO_INTERN_FROM_THIS(timestamp);
char* retval;
int retval_len;
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)
{
PHONGO_INTERN_FROM_THIS(timestamp);
PHONGO_PARSE_PARAMETERS_NONE();
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(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();
phongo_timestamp_init_from_hash(Z_TIMESTAMP_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\Timestamp object handlers */
static zend_object_handlers phongo_handler_timestamp;
static void phongo_timestamp_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(timestamp, object);
zend_object_std_dtor(&intern->std);
if (intern->properties) {
zend_hash_release(intern->properties);
}
}
static zend_object* phongo_timestamp_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(timestamp, class_type);
intern->std.handlers = &phongo_handler_timestamp;
return &intern->std;
}
static zend_object* phongo_timestamp_clone_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(timestamp, object);
phongo_timestamp_t* new_intern;
zend_object* new_object;
new_object = phongo_timestamp_create_object(object->ce);
new_intern = Z_OBJ_TIMESTAMP(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
phongo_timestamp_init(new_intern, intern->increment, intern->timestamp);
return new_object;
}
static int phongo_timestamp_compare_objects(zval* o1, zval* o2)
{
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* phongo_timestamp_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return phongo_timestamp_get_properties_hash(object, true);
}
static HashTable* phongo_timestamp_get_properties(zend_object* object)
{
return phongo_timestamp_get_properties_hash(object, false);
}
void phongo_timestamp_init_ce(INIT_FUNC_ARGS)
{
phongo_timestamp_ce = register_class_MongoDB_BSON_Timestamp(phongo_timestamp_interface_ce, phongo_json_serializable_ce, phongo_type_ce, zend_ce_stringable);
phongo_timestamp_ce->create_object = phongo_timestamp_create_object;
memcpy(&phongo_handler_timestamp, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_timestamp.compare = phongo_timestamp_compare_objects;
phongo_handler_timestamp.clone_obj = phongo_timestamp_clone_object;
phongo_handler_timestamp.get_debug_info = phongo_timestamp_get_debug_info;
phongo_handler_timestamp.get_properties = phongo_timestamp_get_properties;
phongo_handler_timestamp.free_obj = phongo_timestamp_free_object;
phongo_handler_timestamp.offset = offsetof(phongo_timestamp_t, std);
}
bool phongo_timestamp_new(zval* object, uint32_t increment, uint32_t timestamp)
{
PHONGO_INTERN_INIT_EX(timestamp, object);
intern->increment = increment;
intern->timestamp = timestamp;
intern->initialized = true;
return true;
}
mongodb-2.5.5/src/BSON/Timestamp.h 0000644 0001751 0001751 00000001424 15264101572 013542 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.5.5/src/BSON/TimestampInterface.c 0000644 0001751 0001751 00000001554 15264101572 015362 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 "phongo.h"
#include "TimestampInterface_arginfo.h"
zend_class_entry* phongo_timestamp_interface_ce;
void phongo_timestamp_interface_init_ce(INIT_FUNC_ARGS)
{
phongo_timestamp_interface_ce = register_class_MongoDB_BSON_TimestampInterface();
}
mongodb-2.5.5/src/BSON/TimestampInterface_arginfo.h 0000644 0001751 0001751 00000003551 15264101572 017073 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 5ebfb13003e6b82254b7154f492222e0610f0894 */
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[] = {
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("getTimestamp", NULL, arginfo_class_MongoDB_BSON_TimestampInterface_getTimestamp, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("getTimestamp", NULL, arginfo_class_MongoDB_BSON_TimestampInterface_getTimestamp, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("getIncrement", NULL, arginfo_class_MongoDB_BSON_TimestampInterface_getIncrement, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("getIncrement", NULL, arginfo_class_MongoDB_BSON_TimestampInterface_getIncrement, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("__toString", NULL, arginfo_class_MongoDB_BSON_TimestampInterface___toString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("__toString", NULL, arginfo_class_MongoDB_BSON_TimestampInterface___toString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
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.5.5/src/BSON/Timestamp_arginfo.h 0000644 0001751 0001751 00000007303 15264101572 015251 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 5b6c8488c5502a6d0fc472449f49de60560ec15e */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
#endif
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.5.5/src/BSON/Type.c 0000644 0001751 0001751 00000001443 15264101572 012514 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 "phongo.h"
#include "Type_arginfo.h"
zend_class_entry* phongo_type_ce;
void phongo_type_init_ce(INIT_FUNC_ARGS)
{
phongo_type_ce = register_class_MongoDB_BSON_Type();
}
mongodb-2.5.5/src/BSON/Type_arginfo.h 0000644 0001751 0001751 00000000547 15264101572 014232 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 7c297c1f6a9454b4e7a509b278f2776e31d8dbfa */
static zend_class_entry *register_class_MongoDB_BSON_Type(void)
{
zend_class_entry ce, *class_entry;
INIT_NS_CLASS_ENTRY(ce, "MongoDB\\BSON", "Type", NULL);
class_entry = zend_register_internal_interface(&ce);
return class_entry;
}
mongodb-2.5.5/src/BSON/UTCDateTime.c 0000644 0001751 0001751 00000025713 15264101572 013651 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 "phongo.h"
#include "phongo_error.h"
#include "phongo_util.h"
#include "UTCDateTime_arginfo.h"
zend_class_entry* phongo_utcdatetime_ce;
/* Initialize the object and return whether it was successful. */
static bool phongo_utcdatetime_init(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 phongo_utcdatetime_init_from_string(phongo_utcdatetime_t* intern, const char* s_milliseconds, size_t s_milliseconds_len)
{
int64_t milliseconds;
if (!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(phongo_utcdatetime_ce->name));
return false;
}
return 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 phongo_utcdatetime_init_from_hash(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 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 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(phongo_utcdatetime_ce->name));
return false;
}
/* Initialize the object from the current time and return whether it was
* successful. */
static bool phongo_utcdatetime_init_from_current_time(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 phongo_utcdatetime_init_from_date(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 phongo_utcdatetime_init_from_object(phongo_utcdatetime_t* intern, zend_object* object)
{
if (instanceof_function(object->ce, php_date_get_interface_ce())) {
phongo_utcdatetime_init_from_date(intern, php_date_obj_from_obj(object));
return true;
}
if (instanceof_function(object->ce, phongo_int64_ce)) {
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(phongo_int64_ce->name), ZSTR_VAL(object->ce->name));
return false;
}
static HashTable* phongo_utcdatetime_get_properties_hash(zend_object* object, bool is_temp)
{
PHONGO_INTERN_FROM_Z_OBJ(utcdatetime, object);
HashTable* props;
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 phongo_utcdatetime_to_php_date(zval* return_value, const zval* this, zend_class_entry* ce)
{
PHONGO_INTERN_FROM_ZVAL(utcdatetime, this);
php_date_obj* datetime_obj;
char* sec_str;
size_t sec_len;
int64_t sec, usec;
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)
{
PHONGO_INTERN_FROM_THIS(utcdatetime);
zval* milliseconds = NULL;
PHONGO_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_ZVAL_OR_NULL(milliseconds)
PHONGO_PARSE_PARAMETERS_END();
if (milliseconds == NULL) {
phongo_utcdatetime_init_from_current_time(intern);
return;
}
switch (Z_TYPE_P(milliseconds)) {
case IS_OBJECT:
phongo_utcdatetime_init_from_object(intern, Z_OBJ_P(milliseconds));
return;
case IS_LONG:
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)
{
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
PHONGO_INTERN_INIT_EX(utcdatetime, return_value);
props = Z_ARRVAL_P(array);
phongo_utcdatetime_init_from_hash(intern, props);
}
/* Returns the UTCDateTime's milliseconds as a string */
static PHP_METHOD(MongoDB_BSON_UTCDateTime, __toString)
{
PHONGO_INTERN_FROM_THIS(utcdatetime);
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();
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();
phongo_utcdatetime_to_php_date(return_value, getThis(), php_date_get_immutable_ce());
}
static PHP_METHOD(MongoDB_BSON_UTCDateTime, jsonSerialize)
{
PHONGO_INTERN_FROM_THIS(utcdatetime);
PHONGO_PARSE_PARAMETERS_NONE();
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(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();
phongo_utcdatetime_init_from_hash(Z_UTCDATETIME_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\BSON\UTCDateTime object handlers */
static zend_object_handlers phongo_handler_utcdatetime;
static void phongo_utcdatetime_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(utcdatetime, object);
zend_object_std_dtor(&intern->std);
if (intern->properties) {
zend_hash_release(intern->properties);
}
}
static zend_object* phongo_utcdatetime_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(utcdatetime, class_type);
intern->std.handlers = &phongo_handler_utcdatetime;
return &intern->std;
}
static zend_object* phongo_utcdatetime_clone_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(utcdatetime, object);
phongo_utcdatetime_t* new_intern;
zend_object* new_object;
new_object = phongo_utcdatetime_create_object(object->ce);
new_intern = Z_OBJ_UTCDATETIME(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
phongo_utcdatetime_init(new_intern, intern->milliseconds);
return new_object;
}
static int phongo_utcdatetime_compare_objects(zval* o1, zval* o2)
{
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* phongo_utcdatetime_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return phongo_utcdatetime_get_properties_hash(object, true);
}
static HashTable* phongo_utcdatetime_get_properties(zend_object* object)
{
return phongo_utcdatetime_get_properties_hash(object, false);
}
void phongo_utcdatetime_init_ce(INIT_FUNC_ARGS)
{
phongo_utcdatetime_ce = register_class_MongoDB_BSON_UTCDateTime(phongo_utcdatetime_interface_ce, phongo_json_serializable_ce, phongo_type_ce, zend_ce_stringable);
phongo_utcdatetime_ce->create_object = phongo_utcdatetime_create_object;
memcpy(&phongo_handler_utcdatetime, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_utcdatetime.compare = phongo_utcdatetime_compare_objects;
phongo_handler_utcdatetime.clone_obj = phongo_utcdatetime_clone_object;
phongo_handler_utcdatetime.get_debug_info = phongo_utcdatetime_get_debug_info;
phongo_handler_utcdatetime.get_properties = phongo_utcdatetime_get_properties;
phongo_handler_utcdatetime.free_obj = phongo_utcdatetime_free_object;
phongo_handler_utcdatetime.offset = offsetof(phongo_utcdatetime_t, std);
}
bool phongo_utcdatetime_new(zval* object, int64_t msec_since_epoch)
{
PHONGO_INTERN_INIT_EX(utcdatetime, object);
intern->milliseconds = msec_since_epoch;
intern->initialized = true;
return true;
}
mongodb-2.5.5/src/BSON/UTCDateTime.h 0000644 0001751 0001751 00000001416 15264101572 013650 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.5.5/src/BSON/UTCDateTimeInterface.c 0000644 0001751 0001751 00000001566 15264101572 015472 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 "phongo.h"
#include "UTCDateTimeInterface_arginfo.h"
zend_class_entry* phongo_utcdatetime_interface_ce;
void phongo_utcdatetime_interface_init_ce(INIT_FUNC_ARGS)
{
phongo_utcdatetime_interface_ce = register_class_MongoDB_BSON_UTCDateTimeInterface();
}
mongodb-2.5.5/src/BSON/UTCDateTimeInterface_arginfo.h 0000644 0001751 0001751 00000003661 15264101572 017202 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: f4cd2c12699a833caf1cb1d769d564479052180e */
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[] = {
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("toDateTime", NULL, arginfo_class_MongoDB_BSON_UTCDateTimeInterface_toDateTime, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("toDateTime", NULL, arginfo_class_MongoDB_BSON_UTCDateTimeInterface_toDateTime, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("toDateTimeImmutable", NULL, arginfo_class_MongoDB_BSON_UTCDateTimeInterface_toDateTimeImmutable, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("toDateTimeImmutable", NULL, arginfo_class_MongoDB_BSON_UTCDateTimeInterface_toDateTimeImmutable, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("__toString", NULL, arginfo_class_MongoDB_BSON_UTCDateTimeInterface___toString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("__toString", NULL, arginfo_class_MongoDB_BSON_UTCDateTimeInterface___toString, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
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.5.5/src/BSON/UTCDateTime_arginfo.h 0000644 0001751 0001751 00000007462 15264101572 015364 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 05b6082994907fb78762b1c327450617a00a0830 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
#endif
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.5.5/src/BSON/Undefined.c 0000644 0001751 0001751 00000005315 15264101572 013476 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 "phongo.h"
#include "phongo_error.h"
#include "Undefined_arginfo.h"
zend_class_entry* 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, 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 phongo_handler_undefined;
static void phongo_undefined_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(undefined, object);
zend_object_std_dtor(&intern->std);
}
static zend_object* phongo_undefined_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(undefined, class_type);
intern->std.handlers = &phongo_handler_undefined;
return &intern->std;
}
void phongo_undefined_init_ce(INIT_FUNC_ARGS)
{
phongo_undefined_ce = register_class_MongoDB_BSON_Undefined(phongo_json_serializable_ce, phongo_type_ce, zend_ce_stringable);
phongo_undefined_ce->create_object = phongo_undefined_create_object;
memcpy(&phongo_handler_undefined, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
/* Re-assign default handler previously removed in phongo.c */
phongo_handler_undefined.clone_obj = zend_objects_clone_obj;
phongo_handler_undefined.free_obj = phongo_undefined_free_object;
phongo_handler_undefined.offset = offsetof(phongo_undefined_t, std);
}
mongodb-2.5.5/src/BSON/Undefined_arginfo.h 0000644 0001751 0001751 00000005556 15264101572 015217 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: a3f2e651402ca9aa948ec9462d793db58dc964da */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
#endif
zend_class_implements(class_entry, 3, class_entry_JsonSerializable, class_entry_MongoDB_BSON_Type, class_entry_Stringable);
return class_entry;
}
mongodb-2.5.5/src/BSON/Unserializable.c 0000644 0001751 0001751 00000003231 15264101572 014541 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 "phongo.h"
#include "Unserializable_arginfo.h"
zend_class_entry* phongo_unserializable_ce;
static int phongo_implement_unserializable(zend_class_entry* interface, zend_class_entry* class_type)
{
if (class_type->ce_flags & ZEND_ACC_ENUM) {
zend_class_entry* error_interface = interface;
/* Persistable extends Unserializable, so this handler may be called for
* Persistable enums; prefer Persistable in the fatal message when applicable. */
if (interface == phongo_unserializable_ce && phongo_persistable_ce && instanceof_function(class_type, phongo_persistable_ce)) {
error_interface = phongo_persistable_ce;
}
zend_error_noreturn(E_ERROR, "Enum class %s cannot implement interface %s", ZSTR_VAL(class_type->name), ZSTR_VAL(error_interface->name));
return FAILURE;
}
return SUCCESS;
}
void phongo_unserializable_init_ce(INIT_FUNC_ARGS)
{
phongo_unserializable_ce = register_class_MongoDB_BSON_Unserializable();
phongo_unserializable_ce->interface_gets_implemented = phongo_implement_unserializable;
}
mongodb-2.5.5/src/BSON/Unserializable_arginfo.h 0000644 0001751 0001751 00000001776 15264101572 016267 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 56ea9546c171aa438abb57626f0129fe473339fb */
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[] = {
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("bsonUnserialize", NULL, arginfo_class_MongoDB_BSON_Unserializable_bsonUnserialize, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("bsonUnserialize", NULL, arginfo_class_MongoDB_BSON_Unserializable_bsonUnserialize, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
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.5.5/src/BSON/VectorType.c 0000644 0001751 0001751 00000004127 15264101572 013701 0 ustar /*
* Copyright 2025-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 "phongo.h"
#include "VectorType.h"
#include "VectorType_arginfo.h"
zend_class_entry* phongo_vectortype_ce;
phongo_bson_vector_type_t phongo_bson_vector_type_from_name(const char* name)
{
if (!strcmp(name, PHONGO_BSON_VECTOR_TYPE_FLOAT32_NAME)) {
return PHONGO_BSON_VECTOR_TYPE_FLOAT32;
}
if (!strcmp(name, PHONGO_BSON_VECTOR_TYPE_INT8_NAME)) {
return PHONGO_BSON_VECTOR_TYPE_INT8;
}
if (!strcmp(name, PHONGO_BSON_VECTOR_TYPE_PACKED_BIT_NAME)) {
return PHONGO_BSON_VECTOR_TYPE_PACKED_BIT;
}
return PHONGO_BSON_VECTOR_TYPE_UNKNOWN;
}
const char* phongo_bson_vector_type_to_name(phongo_bson_vector_type_t type)
{
switch (type) {
case PHONGO_BSON_VECTOR_TYPE_FLOAT32:
return PHONGO_BSON_VECTOR_TYPE_FLOAT32_NAME;
case PHONGO_BSON_VECTOR_TYPE_INT8:
return PHONGO_BSON_VECTOR_TYPE_INT8_NAME;
case PHONGO_BSON_VECTOR_TYPE_PACKED_BIT:
return PHONGO_BSON_VECTOR_TYPE_PACKED_BIT_NAME;
default:
return NULL;
}
}
phongo_bson_vector_type_t phongo_bson_vector_type_from_case(zend_object* case_obj)
{
return phongo_bson_vector_type_from_name(Z_STRVAL_P(zend_enum_fetch_case_name(case_obj)));
}
zend_object* phongo_bson_vector_type_to_case(phongo_bson_vector_type_t type)
{
const char* name = phongo_bson_vector_type_to_name(type);
if (!name) {
return NULL;
}
return zend_enum_get_case_cstr(phongo_vectortype_ce, name);
}
void phongo_vectortype_init_ce(INIT_FUNC_ARGS)
{
phongo_vectortype_ce = register_class_MongoDB_BSON_VectorType();
}
mongodb-2.5.5/src/BSON/VectorType.h 0000644 0001751 0001751 00000002636 15264101572 013711 0 ustar /*
* Copyright 2025-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_VECTORTYPE_H
#define PHONGO_BSON_VECTORTYPE_H
#define PHONGO_BSON_VECTOR_TYPE_FLOAT32_NAME "Float32"
#define PHONGO_BSON_VECTOR_TYPE_INT8_NAME "Int8"
#define PHONGO_BSON_VECTOR_TYPE_PACKED_BIT_NAME "PackedBit"
typedef enum {
PHONGO_BSON_VECTOR_TYPE_FLOAT32 = 0x27,
PHONGO_BSON_VECTOR_TYPE_INT8 = 0x03,
PHONGO_BSON_VECTOR_TYPE_PACKED_BIT = 0x10,
PHONGO_BSON_VECTOR_TYPE_UNKNOWN = 0,
} phongo_bson_vector_type_t;
phongo_bson_vector_type_t phongo_bson_vector_type_from_name(const char* name);
const char* phongo_bson_vector_type_to_name(phongo_bson_vector_type_t type);
phongo_bson_vector_type_t phongo_bson_vector_type_from_case(zend_object* case_obj);
zend_object* phongo_bson_vector_type_to_case(phongo_bson_vector_type_t type);
#endif /* PHONGO_BSON_VECTORTYPE_H */
mongodb-2.5.5/src/BSON/VectorType_arginfo.h 0000644 0001751 0001751 00000000756 15264101572 015417 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: f6db546bc317d0d1ab8e7a80ecaf92a058f49875 */
static zend_class_entry *register_class_MongoDB_BSON_VectorType(void)
{
zend_class_entry *class_entry = zend_register_internal_enum("MongoDB\\BSON\\VectorType", IS_UNDEF, NULL);
zend_enum_add_case_cstr(class_entry, "Float32", NULL);
zend_enum_add_case_cstr(class_entry, "Int8", NULL);
zend_enum_add_case_cstr(class_entry, "PackedBit", NULL);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Exception/AuthenticationException.c 0000644 0001751 0001751 00000001653 15264101572 021116 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 "phongo.h"
#include "AuthenticationException_arginfo.h"
zend_class_entry* phongo_authenticationexception_ce;
void phongo_authenticationexception_init_ce(INIT_FUNC_ARGS)
{
phongo_authenticationexception_ce = register_class_MongoDB_Driver_Exception_AuthenticationException(phongo_connectionexception_ce);
}
mongodb-2.5.5/src/MongoDB/Exception/AuthenticationException_arginfo.h 0000644 0001751 0001751 00000001312 15264101572 022620 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 63d10707da7b749576ce02f6e565957f94fd7a37 */
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", NULL);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, class_entry_MongoDB_Driver_Exception_ConnectionException, 0);
#else
class_entry = zend_register_internal_class_ex(&ce, class_entry_MongoDB_Driver_Exception_ConnectionException);
#endif
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Exception/BulkWriteCommandException.c 0000644 0001751 0001751 00000014167 15264101572 021352 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 "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* 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(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(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(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(phongo_bulkwritecommandexception_ce, Z_OBJ_P(getThis()), ZEND_STRL("writeConcernErrors"), 0, &rv);
RETURN_ZVAL(result, 1, 0);
}
void phongo_bulkwritecommandexception_init_ce(INIT_FUNC_ARGS)
{
phongo_bulkwritecommandexception_ce = register_class_MongoDB_Driver_Exception_BulkWriteCommandException(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 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(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), phongo_bulkwritecommandresult_ce)) {
zend_update_property(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(phongo_bulkwritecommandexception_ce, object, ZEND_STRL("writeConcernErrors"), &zwriteconcernerrors);
}
if (phongo_bulkwritecommandexception_get_writeerrors(mongoc_bulkwriteexception_writeerrors(bw_exc), &zwriteerrors)) {
zend_update_property(phongo_bulkwritecommandexception_ce, object, ZEND_STRL("writeErrors"), &zwriteerrors);
}
zval_ptr_dtor(&zwriteconcernerrors);
zval_ptr_dtor(&zwriteerrors);
}
mongodb-2.5.5/src/MongoDB/Exception/BulkWriteCommandException.h 0000644 0001751 0001751 00000001621 15264101572 021346 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 phongo_bulkwritecommandexception_init_props(zend_object* object, const mongoc_bulkwriteexception_t* bw_exc, zval* result);
#endif /* PHONGO_BULKWRITECOMMANDEXCEPTION_H */
mongodb-2.5.5/src/MongoDB/Exception/BulkWriteCommandException_arginfo.h 0000644 0001751 0001751 00000011645 15264101572 023062 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 8e4d85c10a3ec545f3ca38591d74195d4732eac5 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, class_entry_MongoDB_Driver_Exception_ServerException, ZEND_ACC_FINAL);
#else
class_entry = zend_register_internal_class_ex(&ce, class_entry_MongoDB_Driver_Exception_ServerException);
class_entry->ce_flags |= ZEND_ACC_FINAL;
#endif
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_string *property_errorReply_class_MongoDB_BSON_Document = zend_string_init("MongoDB\\BSON\\Document", sizeof("MongoDB\\BSON\\Document")-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);
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_string *property_partialResult_class_MongoDB_Driver_BulkWriteCommandResult = zend_string_init("MongoDB\\Driver\\BulkWriteCommandResult", sizeof("MongoDB\\Driver\\BulkWriteCommandResult")-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.5.5/src/MongoDB/Exception/BulkWriteException.c 0000644 0001751 0001751 00000002426 15264101572 020046 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 "phongo.h"
#include "phongo_error.h"
#include "BulkWriteException_arginfo.h"
zend_class_entry* 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(phongo_bulkwriteexception_ce, Z_OBJ_P(getThis()), ZEND_STRL("writeResult"), 0, &rv);
RETURN_ZVAL(writeresult, 1, 0);
}
void phongo_bulkwriteexception_init_ce(INIT_FUNC_ARGS)
{
phongo_bulkwriteexception_ce = register_class_MongoDB_Driver_Exception_BulkWriteException(phongo_serverexception_ce);
}
mongodb-2.5.5/src/MongoDB/Exception/BulkWriteException_arginfo.h 0000644 0001751 0001751 00000003631 15264101572 021557 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: ef1bf3a5b851c5e1e6c80ffb3daad587913f639f */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, class_entry_MongoDB_Driver_Exception_ServerException, 0);
#else
class_entry = zend_register_internal_class_ex(&ce, class_entry_MongoDB_Driver_Exception_ServerException);
#endif
zval property_writeResult_default_value;
ZVAL_UNDEF(&property_writeResult_default_value);
zend_string *property_writeResult_name = zend_string_init("writeResult", sizeof("writeResult") - 1, 1);
zend_string *property_writeResult_class_MongoDB_Driver_WriteResult = zend_string_init("MongoDB\\Driver\\WriteResult", sizeof("MongoDB\\Driver\\WriteResult")-1, 1);
zend_declare_typed_property(class_entry, property_writeResult_name, &property_writeResult_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_writeResult_class_MongoDB_Driver_WriteResult, 0, 0));
zend_string_release(property_writeResult_name);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Exception/CommandException.c 0000644 0001751 0001751 00000002423 15264101572 017511 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 "phongo.h"
#include "phongo_error.h"
#include "CommandException_arginfo.h"
zend_class_entry* 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(phongo_commandexception_ce, Z_OBJ_P(getThis()), ZEND_STRL("resultDocument"), 0, &rv);
RETURN_ZVAL(resultdocument, 1, 0);
}
void phongo_commandexception_init_ce(INIT_FUNC_ARGS)
{
phongo_commandexception_ce = register_class_MongoDB_Driver_Exception_CommandException(phongo_serverexception_ce);
}
mongodb-2.5.5/src/MongoDB/Exception/CommandException_arginfo.h 0000644 0001751 0001751 00000003307 15264101572 021225 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 5c92211a99c6771f13c7ae6e37f01bd387bc6f2a */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, class_entry_MongoDB_Driver_Exception_ServerException, 0);
#else
class_entry = zend_register_internal_class_ex(&ce, class_entry_MongoDB_Driver_Exception_ServerException);
#endif
zval property_resultDocument_default_value;
ZVAL_UNDEF(&property_resultDocument_default_value);
zend_string *property_resultDocument_name = zend_string_init("resultDocument", sizeof("resultDocument") - 1, 1);
zend_declare_typed_property(class_entry, property_resultDocument_name, &property_resultDocument_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_OBJECT));
zend_string_release(property_resultDocument_name);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Exception/ConnectionException.c 0000644 0001751 0001751 00000001624 15264101572 020234 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 "phongo.h"
#include "ConnectionException_arginfo.h"
zend_class_entry* phongo_connectionexception_ce;
void phongo_connectionexception_init_ce(INIT_FUNC_ARGS)
{
phongo_connectionexception_ce = register_class_MongoDB_Driver_Exception_ConnectionException(phongo_runtimeexception_ce);
}
mongodb-2.5.5/src/MongoDB/Exception/ConnectionException_arginfo.h 0000644 0001751 0001751 00000001271 15264101572 021744 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: bc5696aa261289787b61d29dcdbd0ae8b782c40b */
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", NULL);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, class_entry_MongoDB_Driver_Exception_RuntimeException, 0);
#else
class_entry = zend_register_internal_class_ex(&ce, class_entry_MongoDB_Driver_Exception_RuntimeException);
#endif
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Exception/ConnectionTimeoutException.c 0000644 0001751 0001751 00000001672 15264101572 021606 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 "phongo.h"
#include "ConnectionTimeoutException_arginfo.h"
zend_class_entry* phongo_connectiontimeoutexception_ce;
void phongo_connectiontimeoutexception_init_ce(INIT_FUNC_ARGS)
{
phongo_connectiontimeoutexception_ce = register_class_MongoDB_Driver_Exception_ConnectionTimeoutException(phongo_connectionexception_ce);
}
mongodb-2.5.5/src/MongoDB/Exception/ConnectionTimeoutException_arginfo.h 0000644 0001751 0001751 00000001407 15264101572 023314 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 57a9674abe9a302a39515e475f5af803fa3a03d6 */
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", NULL);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, class_entry_MongoDB_Driver_Exception_ConnectionException, ZEND_ACC_FINAL);
#else
class_entry = zend_register_internal_class_ex(&ce, class_entry_MongoDB_Driver_Exception_ConnectionException);
class_entry->ce_flags |= ZEND_ACC_FINAL;
#endif
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Exception/EncryptionException.c 0000644 0001751 0001751 00000001624 15264101572 020267 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 "phongo.h"
#include "EncryptionException_arginfo.h"
zend_class_entry* phongo_encryptionexception_ce;
void phongo_encryptionexception_init_ce(INIT_FUNC_ARGS)
{
phongo_encryptionexception_ce = register_class_MongoDB_Driver_Exception_EncryptionException(phongo_runtimeexception_ce);
}
mongodb-2.5.5/src/MongoDB/Exception/EncryptionException_arginfo.h 0000644 0001751 0001751 00000001271 15264101572 021777 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 27f5cb800d4f6d5bc710a48c3831622d2bc1e83d */
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", NULL);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, class_entry_MongoDB_Driver_Exception_RuntimeException, 0);
#else
class_entry = zend_register_internal_class_ex(&ce, class_entry_MongoDB_Driver_Exception_RuntimeException);
#endif
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Exception/Exception.c 0000644 0001751 0001751 00000001566 15264101572 016221 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 "phongo.h"
#include "Exception_arginfo.h"
zend_class_entry* phongo_exception_ce;
void phongo_exception_init_ce(INIT_FUNC_ARGS)
{
phongo_exception_ce = register_class_MongoDB_Driver_Exception_Exception(zend_ce_throwable);
}
mongodb-2.5.5/src/MongoDB/Exception/Exception_arginfo.h 0000644 0001751 0001751 00000000754 15264101572 017731 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 20977240e2f1eb527ecb609d61137353a1a5973a */
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", NULL);
class_entry = zend_register_internal_interface(&ce);
zend_class_implements(class_entry, 1, class_entry_Throwable);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Exception/ExecutionTimeoutException.c 0000644 0001751 0001751 00000001661 15264101572 021450 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 "phongo.h"
#include "ExecutionTimeoutException_arginfo.h"
zend_class_entry* phongo_executiontimeoutexception_ce;
void phongo_executiontimeoutexception_init_ce(INIT_FUNC_ARGS)
{
phongo_executiontimeoutexception_ce = register_class_MongoDB_Driver_Exception_ExecutionTimeoutException(phongo_serverexception_ce);
}
mongodb-2.5.5/src/MongoDB/Exception/ExecutionTimeoutException_arginfo.h 0000644 0001751 0001751 00000001371 15264101572 023160 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 1a4f91d780a89d2a50c5239070589470e76e768b */
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", NULL);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, class_entry_MongoDB_Driver_Exception_ServerException, ZEND_ACC_FINAL);
#else
class_entry = zend_register_internal_class_ex(&ce, class_entry_MongoDB_Driver_Exception_ServerException);
class_entry->ce_flags |= ZEND_ACC_FINAL;
#endif
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Exception/InvalidArgumentException.c 0000644 0001751 0001751 00000001753 15264101572 021231 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 "phongo.h"
#include "InvalidArgumentException_arginfo.h"
zend_class_entry* phongo_invalidargumentexception_ce;
void phongo_invalidargumentexception_init_ce(INIT_FUNC_ARGS)
{
phongo_invalidargumentexception_ce = register_class_MongoDB_Driver_Exception_InvalidArgumentException(spl_ce_InvalidArgumentException, phongo_exception_ce);
}
mongodb-2.5.5/src/MongoDB/Exception/InvalidArgumentException_arginfo.h 0000644 0001751 0001751 00000001452 15264101572 022737 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 83e36c8ba8811dea91d9fde0e5673916c8027b66 */
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", NULL);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, class_entry_InvalidArgumentException, 0);
#else
class_entry = zend_register_internal_class_ex(&ce, class_entry_InvalidArgumentException);
#endif
zend_class_implements(class_entry, 1, class_entry_MongoDB_Driver_Exception_Exception);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Exception/LogicException.c 0000644 0001751 0001751 00000001657 15264101572 017200 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 "phongo.h"
#include "LogicException_arginfo.h"
zend_class_entry* phongo_logicexception_ce;
void phongo_logicexception_init_ce(INIT_FUNC_ARGS)
{
phongo_logicexception_ce = register_class_MongoDB_Driver_Exception_LogicException(spl_ce_LogicException, phongo_exception_ce);
}
mongodb-2.5.5/src/MongoDB/Exception/LogicException_arginfo.h 0000644 0001751 0001751 00000001370 15264101572 020702 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 5ab852c50a988ce0fe2f9f32f5fb2e4b838ab3f9 */
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", NULL);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, class_entry_LogicException, 0);
#else
class_entry = zend_register_internal_class_ex(&ce, class_entry_LogicException);
#endif
zend_class_implements(class_entry, 1, class_entry_MongoDB_Driver_Exception_Exception);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Exception/RuntimeException.c 0000644 0001751 0001751 00000003603 15264101572 017557 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 "phongo.h"
#include "phongo_error.h"
#include "RuntimeException_arginfo.h"
zend_class_entry* phongo_runtimeexception_ce;
static bool 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(phongo_runtimeexception_ce, Z_OBJ_P(getThis()), ZEND_STRL("errorLabels"), 0, &rv);
RETURN_BOOL(phongo_has_string_array_element(error_labels, label));
}
void phongo_runtimeexception_init_ce(INIT_FUNC_ARGS)
{
phongo_runtimeexception_ce = register_class_MongoDB_Driver_Exception_RuntimeException(spl_ce_RuntimeException, phongo_exception_ce);
}
mongodb-2.5.5/src/MongoDB/Exception/RuntimeException_arginfo.h 0000644 0001751 0001751 00000003405 15264101572 021271 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: d1165a1dc3d202bd1f29d0b5ffdc336e4faf65d6 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, class_entry_RuntimeException, 0);
#else
class_entry = zend_register_internal_class_ex(&ce, class_entry_RuntimeException);
#endif
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_typed_property(class_entry, property_errorLabels_name, &property_errorLabels_default_value, ZEND_ACC_PROTECTED, NULL, (zend_type) ZEND_TYPE_INIT_NONE(0));
zend_string_release(property_errorLabels_name);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Exception/ServerException.c 0000644 0001751 0001751 00000001600 15264101572 017375 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 "phongo.h"
#include "ServerException_arginfo.h"
zend_class_entry* phongo_serverexception_ce;
void phongo_serverexception_init_ce(INIT_FUNC_ARGS)
{
phongo_serverexception_ce = register_class_MongoDB_Driver_Exception_ServerException(phongo_runtimeexception_ce);
}
mongodb-2.5.5/src/MongoDB/Exception/ServerException_arginfo.h 0000644 0001751 0001751 00000001261 15264101572 021112 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 19490ac980b38cd2a6c25c93baf7e1ac0467961f */
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", NULL);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, class_entry_MongoDB_Driver_Exception_RuntimeException, 0);
#else
class_entry = zend_register_internal_class_ex(&ce, class_entry_MongoDB_Driver_Exception_RuntimeException);
#endif
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Exception/UnexpectedValueException.c 0000644 0001751 0001751 00000001753 15264101572 021241 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 "phongo.h"
#include "UnexpectedValueException_arginfo.h"
zend_class_entry* phongo_unexpectedvalueexception_ce;
void phongo_unexpectedvalueexception_init_ce(INIT_FUNC_ARGS)
{
phongo_unexpectedvalueexception_ce = register_class_MongoDB_Driver_Exception_UnexpectedValueException(spl_ce_UnexpectedValueException, phongo_exception_ce);
}
mongodb-2.5.5/src/MongoDB/Exception/UnexpectedValueException_arginfo.h 0000644 0001751 0001751 00000001452 15264101572 022747 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: f2934f2b5cb4d9407b5bbbf59698a7411c908863 */
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", NULL);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, class_entry_UnexpectedValueException, 0);
#else
class_entry = zend_register_internal_class_ex(&ce, class_entry_UnexpectedValueException);
#endif
zend_class_implements(class_entry, 1, class_entry_MongoDB_Driver_Exception_Exception);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Monitoring/CommandFailedEvent.c 0000644 0001751 0001751 00000013502 15264101572 020130 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
#include "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* phongo_commandfailedevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_CommandFailedEvent)
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandFailedEvent, getCommandName, commandfailedevent, "commandName")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandFailedEvent, getDatabaseName, commandfailedevent, "databaseName")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandFailedEvent, getDurationMicros, commandfailedevent, "duration")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandFailedEvent, getError, commandfailedevent, "error")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandFailedEvent, getHost, commandfailedevent, "host")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandFailedEvent, getOperationId, commandfailedevent, "operationId")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandFailedEvent, getPort, commandfailedevent, "port")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandFailedEvent, getReply, commandfailedevent, "reply")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandFailedEvent, getRequestId, commandfailedevent, "requestId")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandFailedEvent, getServiceId, commandfailedevent, "serviceId")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandFailedEvent, getServerConnectionId, commandfailedevent, "serverConnectionId")
static void phongo_commandfailedevent_update_properties(zend_object* object, const mongoc_apm_command_failed_t* event)
{
char operation_id[24], request_id[24];
phongo_bson_state reply_state;
int64_t server_connection_id = mongoc_apm_command_failed_get_server_connection_id_int64(event);
PHONGO_BSON_INIT_NO_ODM_STATE(reply_state);
zend_update_property_string(phongo_commandfailedevent_ce, object, ZEND_STRL("host"), mongoc_apm_command_failed_get_host(event)->host);
zend_update_property_long(phongo_commandfailedevent_ce, object, ZEND_STRL("port"), mongoc_apm_command_failed_get_host(event)->port);
zend_update_property_string(phongo_commandfailedevent_ce, object, ZEND_STRL("commandName"), mongoc_apm_command_failed_get_command_name(event));
zend_update_property_string(phongo_commandfailedevent_ce, object, ZEND_STRL("databaseName"), mongoc_apm_command_failed_get_database_name(event));
zend_update_property_long(phongo_commandfailedevent_ce, object, ZEND_STRL("duration"), mongoc_apm_command_failed_get_duration(event));
{
bson_error_t tmp_error = { 0 };
zval z_error;
mongoc_apm_command_failed_get_error(event, &tmp_error);
object_init_ex(&z_error, phongo_exception_from_mongoc_domain(tmp_error.domain, tmp_error.code));
zend_update_property_string(zend_ce_exception, Z_OBJ_P(&z_error), ZEND_STRL("message"), tmp_error.message);
zend_update_property_long(zend_ce_exception, Z_OBJ_P(&z_error), ZEND_STRL("code"), tmp_error.code);
zend_update_property(phongo_commandfailedevent_ce, object, ZEND_STRL("error"), &z_error);
zval_ptr_dtor(&z_error);
}
if (phongo_bson_to_zval_ex(mongoc_apm_command_failed_get_reply(event), &reply_state)) {
zend_update_property(phongo_commandfailedevent_ce, object, ZEND_STRL("reply"), &reply_state.zchild);
}
zval_ptr_dtor(&reply_state.zchild);
snprintf(operation_id, sizeof(operation_id), "%" PRId64, mongoc_apm_command_failed_get_operation_id(event));
zend_update_property_string(phongo_commandfailedevent_ce, object, ZEND_STRL("operationId"), operation_id);
snprintf(request_id, sizeof(request_id), "%" PRId64, mongoc_apm_command_failed_get_request_id(event));
zend_update_property_string(phongo_commandfailedevent_ce, object, ZEND_STRL("requestId"), request_id);
if (mongoc_apm_command_failed_get_service_id(event)) {
zval service_id;
if (phongo_objectid_new(&service_id, mongoc_apm_command_failed_get_service_id(event))) {
zend_update_property(phongo_commandfailedevent_ce, object, ZEND_STRL("serviceId"), &service_id);
zval_ptr_dtor(&service_id);
}
} else {
zend_update_property_null(phongo_commandfailedevent_ce, object, ZEND_STRL("serviceId"));
}
/* TODO: Use MONGOC_NO_SERVER_CONNECTION_ID once it is added to libmongoc's public API (CDRIVER-4176) */
if (server_connection_id == -1) {
zend_update_property_null(phongo_commandfailedevent_ce, object, ZEND_STRL("serverConnectionId"));
} else {
#if SIZEOF_ZEND_LONG == 4
if (server_connection_id > INT32_MAX || server_connection_id < INT32_MIN) {
zend_error(E_WARNING, "Truncating 64-bit value %" PRId64 " for serverConnectionId", server_connection_id);
}
#endif
zend_update_property_long(phongo_commandfailedevent_ce, object, ZEND_STRL("serverConnectionId"), server_connection_id);
}
}
void phongo_commandfailedevent_init_ce(INIT_FUNC_ARGS)
{
phongo_commandfailedevent_ce = register_class_MongoDB_Driver_Monitoring_CommandFailedEvent();
}
void phongo_commandfailedevent_init(zval* return_value, const mongoc_apm_command_failed_t* event)
{
PHONGO_OBJECT_INIT_EX(commandfailedevent, return_value);
phongo_commandfailedevent_update_properties(object, event);
} mongodb-2.5.5/src/MongoDB/Monitoring/CommandFailedEvent_arginfo.h 0000644 0001751 0001751 00000024345 15264101572 021651 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: a8c6d822dc54c673adeb79b31e5df8d1277df4dd */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
zval property_host_default_value;
ZVAL_UNDEF(&property_host_default_value);
zend_declare_typed_property(class_entry, ZSTR_KNOWN(ZEND_STR_HOST), &property_host_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zval property_port_default_value;
ZVAL_UNDEF(&property_port_default_value);
zend_declare_typed_property(class_entry, ZSTR_KNOWN(ZEND_STR_PORT), &property_port_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zval property_commandName_default_value;
ZVAL_UNDEF(&property_commandName_default_value);
zend_string *property_commandName_name = zend_string_init("commandName", sizeof("commandName") - 1, 1);
zend_declare_typed_property(class_entry, property_commandName_name, &property_commandName_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zend_string_release(property_commandName_name);
zval property_databaseName_default_value;
ZVAL_UNDEF(&property_databaseName_default_value);
zend_string *property_databaseName_name = zend_string_init("databaseName", sizeof("databaseName") - 1, 1);
zend_declare_typed_property(class_entry, property_databaseName_name, &property_databaseName_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zend_string_release(property_databaseName_name);
zval property_duration_default_value;
ZVAL_UNDEF(&property_duration_default_value);
zend_string *property_duration_name = zend_string_init("duration", sizeof("duration") - 1, 1);
zend_declare_typed_property(class_entry, property_duration_name, &property_duration_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_duration_name);
zval property_error_default_value;
ZVAL_UNDEF(&property_error_default_value);
zend_string *property_error_name = zend_string_init("error", sizeof("error") - 1, 1);
zend_string *property_error_class_Exception = zend_string_init("Exception", sizeof("Exception")-1, 1);
zend_declare_typed_property(class_entry, property_error_name, &property_error_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_error_class_Exception, 0, 0));
zend_string_release(property_error_name);
zval property_reply_default_value;
ZVAL_UNDEF(&property_reply_default_value);
zend_string *property_reply_name = zend_string_init("reply", sizeof("reply") - 1, 1);
zend_declare_typed_property(class_entry, property_reply_name, &property_reply_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_OBJECT));
zend_string_release(property_reply_name);
zval property_operationId_default_value;
ZVAL_UNDEF(&property_operationId_default_value);
zend_string *property_operationId_name = zend_string_init("operationId", sizeof("operationId") - 1, 1);
zend_declare_typed_property(class_entry, property_operationId_name, &property_operationId_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zend_string_release(property_operationId_name);
zval property_requestId_default_value;
ZVAL_UNDEF(&property_requestId_default_value);
zend_string *property_requestId_name = zend_string_init("requestId", sizeof("requestId") - 1, 1);
zend_declare_typed_property(class_entry, property_requestId_name, &property_requestId_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zend_string_release(property_requestId_name);
zval property_serviceId_default_value;
ZVAL_UNDEF(&property_serviceId_default_value);
zend_string *property_serviceId_name = zend_string_init("serviceId", sizeof("serviceId") - 1, 1);
zend_string *property_serviceId_class_MongoDB_BSON_ObjectId = zend_string_init("MongoDB\\BSON\\ObjectId", sizeof("MongoDB\\BSON\\ObjectId")-1, 1);
zend_declare_typed_property(class_entry, property_serviceId_name, &property_serviceId_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_serviceId_class_MongoDB_BSON_ObjectId, 0, MAY_BE_NULL));
zend_string_release(property_serviceId_name);
zval property_serverConnectionId_default_value;
ZVAL_UNDEF(&property_serverConnectionId_default_value);
zend_string *property_serverConnectionId_name = zend_string_init("serverConnectionId", sizeof("serverConnectionId") - 1, 1);
zend_declare_typed_property(class_entry, property_serverConnectionId_name, &property_serverConnectionId_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG|MAY_BE_NULL));
zend_string_release(property_serverConnectionId_name);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Monitoring/CommandStartedEvent.c 0000644 0001751 0001751 00000011716 15264101572 020357 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 "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* phongo_commandstartedevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_CommandStartedEvent)
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandStartedEvent, getCommand, commandstartedevent, "command")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandStartedEvent, getCommandName, commandstartedevent, "commandName")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandStartedEvent, getDatabaseName, commandstartedevent, "databaseName")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandStartedEvent, getHost, commandstartedevent, "host")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandStartedEvent, getOperationId, commandstartedevent, "operationId")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandStartedEvent, getPort, commandstartedevent, "port")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandStartedEvent, getRequestId, commandstartedevent, "requestId")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandStartedEvent, getServiceId, commandstartedevent, "serviceId")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandStartedEvent, getServerConnectionId, commandstartedevent, "serverConnectionId")
static void phongo_commandstartedevent_update_properties(zend_object* object, const mongoc_apm_command_started_t* event)
{
char operation_id[24], request_id[24];
phongo_bson_state command_state;
int64_t server_connection_id = mongoc_apm_command_started_get_server_connection_id_int64(event);
PHONGO_BSON_INIT_NO_ODM_STATE(command_state);
zend_update_property_string(phongo_commandstartedevent_ce, object, ZEND_STRL("host"), mongoc_apm_command_started_get_host(event)->host);
zend_update_property_long(phongo_commandstartedevent_ce, object, ZEND_STRL("port"), mongoc_apm_command_started_get_host(event)->port);
zend_update_property_string(phongo_commandstartedevent_ce, object, ZEND_STRL("commandName"), mongoc_apm_command_started_get_command_name(event));
zend_update_property_string(phongo_commandstartedevent_ce, object, ZEND_STRL("databaseName"), mongoc_apm_command_started_get_database_name(event));
if (phongo_bson_to_zval_ex(mongoc_apm_command_started_get_command(event), &command_state)) {
zend_update_property(phongo_commandstartedevent_ce, object, ZEND_STRL("command"), &command_state.zchild);
}
zval_ptr_dtor(&command_state.zchild);
snprintf(operation_id, sizeof(operation_id), "%" PRId64, mongoc_apm_command_started_get_operation_id(event));
zend_update_property_string(phongo_commandstartedevent_ce, object, ZEND_STRL("operationId"), operation_id);
snprintf(request_id, sizeof(request_id), "%" PRId64, mongoc_apm_command_started_get_request_id(event));
zend_update_property_string(phongo_commandstartedevent_ce, object, ZEND_STRL("requestId"), request_id);
if (mongoc_apm_command_started_get_service_id(event)) {
zval service_id;
if (phongo_objectid_new(&service_id, mongoc_apm_command_started_get_service_id(event))) {
zend_update_property(phongo_commandstartedevent_ce, object, ZEND_STRL("serviceId"), &service_id);
zval_ptr_dtor(&service_id);
}
} else {
zend_update_property_null(phongo_commandstartedevent_ce, object, ZEND_STRL("serviceId"));
}
/* TODO: Use MONGOC_NO_SERVER_CONNECTION_ID once it is added to libmongoc's public API (CDRIVER-4176) */
if (server_connection_id == -1) {
zend_update_property_null(phongo_commandstartedevent_ce, object, ZEND_STRL("serverConnectionId"));
} else {
#if SIZEOF_ZEND_LONG == 4
if (server_connection_id > INT32_MAX || server_connection_id < INT32_MIN) {
zend_error(E_WARNING, "Truncating 64-bit value %" PRId64 " for serverConnectionId", server_connection_id);
}
#endif
zend_update_property_long(phongo_commandstartedevent_ce, object, ZEND_STRL("serverConnectionId"), server_connection_id);
}
}
void phongo_commandstartedevent_init_ce(INIT_FUNC_ARGS)
{
phongo_commandstartedevent_ce = register_class_MongoDB_Driver_Monitoring_CommandStartedEvent();
}
void phongo_commandstartedevent_init(zval* return_value, const mongoc_apm_command_started_t* event)
{
PHONGO_OBJECT_INIT_EX(commandstartedevent, return_value);
phongo_commandstartedevent_update_properties(object, event);
}
mongodb-2.5.5/src/MongoDB/Monitoring/CommandStartedEvent_arginfo.h 0000644 0001751 0001751 00000021112 15264101572 022060 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: e250ffaa013fd197fb3946669d1f186da158606d */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
zval property_host_default_value;
ZVAL_UNDEF(&property_host_default_value);
zend_declare_typed_property(class_entry, ZSTR_KNOWN(ZEND_STR_HOST), &property_host_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zval property_port_default_value;
ZVAL_UNDEF(&property_port_default_value);
zend_declare_typed_property(class_entry, ZSTR_KNOWN(ZEND_STR_PORT), &property_port_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zval property_commandName_default_value;
ZVAL_UNDEF(&property_commandName_default_value);
zend_string *property_commandName_name = zend_string_init("commandName", sizeof("commandName") - 1, 1);
zend_declare_typed_property(class_entry, property_commandName_name, &property_commandName_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zend_string_release(property_commandName_name);
zval property_databaseName_default_value;
ZVAL_UNDEF(&property_databaseName_default_value);
zend_string *property_databaseName_name = zend_string_init("databaseName", sizeof("databaseName") - 1, 1);
zend_declare_typed_property(class_entry, property_databaseName_name, &property_databaseName_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zend_string_release(property_databaseName_name);
zval property_command_default_value;
ZVAL_UNDEF(&property_command_default_value);
zend_string *property_command_name = zend_string_init("command", sizeof("command") - 1, 1);
zend_declare_typed_property(class_entry, property_command_name, &property_command_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_OBJECT));
zend_string_release(property_command_name);
zval property_operationId_default_value;
ZVAL_UNDEF(&property_operationId_default_value);
zend_string *property_operationId_name = zend_string_init("operationId", sizeof("operationId") - 1, 1);
zend_declare_typed_property(class_entry, property_operationId_name, &property_operationId_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zend_string_release(property_operationId_name);
zval property_requestId_default_value;
ZVAL_UNDEF(&property_requestId_default_value);
zend_string *property_requestId_name = zend_string_init("requestId", sizeof("requestId") - 1, 1);
zend_declare_typed_property(class_entry, property_requestId_name, &property_requestId_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zend_string_release(property_requestId_name);
zval property_serviceId_default_value;
ZVAL_UNDEF(&property_serviceId_default_value);
zend_string *property_serviceId_name = zend_string_init("serviceId", sizeof("serviceId") - 1, 1);
zend_string *property_serviceId_class_MongoDB_BSON_ObjectId = zend_string_init("MongoDB\\BSON\\ObjectId", sizeof("MongoDB\\BSON\\ObjectId")-1, 1);
zend_declare_typed_property(class_entry, property_serviceId_name, &property_serviceId_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_serviceId_class_MongoDB_BSON_ObjectId, 0, MAY_BE_NULL));
zend_string_release(property_serviceId_name);
zval property_serverConnectionId_default_value;
ZVAL_UNDEF(&property_serverConnectionId_default_value);
zend_string *property_serverConnectionId_name = zend_string_init("serverConnectionId", sizeof("serverConnectionId") - 1, 1);
zend_declare_typed_property(class_entry, property_serverConnectionId_name, &property_serverConnectionId_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG|MAY_BE_NULL));
zend_string_release(property_serverConnectionId_name);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Monitoring/CommandSubscriber.c 0000644 0001751 0001751 00000001605 15264101572 020046 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 "phongo.h"
#include "CommandSubscriber_arginfo.h"
zend_class_entry* phongo_commandsubscriber_ce;
void phongo_commandsubscriber_init_ce(INIT_FUNC_ARGS)
{
phongo_commandsubscriber_ce = register_class_MongoDB_Driver_Monitoring_CommandSubscriber(phongo_subscriber_ce);
}
mongodb-2.5.5/src/MongoDB/Monitoring/CommandSubscriber_arginfo.h 0000644 0001751 0001751 00000004714 15264101572 021564 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 3207fb6b6a5b00471d08add24c41e062d7d2b43e */
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[] = {
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("commandStarted", NULL, arginfo_class_MongoDB_Driver_Monitoring_CommandSubscriber_commandStarted, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("commandStarted", NULL, arginfo_class_MongoDB_Driver_Monitoring_CommandSubscriber_commandStarted, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("commandSucceeded", NULL, arginfo_class_MongoDB_Driver_Monitoring_CommandSubscriber_commandSucceeded, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("commandSucceeded", NULL, arginfo_class_MongoDB_Driver_Monitoring_CommandSubscriber_commandSucceeded, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("commandFailed", NULL, arginfo_class_MongoDB_Driver_Monitoring_CommandSubscriber_commandFailed, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("commandFailed", NULL, arginfo_class_MongoDB_Driver_Monitoring_CommandSubscriber_commandFailed, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
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.5.5/src/MongoDB/Monitoring/CommandSucceededEvent.c 0000644 0001751 0001751 00000012456 15264101572 020637 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 "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* phongo_commandsucceededevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_CommandSucceededEvent)
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandSucceededEvent, getCommandName, commandsucceededevent, "commandName")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandSucceededEvent, getDatabaseName, commandsucceededevent, "databaseName")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandSucceededEvent, getDurationMicros, commandsucceededevent, "duration")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandSucceededEvent, getHost, commandsucceededevent, "host")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandSucceededEvent, getOperationId, commandsucceededevent, "operationId")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandSucceededEvent, getPort, commandsucceededevent, "port")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandSucceededEvent, getReply, commandsucceededevent, "reply")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandSucceededEvent, getRequestId, commandsucceededevent, "requestId")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandSucceededEvent, getServiceId, commandsucceededevent, "serviceId")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_CommandSucceededEvent, getServerConnectionId, commandsucceededevent, "serverConnectionId")
static void phongo_commandsucceededevent_update_properties(zend_object* object, const mongoc_apm_command_succeeded_t* event)
{
char operation_id[24], request_id[24];
phongo_bson_state reply_state;
int64_t server_connection_id = mongoc_apm_command_succeeded_get_server_connection_id_int64(event);
PHONGO_BSON_INIT_NO_ODM_STATE(reply_state);
zend_update_property_string(phongo_commandsucceededevent_ce, object, ZEND_STRL("host"), mongoc_apm_command_succeeded_get_host(event)->host);
zend_update_property_long(phongo_commandsucceededevent_ce, object, ZEND_STRL("port"), mongoc_apm_command_succeeded_get_host(event)->port);
zend_update_property_string(phongo_commandsucceededevent_ce, object, ZEND_STRL("commandName"), mongoc_apm_command_succeeded_get_command_name(event));
zend_update_property_string(phongo_commandsucceededevent_ce, object, ZEND_STRL("databaseName"), mongoc_apm_command_succeeded_get_database_name(event));
zend_update_property_long(phongo_commandsucceededevent_ce, object, ZEND_STRL("duration"), mongoc_apm_command_succeeded_get_duration(event));
if (phongo_bson_to_zval_ex(mongoc_apm_command_succeeded_get_reply(event), &reply_state)) {
zend_update_property(phongo_commandsucceededevent_ce, object, ZEND_STRL("reply"), &reply_state.zchild);
}
zval_ptr_dtor(&reply_state.zchild);
snprintf(operation_id, sizeof(operation_id), "%" PRId64, mongoc_apm_command_succeeded_get_operation_id(event));
zend_update_property_string(phongo_commandsucceededevent_ce, object, ZEND_STRL("operationId"), operation_id);
snprintf(request_id, sizeof(request_id), "%" PRId64, mongoc_apm_command_succeeded_get_request_id(event));
zend_update_property_string(phongo_commandsucceededevent_ce, object, ZEND_STRL("requestId"), request_id);
if (mongoc_apm_command_succeeded_get_service_id(event)) {
zval service_id;
if (phongo_objectid_new(&service_id, mongoc_apm_command_succeeded_get_service_id(event))) {
zend_update_property(phongo_commandsucceededevent_ce, object, ZEND_STRL("serviceId"), &service_id);
zval_ptr_dtor(&service_id);
}
} else {
zend_update_property_null(phongo_commandsucceededevent_ce, object, ZEND_STRL("serviceId"));
}
/* TODO: Use MONGOC_NO_SERVER_CONNECTION_ID once it is added to libmongoc's public API (CDRIVER-4176) */
if (server_connection_id == -1) {
zend_update_property_null(phongo_commandsucceededevent_ce, object, ZEND_STRL("serverConnectionId"));
} else {
#if SIZEOF_ZEND_LONG == 4
if (server_connection_id > INT32_MAX || server_connection_id < INT32_MIN) {
zend_error(E_WARNING, "Truncating 64-bit value %" PRId64 " for serverConnectionId", server_connection_id);
}
#endif
zend_update_property_long(phongo_commandsucceededevent_ce, object, ZEND_STRL("serverConnectionId"), server_connection_id);
}
}
void phongo_commandsucceededevent_init_ce(INIT_FUNC_ARGS)
{
phongo_commandsucceededevent_ce = register_class_MongoDB_Driver_Monitoring_CommandSucceededEvent();
}
void phongo_commandsucceededevent_init(zval* return_value, const mongoc_apm_command_succeeded_t* event)
{
PHONGO_OBJECT_INIT_EX(commandsucceededevent, return_value);
phongo_commandsucceededevent_update_properties(object, event);
}
mongodb-2.5.5/src/MongoDB/Monitoring/CommandSucceededEvent_arginfo.h 0000644 0001751 0001751 00000022762 15264101572 022352 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 9341ea392077dd748049c3c7a1eadb0eff540969 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
zval property_host_default_value;
ZVAL_UNDEF(&property_host_default_value);
zend_declare_typed_property(class_entry, ZSTR_KNOWN(ZEND_STR_HOST), &property_host_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zval property_port_default_value;
ZVAL_UNDEF(&property_port_default_value);
zend_declare_typed_property(class_entry, ZSTR_KNOWN(ZEND_STR_PORT), &property_port_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zval property_commandName_default_value;
ZVAL_UNDEF(&property_commandName_default_value);
zend_string *property_commandName_name = zend_string_init("commandName", sizeof("commandName") - 1, 1);
zend_declare_typed_property(class_entry, property_commandName_name, &property_commandName_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zend_string_release(property_commandName_name);
zval property_databaseName_default_value;
ZVAL_UNDEF(&property_databaseName_default_value);
zend_string *property_databaseName_name = zend_string_init("databaseName", sizeof("databaseName") - 1, 1);
zend_declare_typed_property(class_entry, property_databaseName_name, &property_databaseName_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zend_string_release(property_databaseName_name);
zval property_duration_default_value;
ZVAL_UNDEF(&property_duration_default_value);
zend_string *property_duration_name = zend_string_init("duration", sizeof("duration") - 1, 1);
zend_declare_typed_property(class_entry, property_duration_name, &property_duration_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_duration_name);
zval property_reply_default_value;
ZVAL_UNDEF(&property_reply_default_value);
zend_string *property_reply_name = zend_string_init("reply", sizeof("reply") - 1, 1);
zend_declare_typed_property(class_entry, property_reply_name, &property_reply_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_OBJECT));
zend_string_release(property_reply_name);
zval property_operationId_default_value;
ZVAL_UNDEF(&property_operationId_default_value);
zend_string *property_operationId_name = zend_string_init("operationId", sizeof("operationId") - 1, 1);
zend_declare_typed_property(class_entry, property_operationId_name, &property_operationId_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zend_string_release(property_operationId_name);
zval property_requestId_default_value;
ZVAL_UNDEF(&property_requestId_default_value);
zend_string *property_requestId_name = zend_string_init("requestId", sizeof("requestId") - 1, 1);
zend_declare_typed_property(class_entry, property_requestId_name, &property_requestId_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zend_string_release(property_requestId_name);
zval property_serviceId_default_value;
ZVAL_UNDEF(&property_serviceId_default_value);
zend_string *property_serviceId_name = zend_string_init("serviceId", sizeof("serviceId") - 1, 1);
zend_string *property_serviceId_class_MongoDB_BSON_ObjectId = zend_string_init("MongoDB\\BSON\\ObjectId", sizeof("MongoDB\\BSON\\ObjectId")-1, 1);
zend_declare_typed_property(class_entry, property_serviceId_name, &property_serviceId_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_serviceId_class_MongoDB_BSON_ObjectId, 0, MAY_BE_NULL));
zend_string_release(property_serviceId_name);
zval property_serverConnectionId_default_value;
ZVAL_UNDEF(&property_serverConnectionId_default_value);
zend_string *property_serverConnectionId_name = zend_string_init("serverConnectionId", sizeof("serverConnectionId") - 1, 1);
zend_declare_typed_property(class_entry, property_serverConnectionId_name, &property_serverConnectionId_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG|MAY_BE_NULL));
zend_string_release(property_serverConnectionId_name);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Monitoring/LogSubscriber.c 0000644 0001751 0001751 00000001615 15264101572 017212 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 "phongo.h"
#include "LogSubscriber_arginfo.h"
zend_class_entry* phongo_logsubscriber_ce;
void phongo_logsubscriber_init_ce(INIT_FUNC_ARGS)
{
phongo_logsubscriber_ce = register_class_MongoDB_Driver_Monitoring_LogSubscriber(phongo_subscriber_ce);
}
mongodb-2.5.5/src/MongoDB/Monitoring/LogSubscriber_arginfo.h 0000644 0001751 0001751 00000007364 15264101572 020733 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 0a17415d9367b2a9db97fdfb381375c07db7523b */
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[] = {
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("log", NULL, arginfo_class_MongoDB_Driver_Monitoring_LogSubscriber_log, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("log", NULL, arginfo_class_MongoDB_Driver_Monitoring_LogSubscriber_log, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
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.5.5/src/MongoDB/Monitoring/SDAMSubscriber.c 0000644 0001751 0001751 00000001566 15264101572 017222 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 "phongo.h"
#include "SDAMSubscriber_arginfo.h"
zend_class_entry* phongo_sdamsubscriber_ce;
void phongo_sdamsubscriber_init_ce(INIT_FUNC_ARGS)
{
phongo_sdamsubscriber_ce = register_class_MongoDB_Driver_Monitoring_SDAMSubscriber(phongo_subscriber_ce);
}
mongodb-2.5.5/src/MongoDB/Monitoring/SDAMSubscriber_arginfo.h 0000644 0001751 0001751 00000013707 15264101572 020734 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: b7d58477d2ac5f63bdfb04801eb6517aff5dd8df */
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[] = {
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("serverChanged", NULL, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverChanged, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("serverChanged", NULL, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverChanged, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("serverClosed", NULL, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverClosed, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("serverClosed", NULL, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverClosed, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("serverOpening", NULL, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverOpening, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("serverOpening", NULL, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverOpening, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("serverHeartbeatFailed", NULL, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverHeartbeatFailed, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("serverHeartbeatFailed", NULL, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverHeartbeatFailed, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("serverHeartbeatStarted", NULL, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverHeartbeatStarted, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("serverHeartbeatStarted", NULL, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverHeartbeatStarted, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("serverHeartbeatSucceeded", NULL, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverHeartbeatSucceeded, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("serverHeartbeatSucceeded", NULL, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_serverHeartbeatSucceeded, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("topologyChanged", NULL, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_topologyChanged, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("topologyChanged", NULL, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_topologyChanged, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("topologyClosed", NULL, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_topologyClosed, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("topologyClosed", NULL, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_topologyClosed, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("topologyOpening", NULL, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_topologyOpening, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("topologyOpening", NULL, arginfo_class_MongoDB_Driver_Monitoring_SDAMSubscriber_topologyOpening, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
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.5.5/src/MongoDB/Monitoring/ServerChangedEvent.c 0000644 0001751 0001751 00000012133 15264101572 020164 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 "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* phongo_serverchangedevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_ServerChangedEvent)
/* Returns this event's host */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerChangedEvent, getHost)
{
PHONGO_INTERN_FROM_THIS(serverchangedevent);
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRING(intern->host.host);
}
/* Returns this event's port */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerChangedEvent, getPort)
{
PHONGO_INTERN_FROM_THIS(serverchangedevent);
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_LONG(intern->host.port);
}
/* Returns this event's new description */
static PHP_METHOD(MongoDB_Driver_Monitoring_ServerChangedEvent, getNewDescription)
{
PHONGO_INTERN_FROM_THIS(serverchangedevent);
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)
{
PHONGO_INTERN_FROM_THIS(serverchangedevent);
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)
{
PHONGO_INTERN_FROM_THIS(serverchangedevent);
PHONGO_PARSE_PARAMETERS_NONE();
phongo_objectid_new(return_value, &intern->topology_id);
}
static void phongo_serverchangedevent_update_properties(phongo_serverchangedevent_t* intern)
{
zval topology_id, new_sd, old_sd;
zend_update_property_string(phongo_serverchangedevent_ce, &intern->std, ZEND_STRL("host"), intern->host.host);
zend_update_property_long(phongo_serverchangedevent_ce, &intern->std, ZEND_STRL("port"), intern->host.port);
if (phongo_objectid_new(&topology_id, &intern->topology_id)) {
zend_update_property(phongo_serverchangedevent_ce, &intern->std, ZEND_STRL("topologyId"), &topology_id);
zval_ptr_dtor(&topology_id);
}
phongo_serverdescription_init(&new_sd, intern->new_server_description);
zend_update_property(phongo_serverchangedevent_ce, &intern->std, ZEND_STRL("newDescription"), &new_sd);
zval_ptr_dtor(&new_sd);
phongo_serverdescription_init(&old_sd, intern->old_server_description);
zend_update_property(phongo_serverchangedevent_ce, &intern->std, ZEND_STRL("previousDescription"), &old_sd);
zval_ptr_dtor(&old_sd);
}
/* MongoDB\Driver\Monitoring\ServerChangedEvent object handlers */
static zend_object_handlers phongo_handler_serverchangedevent;
static void phongo_serverchangedevent_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_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* phongo_serverchangedevent_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(serverchangedevent, class_type);
intern->std.handlers = &phongo_handler_serverchangedevent;
return &intern->std;
}
void phongo_serverchangedevent_init_ce(INIT_FUNC_ARGS)
{
phongo_serverchangedevent_ce = register_class_MongoDB_Driver_Monitoring_ServerChangedEvent();
phongo_serverchangedevent_ce->create_object = phongo_serverchangedevent_create_object;
memcpy(&phongo_handler_serverchangedevent, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_serverchangedevent.free_obj = phongo_serverchangedevent_free_object;
phongo_handler_serverchangedevent.offset = offsetof(phongo_serverchangedevent_t, std);
}
void phongo_serverchangedevent_init(zval* return_value, const mongoc_apm_server_changed_t* event)
{
PHONGO_INTERN_INIT_EX(serverchangedevent, return_value);
memcpy(&intern->host, mongoc_apm_server_changed_get_host(event), sizeof(mongoc_host_list_t));
mongoc_apm_server_changed_get_topology_id(event, &intern->topology_id);
intern->new_server_description = mongoc_server_description_new_copy(mongoc_apm_server_changed_get_new_description(event));
intern->old_server_description = mongoc_server_description_new_copy(mongoc_apm_server_changed_get_previous_description(event));
phongo_serverchangedevent_update_properties(intern);
}
mongodb-2.5.5/src/MongoDB/Monitoring/ServerChangedEvent_arginfo.h 0000644 0001751 0001751 00000013434 15264101572 021703 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 978047b8c3560beeb59e80be3d9c132e3b9d2c93 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
zval property_host_default_value;
ZVAL_UNDEF(&property_host_default_value);
zend_declare_typed_property(class_entry, ZSTR_KNOWN(ZEND_STR_HOST), &property_host_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zval property_port_default_value;
ZVAL_UNDEF(&property_port_default_value);
zend_declare_typed_property(class_entry, ZSTR_KNOWN(ZEND_STR_PORT), &property_port_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zval property_topologyId_default_value;
ZVAL_UNDEF(&property_topologyId_default_value);
zend_string *property_topologyId_name = zend_string_init("topologyId", sizeof("topologyId") - 1, 1);
zend_string *property_topologyId_class_MongoDB_BSON_ObjectId = zend_string_init("MongoDB\\BSON\\ObjectId", sizeof("MongoDB\\BSON\\ObjectId")-1, 1);
zend_declare_typed_property(class_entry, property_topologyId_name, &property_topologyId_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_topologyId_class_MongoDB_BSON_ObjectId, 0, 0));
zend_string_release(property_topologyId_name);
zval property_newDescription_default_value;
ZVAL_UNDEF(&property_newDescription_default_value);
zend_string *property_newDescription_name = zend_string_init("newDescription", sizeof("newDescription") - 1, 1);
zend_string *property_newDescription_class_MongoDB_Driver_ServerDescription = zend_string_init("MongoDB\\Driver\\ServerDescription", sizeof("MongoDB\\Driver\\ServerDescription")-1, 1);
zend_declare_typed_property(class_entry, property_newDescription_name, &property_newDescription_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_newDescription_class_MongoDB_Driver_ServerDescription, 0, 0));
zend_string_release(property_newDescription_name);
zval property_previousDescription_default_value;
ZVAL_UNDEF(&property_previousDescription_default_value);
zend_string *property_previousDescription_name = zend_string_init("previousDescription", sizeof("previousDescription") - 1, 1);
zend_string *property_previousDescription_class_MongoDB_Driver_ServerDescription = zend_string_init("MongoDB\\Driver\\ServerDescription", sizeof("MongoDB\\Driver\\ServerDescription")-1, 1);
zend_declare_typed_property(class_entry, property_previousDescription_name, &property_previousDescription_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_previousDescription_class_MongoDB_Driver_ServerDescription, 0, 0));
zend_string_release(property_previousDescription_name);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Monitoring/ServerClosedEvent.c 0000644 0001751 0001751 00000004356 15264101572 020054 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 "phongo.h"
#include "phongo_error.h"
#include "BSON/ObjectId.h"
#include "ServerClosedEvent_arginfo.h"
zend_class_entry* phongo_serverclosedevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_ServerClosedEvent)
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_ServerClosedEvent, getHost, serverclosedevent, "host")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_ServerClosedEvent, getPort, serverclosedevent, "port")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_ServerClosedEvent, getTopologyId, serverclosedevent, "topologyId")
static void phongo_serverclosedevent_update_properties(zend_object* object, const mongoc_apm_server_closed_t* event)
{
zval ztopology_id;
bson_oid_t topology_id;
zend_update_property_string(phongo_serverclosedevent_ce, object, ZEND_STRL("host"), mongoc_apm_server_closed_get_host(event)->host);
zend_update_property_long(phongo_serverclosedevent_ce, object, ZEND_STRL("port"), mongoc_apm_server_closed_get_host(event)->port);
mongoc_apm_server_closed_get_topology_id(event, &topology_id);
if (phongo_objectid_new(&ztopology_id, &topology_id)) {
zend_update_property(phongo_serverclosedevent_ce, object, ZEND_STRL("topologyId"), &ztopology_id);
zval_ptr_dtor(&ztopology_id);
}
}
void phongo_serverclosedevent_init_ce(INIT_FUNC_ARGS)
{
phongo_serverclosedevent_ce = register_class_MongoDB_Driver_Monitoring_ServerClosedEvent();
}
void phongo_serverclosedevent_init(zval* return_value, const mongoc_apm_server_closed_t* event)
{
PHONGO_OBJECT_INIT_EX(serverclosedevent, return_value);
phongo_serverclosedevent_update_properties(object, event);
}
mongodb-2.5.5/src/MongoDB/Monitoring/ServerClosedEvent_arginfo.h 0000644 0001751 0001751 00000006704 15264101572 021565 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 69a93e4cabab41afbe70c84632dfc5c8b519b837 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
zval property_host_default_value;
ZVAL_UNDEF(&property_host_default_value);
zend_declare_typed_property(class_entry, ZSTR_KNOWN(ZEND_STR_HOST), &property_host_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zval property_port_default_value;
ZVAL_UNDEF(&property_port_default_value);
zend_declare_typed_property(class_entry, ZSTR_KNOWN(ZEND_STR_PORT), &property_port_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zval property_topologyId_default_value;
ZVAL_UNDEF(&property_topologyId_default_value);
zend_string *property_topologyId_name = zend_string_init("topologyId", sizeof("topologyId") - 1, 1);
zend_string *property_topologyId_class_MongoDB_BSON_ObjectId = zend_string_init("MongoDB\\BSON\\ObjectId", sizeof("MongoDB\\BSON\\ObjectId")-1, 1);
zend_declare_typed_property(class_entry, property_topologyId_name, &property_topologyId_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_topologyId_class_MongoDB_BSON_ObjectId, 0, 0));
zend_string_release(property_topologyId_name);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Monitoring/ServerHeartbeatFailedEvent.c 0000644 0001751 0001751 00000006613 15264101572 021645 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
#include "phongo.h"
#include "phongo_error.h"
#include "ServerHeartbeatFailedEvent_arginfo.h"
zend_class_entry* phongo_serverheartbeatfailedevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent)
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent, getDurationMicros, serverheartbeatfailedevent, "duration")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent, getError, serverheartbeatfailedevent, "error")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent, getHost, serverheartbeatfailedevent, "host")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent, getPort, serverheartbeatfailedevent, "port")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent, isAwaited, serverheartbeatfailedevent, "awaited")
static void phongo_serverheartbeatfailedevent_update_properties(zend_object* object, const mongoc_apm_server_heartbeat_failed_t* event)
{
zend_update_property_string(phongo_serverheartbeatfailedevent_ce, object, ZEND_STRL("host"), mongoc_apm_server_heartbeat_failed_get_host(event)->host);
zend_update_property_long(phongo_serverheartbeatfailedevent_ce, object, ZEND_STRL("port"), mongoc_apm_server_heartbeat_failed_get_host(event)->port);
zend_update_property_bool(phongo_serverheartbeatfailedevent_ce, object, ZEND_STRL("awaited"), mongoc_apm_server_heartbeat_failed_get_awaited(event));
zend_update_property_long(phongo_serverheartbeatfailedevent_ce, object, ZEND_STRL("duration"), mongoc_apm_server_heartbeat_failed_get_duration(event));
{
bson_error_t tmp_error = { 0 };
zval zerror;
/* We need to process and convert the error right here, otherwise
* debug_info will turn into a recursive loop, and with the wrong trace
* locations */
mongoc_apm_server_heartbeat_failed_get_error(event, &tmp_error);
object_init_ex(&zerror, phongo_exception_from_mongoc_domain(tmp_error.domain, tmp_error.code));
zend_update_property_string(zend_ce_exception, Z_OBJ_P(&zerror), ZEND_STRL("message"), tmp_error.message);
zend_update_property_long(zend_ce_exception, Z_OBJ_P(&zerror), ZEND_STRL("code"), tmp_error.code);
zend_update_property(phongo_serverheartbeatfailedevent_ce, object, ZEND_STRL("error"), &zerror);
zval_ptr_dtor(&zerror);
}
}
void phongo_serverheartbeatfailedevent_init_ce(INIT_FUNC_ARGS)
{
phongo_serverheartbeatfailedevent_ce = register_class_MongoDB_Driver_Monitoring_ServerHeartbeatFailedEvent();
}
void phongo_serverheartbeatfailedevent_init(zval* return_value, const mongoc_apm_server_heartbeat_failed_t* event)
{
PHONGO_OBJECT_INIT_EX(serverheartbeatfailedevent, return_value);
phongo_serverheartbeatfailedevent_update_properties(object, event);
}
mongodb-2.5.5/src/MongoDB/Monitoring/ServerHeartbeatFailedEvent_arginfo.h 0000644 0001751 0001751 00000012255 15264101572 023356 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 2d55d85a35a4a21004611412546aeab7ffdbad93 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
zval property_host_default_value;
ZVAL_UNDEF(&property_host_default_value);
zend_declare_typed_property(class_entry, ZSTR_KNOWN(ZEND_STR_HOST), &property_host_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zval property_port_default_value;
ZVAL_UNDEF(&property_port_default_value);
zend_declare_typed_property(class_entry, ZSTR_KNOWN(ZEND_STR_PORT), &property_port_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zval property_awaited_default_value;
ZVAL_UNDEF(&property_awaited_default_value);
zend_string *property_awaited_name = zend_string_init("awaited", sizeof("awaited") - 1, 1);
zend_declare_typed_property(class_entry, property_awaited_name, &property_awaited_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL));
zend_string_release(property_awaited_name);
zval property_duration_default_value;
ZVAL_UNDEF(&property_duration_default_value);
zend_string *property_duration_name = zend_string_init("duration", sizeof("duration") - 1, 1);
zend_declare_typed_property(class_entry, property_duration_name, &property_duration_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_duration_name);
zval property_error_default_value;
ZVAL_UNDEF(&property_error_default_value);
zend_string *property_error_name = zend_string_init("error", sizeof("error") - 1, 1);
zend_string *property_error_class_Exception = zend_string_init("Exception", sizeof("Exception")-1, 1);
zend_declare_typed_property(class_entry, property_error_name, &property_error_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_error_class_Exception, 0, 0));
zend_string_release(property_error_name);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Monitoring/ServerHeartbeatStartedEvent.c 0000644 0001751 0001751 00000004415 15264101572 022065 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 "phongo.h"
#include "phongo_error.h"
#include "ServerHeartbeatStartedEvent_arginfo.h"
zend_class_entry* phongo_serverheartbeatstartedevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent)
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent, getHost, serverheartbeatstartedevent, "host")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent, getPort, serverheartbeatstartedevent, "port")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent, isAwaited, serverheartbeatstartedevent, "awaited")
static void phongo_serverheartbeatstartedevent_update_properties(zend_object* object, const mongoc_apm_server_heartbeat_started_t* event)
{
zend_update_property_string(phongo_serverheartbeatstartedevent_ce, object, ZEND_STRL("host"), mongoc_apm_server_heartbeat_started_get_host(event)->host);
zend_update_property_long(phongo_serverheartbeatstartedevent_ce, object, ZEND_STRL("port"), mongoc_apm_server_heartbeat_started_get_host(event)->port);
zend_update_property_bool(phongo_serverheartbeatstartedevent_ce, object, ZEND_STRL("awaited"), mongoc_apm_server_heartbeat_started_get_awaited(event));
}
void phongo_serverheartbeatstartedevent_init_ce(INIT_FUNC_ARGS)
{
phongo_serverheartbeatstartedevent_ce = register_class_MongoDB_Driver_Monitoring_ServerHeartbeatStartedEvent();
}
void phongo_serverheartbeatstartedevent_init(zval* return_value, const mongoc_apm_server_heartbeat_started_t* event)
{
PHONGO_OBJECT_INIT_EX(serverheartbeatstartedevent, return_value);
phongo_serverheartbeatstartedevent_update_properties(object, event);
}
mongodb-2.5.5/src/MongoDB/Monitoring/ServerHeartbeatStartedEvent_arginfo.h 0000644 0001751 0001751 00000006626 15264101572 023605 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: b12f4bd39fb4ec5dcb13e603b9fbfba629d32094 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
zval property_host_default_value;
ZVAL_UNDEF(&property_host_default_value);
zend_declare_typed_property(class_entry, ZSTR_KNOWN(ZEND_STR_HOST), &property_host_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zval property_port_default_value;
ZVAL_UNDEF(&property_port_default_value);
zend_declare_typed_property(class_entry, ZSTR_KNOWN(ZEND_STR_PORT), &property_port_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zval property_awaited_default_value;
ZVAL_UNDEF(&property_awaited_default_value);
zend_string *property_awaited_name = zend_string_init("awaited", sizeof("awaited") - 1, 1);
zend_declare_typed_property(class_entry, property_awaited_name, &property_awaited_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL));
zend_string_release(property_awaited_name);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Monitoring/ServerHeartbeatSucceededEvent.c 0000644 0001751 0001751 00000006073 15264101572 022345 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 "phongo.h"
#include "phongo_error.h"
#include "ServerHeartbeatSucceededEvent_arginfo.h"
zend_class_entry* phongo_serverheartbeatsucceededevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent)
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent, getDurationMicros, serverheartbeatsucceededevent, "duration")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent, getHost, serverheartbeatsucceededevent, "host")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent, getPort, serverheartbeatsucceededevent, "port")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent, getReply, serverheartbeatsucceededevent, "reply")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent, isAwaited, serverheartbeatsucceededevent, "awaited")
static void phongo_serverheartbeatsucceededevent_update_properties(zend_object* object, const mongoc_apm_server_heartbeat_succeeded_t* event)
{
phongo_bson_state reply_state;
PHONGO_BSON_INIT_NO_ODM_STATE(reply_state);
zend_update_property_string(phongo_serverheartbeatsucceededevent_ce, object, ZEND_STRL("host"), mongoc_apm_server_heartbeat_succeeded_get_host(event)->host);
zend_update_property_long(phongo_serverheartbeatsucceededevent_ce, object, ZEND_STRL("port"), mongoc_apm_server_heartbeat_succeeded_get_host(event)->port);
zend_update_property_bool(phongo_serverheartbeatsucceededevent_ce, object, ZEND_STRL("awaited"), mongoc_apm_server_heartbeat_succeeded_get_awaited(event));
zend_update_property_long(phongo_serverheartbeatsucceededevent_ce, object, ZEND_STRL("duration"), mongoc_apm_server_heartbeat_succeeded_get_duration(event));
if (phongo_bson_to_zval_ex(mongoc_apm_server_heartbeat_succeeded_get_reply(event), &reply_state)) {
zend_update_property(phongo_serverheartbeatsucceededevent_ce, object, ZEND_STRL("reply"), &reply_state.zchild);
}
zval_ptr_dtor(&reply_state.zchild);
}
void phongo_serverheartbeatsucceededevent_init_ce(INIT_FUNC_ARGS)
{
phongo_serverheartbeatsucceededevent_ce = register_class_MongoDB_Driver_Monitoring_ServerHeartbeatSucceededEvent();
}
void phongo_serverheartbeatsucceededevent_init(zval* return_value, const mongoc_apm_server_heartbeat_succeeded_t* event)
{
PHONGO_OBJECT_INIT_EX(serverheartbeatsucceededevent, return_value);
phongo_serverheartbeatsucceededevent_update_properties(object, event);
}
mongodb-2.5.5/src/MongoDB/Monitoring/ServerHeartbeatSucceededEvent_arginfo.h 0000644 0001751 0001751 00000012205 15264101572 024051 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 7fccc6765f058925077bb698c8a79ddb8355b852 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
zval property_host_default_value;
ZVAL_UNDEF(&property_host_default_value);
zend_declare_typed_property(class_entry, ZSTR_KNOWN(ZEND_STR_HOST), &property_host_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zval property_port_default_value;
ZVAL_UNDEF(&property_port_default_value);
zend_declare_typed_property(class_entry, ZSTR_KNOWN(ZEND_STR_PORT), &property_port_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zval property_awaited_default_value;
ZVAL_UNDEF(&property_awaited_default_value);
zend_string *property_awaited_name = zend_string_init("awaited", sizeof("awaited") - 1, 1);
zend_declare_typed_property(class_entry, property_awaited_name, &property_awaited_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL));
zend_string_release(property_awaited_name);
zval property_duration_default_value;
ZVAL_UNDEF(&property_duration_default_value);
zend_string *property_duration_name = zend_string_init("duration", sizeof("duration") - 1, 1);
zend_declare_typed_property(class_entry, property_duration_name, &property_duration_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_duration_name);
zval property_reply_default_value;
ZVAL_UNDEF(&property_reply_default_value);
zend_string *property_reply_name = zend_string_init("reply", sizeof("reply") - 1, 1);
zend_declare_typed_property(class_entry, property_reply_name, &property_reply_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_OBJECT));
zend_string_release(property_reply_name);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Monitoring/ServerOpeningEvent.c 0000644 0001751 0001751 00000004406 15264101572 020236 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 "phongo.h"
#include "phongo_error.h"
#include "BSON/ObjectId.h"
#include "ServerOpeningEvent_arginfo.h"
zend_class_entry* phongo_serveropeningevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_ServerOpeningEvent)
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_ServerOpeningEvent, getHost, serveropeningevent, "host")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_ServerOpeningEvent, getPort, serveropeningevent, "port")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_ServerOpeningEvent, getTopologyId, serveropeningevent, "topologyId")
static void phongo_serveropeningevent_update_properties(zend_object* object, const mongoc_apm_server_opening_t* event)
{
zval ztopology_id;
bson_oid_t topology_id;
zend_update_property_string(phongo_serveropeningevent_ce, object, ZEND_STRL("host"), mongoc_apm_server_opening_get_host(event)->host);
zend_update_property_long(phongo_serveropeningevent_ce, object, ZEND_STRL("port"), mongoc_apm_server_opening_get_host(event)->port);
mongoc_apm_server_opening_get_topology_id(event, &topology_id);
if (phongo_objectid_new(&ztopology_id, &topology_id)) {
zend_update_property(phongo_serveropeningevent_ce, object, ZEND_STRL("topologyId"), &ztopology_id);
zval_ptr_dtor(&ztopology_id);
}
}
void phongo_serveropeningevent_init_ce(INIT_FUNC_ARGS)
{
phongo_serveropeningevent_ce = register_class_MongoDB_Driver_Monitoring_ServerOpeningEvent();
}
void phongo_serveropeningevent_init(zval* return_value, const mongoc_apm_server_opening_t* event)
{
PHONGO_OBJECT_INIT_EX(serveropeningevent, return_value);
phongo_serveropeningevent_update_properties(object, event);
}
mongodb-2.5.5/src/MongoDB/Monitoring/ServerOpeningEvent_arginfo.h 0000644 0001751 0001751 00000006730 15264101572 021752 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: e05cac5a6840d453e7c00175763fc8d1b659054f */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
zval property_host_default_value;
ZVAL_UNDEF(&property_host_default_value);
zend_declare_typed_property(class_entry, ZSTR_KNOWN(ZEND_STR_HOST), &property_host_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zval property_port_default_value;
ZVAL_UNDEF(&property_port_default_value);
zend_declare_typed_property(class_entry, ZSTR_KNOWN(ZEND_STR_PORT), &property_port_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zval property_topologyId_default_value;
ZVAL_UNDEF(&property_topologyId_default_value);
zend_string *property_topologyId_name = zend_string_init("topologyId", sizeof("topologyId") - 1, 1);
zend_string *property_topologyId_class_MongoDB_BSON_ObjectId = zend_string_init("MongoDB\\BSON\\ObjectId", sizeof("MongoDB\\BSON\\ObjectId")-1, 1);
zend_declare_typed_property(class_entry, property_topologyId_name, &property_topologyId_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_topologyId_class_MongoDB_BSON_ObjectId, 0, 0));
zend_string_release(property_topologyId_name);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Monitoring/Subscriber.c 0000644 0001751 0001751 00000001516 15264101572 016550 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 "phongo.h"
#include "Subscriber_arginfo.h"
zend_class_entry* phongo_subscriber_ce;
void phongo_subscriber_init_ce(INIT_FUNC_ARGS)
{
phongo_subscriber_ce = register_class_MongoDB_Driver_Monitoring_Subscriber();
}
mongodb-2.5.5/src/MongoDB/Monitoring/Subscriber_arginfo.h 0000644 0001751 0001751 00000000616 15264101572 020262 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: a86f5de0f86037e928a37f1b6c38593ce005b202 */
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", NULL);
class_entry = zend_register_internal_interface(&ce);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Monitoring/TopologyChangedEvent.c 0000644 0001751 0001751 00000010661 15264101572 020536 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 "phongo.h"
#include "phongo_error.h"
#include "BSON/ObjectId.h"
#include "MongoDB/TopologyDescription.h"
#include "TopologyChangedEvent_arginfo.h"
zend_class_entry* phongo_topologychangedevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_TopologyChangedEvent)
/* Returns this event's new description */
static PHP_METHOD(MongoDB_Driver_Monitoring_TopologyChangedEvent, getNewDescription)
{
PHONGO_INTERN_FROM_THIS(topologychangedevent);
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)
{
PHONGO_INTERN_FROM_THIS(topologychangedevent);
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)
{
PHONGO_INTERN_FROM_THIS(topologychangedevent);
PHONGO_PARSE_PARAMETERS_NONE();
phongo_objectid_new(return_value, &intern->topology_id);
}
static void phongo_topologychangedevent_update_properties(phongo_topologychangedevent_t* intern)
{
zval topology_id, new_td, old_td;
if (phongo_objectid_new(&topology_id, &intern->topology_id)) {
zend_update_property(phongo_topologychangedevent_ce, &intern->std, ZEND_STRL("topologyId"), &topology_id);
zval_ptr_dtor(&topology_id);
}
phongo_topologydescription_init(&new_td, intern->new_topology_description);
zend_update_property(phongo_topologychangedevent_ce, &intern->std, ZEND_STRL("newDescription"), &new_td);
zval_ptr_dtor(&new_td);
phongo_topologydescription_init(&old_td, intern->old_topology_description);
zend_update_property(phongo_topologychangedevent_ce, &intern->std, ZEND_STRL("previousDescription"), &old_td);
zval_ptr_dtor(&old_td);
}
/* MongoDB\Driver\Monitoring\TopologyChangedEvent object handlers */
static zend_object_handlers phongo_handler_topologychangedevent;
static void phongo_topologychangedevent_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_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* phongo_topologychangedevent_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(topologychangedevent, class_type);
intern->std.handlers = &phongo_handler_topologychangedevent;
return &intern->std;
}
void phongo_topologychangedevent_init_ce(INIT_FUNC_ARGS)
{
phongo_topologychangedevent_ce = register_class_MongoDB_Driver_Monitoring_TopologyChangedEvent();
phongo_topologychangedevent_ce->create_object = phongo_topologychangedevent_create_object;
memcpy(&phongo_handler_topologychangedevent, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_topologychangedevent.free_obj = phongo_topologychangedevent_free_object;
phongo_handler_topologychangedevent.offset = offsetof(phongo_topologychangedevent_t, std);
}
void phongo_topologychangedevent_init(zval* return_value, const mongoc_apm_topology_changed_t* event)
{
PHONGO_INTERN_INIT_EX(topologychangedevent, return_value);
mongoc_apm_topology_changed_get_topology_id(event, &intern->topology_id);
intern->new_topology_description = mongoc_topology_description_new_copy(mongoc_apm_topology_changed_get_new_description(event));
intern->old_topology_description = mongoc_topology_description_new_copy(mongoc_apm_topology_changed_get_previous_description(event));
phongo_topologychangedevent_update_properties(intern);
}
mongodb-2.5.5/src/MongoDB/Monitoring/TopologyChangedEvent_arginfo.h 0000644 0001751 0001751 00000011074 15264101572 022247 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: a9523c4af372004f40da12f771319b381726336e */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
zval property_topologyId_default_value;
ZVAL_UNDEF(&property_topologyId_default_value);
zend_string *property_topologyId_name = zend_string_init("topologyId", sizeof("topologyId") - 1, 1);
zend_string *property_topologyId_class_MongoDB_BSON_ObjectId = zend_string_init("MongoDB\\BSON\\ObjectId", sizeof("MongoDB\\BSON\\ObjectId")-1, 1);
zend_declare_typed_property(class_entry, property_topologyId_name, &property_topologyId_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_topologyId_class_MongoDB_BSON_ObjectId, 0, 0));
zend_string_release(property_topologyId_name);
zval property_newDescription_default_value;
ZVAL_UNDEF(&property_newDescription_default_value);
zend_string *property_newDescription_name = zend_string_init("newDescription", sizeof("newDescription") - 1, 1);
zend_string *property_newDescription_class_MongoDB_Driver_TopologyDescription = zend_string_init("MongoDB\\Driver\\TopologyDescription", sizeof("MongoDB\\Driver\\TopologyDescription")-1, 1);
zend_declare_typed_property(class_entry, property_newDescription_name, &property_newDescription_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_newDescription_class_MongoDB_Driver_TopologyDescription, 0, 0));
zend_string_release(property_newDescription_name);
zval property_previousDescription_default_value;
ZVAL_UNDEF(&property_previousDescription_default_value);
zend_string *property_previousDescription_name = zend_string_init("previousDescription", sizeof("previousDescription") - 1, 1);
zend_string *property_previousDescription_class_MongoDB_Driver_TopologyDescription = zend_string_init("MongoDB\\Driver\\TopologyDescription", sizeof("MongoDB\\Driver\\TopologyDescription")-1, 1);
zend_declare_typed_property(class_entry, property_previousDescription_name, &property_previousDescription_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_previousDescription_class_MongoDB_Driver_TopologyDescription, 0, 0));
zend_string_release(property_previousDescription_name);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Monitoring/TopologyClosedEvent.c 0000644 0001751 0001751 00000003463 15264101572 020420 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 "phongo.h"
#include "phongo_error.h"
#include "BSON/ObjectId.h"
#include "TopologyClosedEvent_arginfo.h"
zend_class_entry* phongo_topologyclosedevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_TopologyClosedEvent)
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_TopologyClosedEvent, getTopologyId, topologyclosedevent, "topologyId")
static void phongo_topologyclosedevent_update_properties(zend_object* object, const mongoc_apm_topology_closed_t* event)
{
zval ztopology_id;
bson_oid_t topology_id;
mongoc_apm_topology_closed_get_topology_id(event, &topology_id);
if (phongo_objectid_new(&ztopology_id, &topology_id)) {
zend_update_property(phongo_topologyclosedevent_ce, object, ZEND_STRL("topologyId"), &ztopology_id);
zval_ptr_dtor(&ztopology_id);
}
}
void phongo_topologyclosedevent_init_ce(INIT_FUNC_ARGS)
{
phongo_topologyclosedevent_ce = register_class_MongoDB_Driver_Monitoring_TopologyClosedEvent();
}
void phongo_topologyclosedevent_init(zval* return_value, const mongoc_apm_topology_closed_t* event)
{
PHONGO_OBJECT_INIT_EX(topologyclosedevent, return_value);
phongo_topologyclosedevent_update_properties(object, event);
}
mongodb-2.5.5/src/MongoDB/Monitoring/TopologyClosedEvent_arginfo.h 0000644 0001751 0001751 00000004310 15264101572 022122 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 3ab90b4e8bbb8fe5d0b2248e40b102ab029ac6f1 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
zval property_topologyId_default_value;
ZVAL_UNDEF(&property_topologyId_default_value);
zend_string *property_topologyId_name = zend_string_init("topologyId", sizeof("topologyId") - 1, 1);
zend_string *property_topologyId_class_MongoDB_BSON_ObjectId = zend_string_init("MongoDB\\BSON\\ObjectId", sizeof("MongoDB\\BSON\\ObjectId")-1, 1);
zend_declare_typed_property(class_entry, property_topologyId_name, &property_topologyId_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_topologyId_class_MongoDB_BSON_ObjectId, 0, 0));
zend_string_release(property_topologyId_name);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Monitoring/TopologyOpeningEvent.c 0000644 0001751 0001751 00000003503 15264101572 020601 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 "phongo.h"
#include "phongo_error.h"
#include "BSON/ObjectId.h"
#include "TopologyOpeningEvent_arginfo.h"
zend_class_entry* phongo_topologyopeningevent_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Monitoring_TopologyOpeningEvent)
PHONGO_PROPERTY_GETTER(MongoDB_Driver_Monitoring_TopologyOpeningEvent, getTopologyId, topologyopeningevent, "topologyId")
static void phongo_topologyopeningevent_update_properties(zend_object* object, const mongoc_apm_topology_opening_t* event)
{
zval ztopology_id;
bson_oid_t topology_id;
mongoc_apm_topology_opening_get_topology_id(event, &topology_id);
if (phongo_objectid_new(&ztopology_id, &topology_id)) {
zend_update_property(phongo_topologyopeningevent_ce, object, ZEND_STRL("topologyId"), &ztopology_id);
zval_ptr_dtor(&ztopology_id);
}
}
void phongo_topologyopeningevent_init_ce(INIT_FUNC_ARGS)
{
phongo_topologyopeningevent_ce = register_class_MongoDB_Driver_Monitoring_TopologyOpeningEvent();
}
void phongo_topologyopeningevent_init(zval* return_value, const mongoc_apm_topology_opening_t* event)
{
PHONGO_OBJECT_INIT_EX(topologyopeningevent, return_value);
phongo_topologyopeningevent_update_properties(object, event);
}
mongodb-2.5.5/src/MongoDB/Monitoring/TopologyOpeningEvent_arginfo.h 0000644 0001751 0001751 00000004324 15264101572 022315 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 10d60d037a0fa78818daacad26b91791a6c54784 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
zval property_topologyId_default_value;
ZVAL_UNDEF(&property_topologyId_default_value);
zend_string *property_topologyId_name = zend_string_init("topologyId", sizeof("topologyId") - 1, 1);
zend_string *property_topologyId_class_MongoDB_BSON_ObjectId = zend_string_init("MongoDB\\BSON\\ObjectId", sizeof("MongoDB\\BSON\\ObjectId")-1, 1);
zend_declare_typed_property(class_entry, property_topologyId_name, &property_topologyId_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_topologyId_class_MongoDB_BSON_ObjectId, 0, 0));
zend_string_release(property_topologyId_name);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Monitoring/functions.c 0000644 0001751 0001751 00000006033 15264101572 016454 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 "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), phongo_commandsubscriber_ce) || \
instanceof_function(Z_OBJCE_P(zv), phongo_sdamsubscriber_ce)
#define IS_LOG_SUBSCRIBER(zv) instanceof_function(Z_OBJCE_P(zv), 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, 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, 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.5.5/src/MongoDB/BulkWrite.c 0000644 0001751 0001751 00000045117 15264101572 014235 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 "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* phongo_bulkwrite_ce;
/* Extracts the "_id" field of a BSON document into a return value. */
static void phongo_bulkwrite_extract_id(bson_t* doc, zval** return_value)
{
zval* id = NULL;
phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
state.map.root.type = PHONGO_TYPEMAP_NATIVE_ARRAY;
if (!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 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 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 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 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
phongo_zval_to_bson(value, PHONGO_BSON_ALLOW_ROOT_ARRAY, &b, NULL);
if (EG(exception)) {
bson_destroy(&b);
return false;
}
if (!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 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;
}
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 (!phongo_bulkwrite_opts_append_array(boptions, (opt), zoptions)) { \
return false; \
} \
}
#define PHONGO_BULKWRITE_OPT_DOCUMENT(opt) \
if (zoptions && php_array_existsc(zoptions, (opt))) { \
if (!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 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 (Z_STRLEN_P(value) > PHONGO_BSON_MAX_LENGTH) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"hint\" option to be <= %" PRId32 " bytes, %zu given", (int32_t) PHONGO_BSON_MAX_LENGTH, Z_STRLEN_P(value));
return false;
}
if (!bson_append_utf8(boptions, ZEND_STRL("hint"), 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 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 (!phongo_bulkwrite_opt_hint(boptions, zoptions)) {
return false;
}
return true;
}
/* Applies options (including defaults) for a delete operation. */
static bool 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 (!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)
{
PHONGO_INTERN_FROM_THIS(bulkwrite);
zval* options = NULL;
zend_bool ordered = 1;
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();
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)
{
PHONGO_INTERN_FROM_THIS(bulkwrite);
zval* zdocument;
bson_t bdocument = BSON_INITIALIZER, boptions = BSON_INITIALIZER;
bson_t* bson_out = NULL;
bson_error_t error = { 0 };
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY_OR_OBJECT(zdocument)
PHONGO_PARSE_PARAMETERS_END();
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, "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++;
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)
{
PHONGO_INTERN_FROM_THIS(bulkwrite);
zval * zquery, *zupdate, *zoptions = NULL;
bson_t bquery = BSON_INITIALIZER, bupdate = BSON_INITIALIZER, boptions = BSON_INITIALIZER;
bson_error_t error = { 0 };
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();
phongo_zval_to_bson(zquery, PHONGO_BSON_NONE, &bquery, NULL);
if (EG(exception)) {
goto cleanup;
}
// Explicitly allow MongoDB\BSON\PackedArray for update pipelines
phongo_zval_to_bson(zupdate, PHONGO_BSON_ALLOW_ROOT_ARRAY, &bupdate, NULL);
if (EG(exception)) {
goto cleanup;
}
if (!phongo_bulkwrite_update_apply_options(&boptions, zoptions)) {
goto cleanup;
}
if (phongo_bulkwrite_update_has_operators(&bupdate) || 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)
{
PHONGO_INTERN_FROM_THIS(bulkwrite);
zval * zquery, *zoptions = NULL;
bson_t bquery = BSON_INITIALIZER, boptions = BSON_INITIALIZER;
bson_error_t error = { 0 };
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();
phongo_zval_to_bson(zquery, PHONGO_BSON_NONE, &bquery, NULL);
if (EG(exception)) {
goto cleanup;
}
if (!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)
{
PHONGO_INTERN_FROM_THIS(bulkwrite);
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_LONG(intern->num_ops);
}
/* MongoDB\Driver\BulkWrite object handlers */
static zend_object_handlers phongo_handler_bulkwrite;
static void phongo_bulkwrite_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_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* phongo_bulkwrite_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(bulkwrite, class_type);
intern->std.handlers = &phongo_handler_bulkwrite;
return &intern->std;
}
static HashTable* phongo_bulkwrite_get_debug_info(zend_object* object, int* is_temp)
{
PHONGO_INTERN_FROM_Z_OBJ(bulkwrite, object);
zval retval = ZVAL_STATIC_INIT;
*is_temp = 1;
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 (!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;
phongo_writeconcern_init(&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 phongo_bulkwrite_init_ce(INIT_FUNC_ARGS)
{
phongo_bulkwrite_ce = register_class_MongoDB_Driver_BulkWrite(zend_ce_countable);
phongo_bulkwrite_ce->create_object = phongo_bulkwrite_create_object;
memcpy(&phongo_handler_bulkwrite, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_bulkwrite.get_debug_info = phongo_bulkwrite_get_debug_info;
phongo_handler_bulkwrite.free_obj = phongo_bulkwrite_free_object;
phongo_handler_bulkwrite.offset = offsetof(phongo_bulkwrite_t, std);
}
mongodb-2.5.5/src/MongoDB/BulkWriteCommand.c 0000644 0001751 0001751 00000055075 15264101572 015540 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 "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* 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(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;
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 (!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)
{
PHONGO_INTERN_FROM_THIS(bulkwritecommand);
zval* zoptions = NULL;
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();
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)
{
PHONGO_INTERN_FROM_THIS(bulkwritecommand);
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\"", 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;
}
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
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)
{
PHONGO_INTERN_FROM_THIS(bulkwritecommand);
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 };
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;
}
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)
{
PHONGO_INTERN_FROM_THIS(bulkwritecommand);
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 };
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;
}
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)
{
PHONGO_INTERN_FROM_THIS(bulkwritecommand);
char* ns;
size_t ns_len;
zval* zdocument;
bson_t bdocument = BSON_INITIALIZER;
bson_t* bson_out = NULL;
bson_error_t error = { 0 };
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;
}
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, "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)
{
PHONGO_INTERN_FROM_THIS(bulkwritecommand);
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 };
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;
}
phongo_zval_to_bson(zfilter, PHONGO_BSON_NONE, &bfilter, NULL);
if (EG(exception)) {
goto cleanup;
}
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)
{
PHONGO_INTERN_FROM_THIS(bulkwritecommand);
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 };
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;
}
phongo_zval_to_bson(zfilter, PHONGO_BSON_NONE, &bfilter, NULL);
if (EG(exception)) {
goto cleanup;
}
// Explicitly allow MongoDB\BSON\PackedArray for update pipelines
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)
{
PHONGO_INTERN_FROM_THIS(bulkwritecommand);
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 };
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;
}
phongo_zval_to_bson(zfilter, PHONGO_BSON_NONE, &bfilter, NULL);
if (EG(exception)) {
goto cleanup;
}
// Explicitly allow MongoDB\BSON\PackedArray for update pipelines
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 phongo_handler_bulkwritecommand;
static void phongo_bulkwritecommand_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_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* phongo_bulkwritecommand_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(bulkwritecommand, class_type);
intern->std.handlers = &phongo_handler_bulkwritecommand;
return &intern->std;
}
static HashTable* phongo_bulkwritecommand_get_debug_info(zend_object* object, int* is_temp)
{
PHONGO_INTERN_FROM_Z_OBJ(bulkwritecommand, object);
zval retval = ZVAL_STATIC_INIT;
*is_temp = 1;
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 (!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 phongo_bulkwritecommand_init_ce(INIT_FUNC_ARGS)
{
phongo_bulkwritecommand_ce = register_class_MongoDB_Driver_BulkWriteCommand(zend_ce_countable);
phongo_bulkwritecommand_ce->create_object = phongo_bulkwritecommand_create_object;
memcpy(&phongo_handler_bulkwritecommand, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_bulkwritecommand.get_debug_info = phongo_bulkwritecommand_get_debug_info;
phongo_handler_bulkwritecommand.free_obj = phongo_bulkwritecommand_free_object;
phongo_handler_bulkwritecommand.offset = offsetof(phongo_bulkwritecommand_t, std);
}
mongodb-2.5.5/src/MongoDB/BulkWriteCommand.h 0000644 0001751 0001751 00000001527 15264101572 015536 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(phongo_bulkwritecommand_t* intern);
#endif /* PHONGO_BULKWRITECOMMAND_H */
mongodb-2.5.5/src/MongoDB/BulkWriteCommandResult.c 0000644 0001751 0001751 00000020702 15264101572 016724 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 "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* phongo_bulkwritecommandresult_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_BulkWriteCommandResult)
/* Returns the number of documents that were inserted */
static PHP_METHOD(MongoDB_Driver_BulkWriteCommandResult, getInsertedCount)
{
PHONGO_INTERN_FROM_THIS(bulkwritecommandresult);
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)
{
PHONGO_INTERN_FROM_THIS(bulkwritecommandresult);
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)
{
PHONGO_INTERN_FROM_THIS(bulkwritecommandresult);
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)
{
PHONGO_INTERN_FROM_THIS(bulkwritecommandresult);
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)
{
PHONGO_INTERN_FROM_THIS(bulkwritecommandresult);
PHONGO_PARSE_PARAMETERS_NONE();
PHONGO_BULKWRITECOMMANDRESULT_CHECK_ACKNOWLEDGED("getUpsertedCount");
RETURN_LONG(intern->upserted_count);
}
static PHP_METHOD(MongoDB_Driver_BulkWriteCommandResult, getInsertResults)
{
PHONGO_INTERN_FROM_THIS(bulkwritecommandresult);
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)
{
PHONGO_INTERN_FROM_THIS(bulkwritecommandresult);
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)
{
PHONGO_INTERN_FROM_THIS(bulkwritecommandresult);
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)
{
PHONGO_INTERN_FROM_THIS(bulkwritecommandresult);
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_BOOL(intern->is_acknowledged);
}
/* MongoDB\Driver\BulkWriteCommandResult object handlers */
static zend_object_handlers phongo_handler_bulkwritecommandresult;
static void phongo_bulkwritecommandresult_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_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* phongo_bulkwritecommandresult_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(bulkwritecommandresult, class_type);
intern->std.handlers = &phongo_handler_bulkwritecommandresult;
return &intern->std;
}
static HashTable* phongo_bulkwritecommandresult_get_debug_info(zend_object* object, int* is_temp)
{
PHONGO_INTERN_FROM_Z_OBJ(bulkwritecommandresult, object);
zval retval = ZVAL_STATIC_INIT;
*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 phongo_bulkwritecommandresult_init_ce(INIT_FUNC_ARGS)
{
phongo_bulkwritecommandresult_ce = register_class_MongoDB_Driver_BulkWriteCommandResult();
phongo_bulkwritecommandresult_ce->create_object = phongo_bulkwritecommandresult_create_object;
memcpy(&phongo_handler_bulkwritecommandresult, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_bulkwritecommandresult.get_debug_info = phongo_bulkwritecommandresult_get_debug_info;
phongo_handler_bulkwritecommandresult.free_obj = phongo_bulkwritecommandresult_free_object;
phongo_handler_bulkwritecommandresult.offset = offsetof(phongo_bulkwritecommandresult_t, std);
}
static inline bson_t* _bson_copy_or_null(const bson_t* bson)
{
return bson ? bson_copy(bson) : NULL;
}
phongo_bulkwritecommandresult_t* phongo_bulkwritecommandresult_init(zval* return_value, mongoc_bulkwriteresult_t* bw_res)
{
PHONGO_INTERN_INIT_EX(bulkwritecommandresult, 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.5.5/src/MongoDB/BulkWriteCommandResult.h 0000644 0001751 0001751 00000001641 15264101572 016732 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"
phongo_bulkwritecommandresult_t* phongo_bulkwritecommandresult_init(zval* return_value, mongoc_bulkwriteresult_t* bw_res);
#endif /* PHONGO_BULKWRITECOMMANDRESULT_H */
mongodb-2.5.5/src/MongoDB/BulkWriteCommandResult_arginfo.h 0000644 0001751 0001751 00000011067 15264101572 020442 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: c3b36fa7e01da6c3e30280afc23e71b81ef39c36 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
return class_entry;
}
mongodb-2.5.5/src/MongoDB/BulkWriteCommand_arginfo.h 0000644 0001751 0001751 00000010461 15264101572 017240 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 8c202ca492791b5f182d4a1e61f6152a10a6d0fe */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
zend_class_implements(class_entry, 1, class_entry_Countable);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/BulkWrite_arginfo.h 0000644 0001751 0001751 00000005324 15264101572 015743 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: b7ffabc15b61c0824fda1f95035668477c3ea8a2 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
zend_class_implements(class_entry, 1, class_entry_Countable);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/ClientEncryption.c 0000644 0001751 0001751 00000122537 15264101572 015620 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 "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* phongo_clientencryption_ce;
/* Forward declarations */
static void phongo_clientencryption_create_datakey(phongo_clientencryption_t* clientencryption, zval* return_value, char* kms_provider, zval* options);
static void phongo_clientencryption_encrypt(phongo_clientencryption_t* clientencryption, zval* zvalue, zval* zciphertext, zval* options);
static void phongo_clientencryption_encrypt_expression(phongo_clientencryption_t* clientencryption, zval* zexpr, zval* return_value, zval* options);
static void phongo_clientencryption_decrypt(phongo_clientencryption_t* clientencryption, zval* zciphertext, zval* zvalue);
#define RETVAL_BSON_T(reply) \
do { \
phongo_bson_state state; \
PHONGO_BSON_INIT_NO_ODM_STATE(state); \
if (!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", 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;
}
/* 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, 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)
{
PHONGO_INTERN_FROM_THIS(clientencryption);
char* kms_provider = NULL;
size_t kms_provider_len = 0;
zval* options = NULL;
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, 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)
{
PHONGO_INTERN_FROM_THIS(clientencryption);
zval* value = NULL;
zval* options = NULL;
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)
{
PHONGO_INTERN_FROM_THIS(clientencryption);
zval* expr = NULL;
zval* options = NULL;
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)
{
PHONGO_INTERN_FROM_THIS(clientencryption);
zval* ciphertext;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_OBJECT_OF_CLASS(ciphertext, 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, 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)
{
PHONGO_INTERN_FROM_THIS(clientencryption);
mongoc_cursor_t* cursor;
bson_error_t error = { 0 };
zval query = ZVAL_STATIC_INIT;
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, 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();
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();
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(&reply);
bson_destroy(masterkey);
mongoc_client_encryption_rewrap_many_datakey_result_destroy(result);
}
/* MongoDB\Driver\ClientEncryption object handlers */
static zend_object_handlers phongo_handler_clientencryption;
static void phongo_clientencryption_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_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* phongo_clientencryption_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(clientencryption, class_type);
intern->std.handlers = &phongo_handler_clientencryption;
return &intern->std;
}
static HashTable* phongo_clientencryption_get_debug_info(zend_object* object, int* is_temp)
{
zval retval = ZVAL_STATIC_INIT;
*is_temp = 1;
array_init(&retval);
return Z_ARRVAL(retval);
}
void phongo_clientencryption_init_ce(INIT_FUNC_ARGS)
{
phongo_clientencryption_ce = register_class_MongoDB_Driver_ClientEncryption();
phongo_clientencryption_ce->create_object = phongo_clientencryption_create_object;
memcpy(&phongo_handler_clientencryption, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_clientencryption.get_debug_info = phongo_clientencryption_get_debug_info;
phongo_handler_clientencryption.free_obj = phongo_clientencryption_free_object;
phongo_handler_clientencryption.offset = offsetof(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), phongo_manager_ce)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"keyVaultClient\" option to be %s, %s given", ZSTR_VAL(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_validate_namespace(key_vault_namespace, plen)) {
if (pfree) {
efree(key_vault_namespace);
}
goto cleanup;
}
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;
}
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;
}
phongo_zval_to_bson(tls_options, PHONGO_BSON_NONE, &bson_options, NULL);
if (EG(exception)) {
bson_destroy(&bson_options);
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(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++) {
if (keyaltnames[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), phongo_binary_ce)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"keyMaterial\" option to be %s, %s given", ZSTR_VAL(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;
}
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(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_string_opts_t* phongo_clientencryption_encrypt_string_opts_from_zval(zval* options)
{
mongoc_client_encryption_encrypt_string_opts_t* opts;
opts = mongoc_client_encryption_encrypt_string_opts_new();
if (!options || Z_TYPE_P(options) != IS_ARRAY) {
return opts;
}
if (php_array_existsc(options, "caseSensitive")) {
mongoc_client_encryption_encrypt_string_opts_set_case_sensitive(opts, php_array_fetchc_bool(options, "caseSensitive"));
}
if (php_array_existsc(options, "diacriticSensitive")) {
mongoc_client_encryption_encrypt_string_opts_set_diacritic_sensitive(opts, php_array_fetchc_bool(options, "diacriticSensitive"));
}
if (php_array_existsc(options, "prefix")) {
zval* prefix_zval;
mongoc_client_encryption_encrypt_string_prefix_opts_t* prefix_opts;
prefix_opts = mongoc_client_encryption_encrypt_string_prefix_opts_new();
prefix_zval = php_array_fetchc_deref(options, "prefix");
if (prefix_zval && Z_TYPE_P(prefix_zval) == IS_ARRAY) {
if (php_array_existsc(prefix_zval, "strMaxQueryLength")) {
int64_t v = php_array_fetchc_long(prefix_zval, "strMaxQueryLength");
if (v < INT32_MIN || v > INT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"strMaxQueryLength\" to be a 32-bit integer, %" PRId64 " given", v);
mongoc_client_encryption_encrypt_string_prefix_opts_destroy(prefix_opts);
goto cleanup;
}
mongoc_client_encryption_encrypt_string_prefix_opts_set_str_max_query_length(prefix_opts, (int32_t) v);
}
if (php_array_existsc(prefix_zval, "strMinQueryLength")) {
int64_t v = php_array_fetchc_long(prefix_zval, "strMinQueryLength");
if (v < INT32_MIN || v > INT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"strMinQueryLength\" to be a 32-bit integer, %" PRId64 " given", v);
mongoc_client_encryption_encrypt_string_prefix_opts_destroy(prefix_opts);
goto cleanup;
}
mongoc_client_encryption_encrypt_string_prefix_opts_set_str_min_query_length(prefix_opts, (int32_t) v);
}
}
mongoc_client_encryption_encrypt_string_opts_set_prefix(opts, prefix_opts);
mongoc_client_encryption_encrypt_string_prefix_opts_destroy(prefix_opts);
}
if (php_array_existsc(options, "suffix")) {
zval* suffix_zval;
mongoc_client_encryption_encrypt_string_suffix_opts_t* suffix_opts;
suffix_opts = mongoc_client_encryption_encrypt_string_suffix_opts_new();
suffix_zval = php_array_fetchc_deref(options, "suffix");
if (suffix_zval && Z_TYPE_P(suffix_zval) == IS_ARRAY) {
if (php_array_existsc(suffix_zval, "strMaxQueryLength")) {
int64_t v = php_array_fetchc_long(suffix_zval, "strMaxQueryLength");
if (v < INT32_MIN || v > INT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"strMaxQueryLength\" to be a 32-bit integer, %" PRId64 " given", v);
mongoc_client_encryption_encrypt_string_suffix_opts_destroy(suffix_opts);
goto cleanup;
}
mongoc_client_encryption_encrypt_string_suffix_opts_set_str_max_query_length(suffix_opts, (int32_t) v);
}
if (php_array_existsc(suffix_zval, "strMinQueryLength")) {
int64_t v = php_array_fetchc_long(suffix_zval, "strMinQueryLength");
if (v < INT32_MIN || v > INT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"strMinQueryLength\" to be a 32-bit integer, %" PRId64 " given", v);
mongoc_client_encryption_encrypt_string_suffix_opts_destroy(suffix_opts);
goto cleanup;
}
mongoc_client_encryption_encrypt_string_suffix_opts_set_str_min_query_length(suffix_opts, (int32_t) v);
}
}
mongoc_client_encryption_encrypt_string_opts_set_suffix(opts, suffix_opts);
mongoc_client_encryption_encrypt_string_suffix_opts_destroy(suffix_opts);
}
if (php_array_existsc(options, "substring")) {
zval* substring_zval;
mongoc_client_encryption_encrypt_string_substring_opts_t* substring_opts;
substring_opts = mongoc_client_encryption_encrypt_string_substring_opts_new();
substring_zval = php_array_fetchc_deref(options, "substring");
if (substring_zval && Z_TYPE_P(substring_zval) == IS_ARRAY) {
if (php_array_existsc(substring_zval, "strMaxLength")) {
int64_t v = php_array_fetchc_long(substring_zval, "strMaxLength");
if (v < INT32_MIN || v > INT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"strMaxLength\" to be a 32-bit integer, %" PRId64 " given", v);
mongoc_client_encryption_encrypt_string_substring_opts_destroy(substring_opts);
goto cleanup;
}
mongoc_client_encryption_encrypt_string_substring_opts_set_str_max_length(substring_opts, (int32_t) v);
}
if (php_array_existsc(substring_zval, "strMaxQueryLength")) {
int64_t v = php_array_fetchc_long(substring_zval, "strMaxQueryLength");
if (v < INT32_MIN || v > INT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"strMaxQueryLength\" to be a 32-bit integer, %" PRId64 " given", v);
mongoc_client_encryption_encrypt_string_substring_opts_destroy(substring_opts);
goto cleanup;
}
mongoc_client_encryption_encrypt_string_substring_opts_set_str_max_query_length(substring_opts, (int32_t) v);
}
if (php_array_existsc(substring_zval, "strMinQueryLength")) {
int64_t v = php_array_fetchc_long(substring_zval, "strMinQueryLength");
if (v < INT32_MIN || v > INT32_MAX) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"strMinQueryLength\" to be a 32-bit integer, %" PRId64 " given", v);
mongoc_client_encryption_encrypt_string_substring_opts_destroy(substring_opts);
goto cleanup;
}
mongoc_client_encryption_encrypt_string_substring_opts_set_str_min_query_length(substring_opts, (int32_t) v);
}
}
mongoc_client_encryption_encrypt_string_opts_set_substring(opts, substring_opts);
mongoc_client_encryption_encrypt_string_substring_opts_destroy(substring_opts);
}
return opts;
cleanup:
if (opts) {
mongoc_client_encryption_encrypt_string_opts_destroy(opts);
}
return NULL;
}
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) {
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);
}
if (php_array_existsc(options, "stringOpts")) {
mongoc_client_encryption_encrypt_string_opts_t* string_opts;
string_opts = phongo_clientencryption_encrypt_string_opts_from_zval(php_array_fetchc_deref(options, "stringOpts"));
if (!string_opts) {
/* Exception already thrown */
goto cleanup;
}
mongoc_client_encryption_encrypt_opts_set_string_opts(opts, string_opts);
mongoc_client_encryption_encrypt_string_opts_destroy(string_opts);
}
return opts;
cleanup:
if (opts) {
mongoc_client_encryption_encrypt_opts_destroy(opts);
}
return NULL;
}
static void phongo_clientencryption_encrypt(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(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 };
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 (!phongo_bson_to_zval_internal(&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(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(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(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(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(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(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.5.5/src/MongoDB/ClientEncryption.h 0000644 0001751 0001751 00000001530 15264101572 015612 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(phongo_clientencryption_t* intern, zval* options, zval* default_key_vault_client_manager);
#endif /* PHONGO_CLIENTENCRYPTION_H */
mongodb-2.5.5/src/MongoDB/ClientEncryption_arginfo.h 0000644 0001751 0001751 00000024256 15264101572 017331 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 1b2aa1b90af91216b8f9261143058edf9a2a81ca */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
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.5.5/src/MongoDB/Command.c 0000644 0001751 0001751 00000011337 15264101572 013700 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 "phongo.h"
#include "phongo_bson_encode.h"
#include "phongo_error.h"
#include "Command_arginfo.h"
zend_class_entry* 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 phongo_command_init_max_await_time_ms(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 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 phongo_command_init(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;
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 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 (!phongo_command_init_max_await_time_ms(intern, options)) {
return false;
}
return true;
}
/* Constructs a new Command */
static PHP_METHOD(MongoDB_Driver_Command, __construct)
{
PHONGO_INTERN_FROM_THIS(command);
zval* document;
zval* options = NULL;
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();
phongo_command_init(intern, document, options);
}
/* MongoDB\Driver\Command object handlers */
static zend_object_handlers phongo_handler_command;
static void phongo_command_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(command, object);
zend_object_std_dtor(&intern->std);
if (intern->bson) {
bson_clear(&intern->bson);
}
}
static zend_object* phongo_command_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(command, class_type);
intern->std.handlers = &phongo_handler_command;
return &intern->std;
}
static HashTable* phongo_command_get_debug_info(zend_object* object, int* is_temp)
{
PHONGO_INTERN_FROM_Z_OBJ(command, object);
zval retval = ZVAL_STATIC_INIT;
*is_temp = 1;
array_init_size(&retval, 1);
if (intern->bson) {
zval zv;
if (!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 phongo_command_init_ce(INIT_FUNC_ARGS)
{
phongo_command_ce = register_class_MongoDB_Driver_Command();
phongo_command_ce->create_object = phongo_command_create_object;
memcpy(&phongo_handler_command, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_command.get_debug_info = phongo_command_get_debug_info;
phongo_handler_command.free_obj = phongo_command_free_object;
phongo_handler_command.offset = offsetof(phongo_command_t, std);
}
mongodb-2.5.5/src/MongoDB/Command_arginfo.h 0000644 0001751 0001751 00000002202 15264101572 015401 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: e779e5022eadeccbd0d2dfb14ce2cf157bb253d8 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Cursor.c 0000644 0001751 0001751 00000032566 15264101572 013606 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 "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* 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 phongo_cursor_free_session_if_exhausted(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 phongo_cursor_free_current(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)
{
PHONGO_INTERN_FROM_THIS(cursor);
phongo_bson_state state;
zval* typemap = NULL;
bool restore_current_element = false;
PHONGO_BSON_INIT_STATE(state);
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY_OR_NULL(typemap)
PHONGO_PARSE_PARAMETERS_END();
if (!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)) {
phongo_cursor_free_current(intern);
restore_current_element = true;
}
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 (!phongo_bson_to_zval_ex(doc, &intern->visitor_data)) {
phongo_cursor_free_current(intern);
}
}
}
static int 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(), phongo_cursor_to_array_apply, (void*) return_value) != SUCCESS) {
zval_ptr_dtor_nogc(return_value);
RETURN_NULL();
}
}
/* Returns the CursorId for this cursor */
static PHP_METHOD(MongoDB_Driver_Cursor, getId)
{
PHONGO_INTERN_FROM_THIS(cursor);
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)
{
PHONGO_INTERN_FROM_THIS(cursor);
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)
{
PHONGO_INTERN_FROM_THIS(cursor);
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_BOOL(!mongoc_cursor_more(intern->cursor));
}
static PHP_METHOD(MongoDB_Driver_Cursor, current)
{
PHONGO_INTERN_FROM_THIS(cursor);
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)
{
PHONGO_INTERN_FROM_THIS(cursor);
PHONGO_PARSE_PARAMETERS_NONE();
if (Z_ISUNDEF(intern->visitor_data.zchild)) {
RETURN_NULL();
}
RETURN_LONG(intern->current);
}
static PHP_METHOD(MongoDB_Driver_Cursor, next)
{
PHONGO_INTERN_FROM_THIS(cursor);
const bson_t* doc;
PHONGO_PARSE_PARAMETERS_NONE();
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 (!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. */
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);
}
}
phongo_cursor_free_session_if_exhausted(intern);
}
static PHP_METHOD(MongoDB_Driver_Cursor, valid)
{
PHONGO_INTERN_FROM_THIS(cursor);
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_BOOL(!Z_ISUNDEF(intern->visitor_data.zchild));
}
static PHP_METHOD(MongoDB_Driver_Cursor, rewind)
{
PHONGO_INTERN_FROM_THIS(cursor);
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;
}
phongo_cursor_free_current(intern);
doc = mongoc_cursor_current(intern->cursor);
if (doc) {
if (!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. */
phongo_cursor_free_current(intern);
}
}
phongo_cursor_free_session_if_exhausted(intern);
}
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Cursor)
/* MongoDB\Driver\Cursor object handlers */
static zend_object_handlers phongo_handler_cursor;
static void phongo_cursor_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_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);
}
phongo_bson_typemap_dtor(&intern->visitor_data.map);
phongo_cursor_free_current(intern);
}
static zend_object* phongo_cursor_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(cursor, class_type);
PHONGO_SET_CREATED_BY_PID(intern);
intern->std.handlers = &phongo_handler_cursor;
return &intern->std;
}
static HashTable* phongo_cursor_get_debug_info(zend_object* object, int* is_temp)
{
PHONGO_INTERN_FROM_Z_OBJ(cursor, object);
zval retval = ZVAL_STATIC_INIT;
*is_temp = 1;
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 phongo_cursor_init_ce(INIT_FUNC_ARGS)
{
phongo_cursor_ce = register_class_MongoDB_Driver_Cursor(phongo_cursor_interface_ce);
phongo_cursor_ce->create_object = phongo_cursor_create_object;
memcpy(&phongo_handler_cursor, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_cursor.get_debug_info = phongo_cursor_get_debug_info;
phongo_handler_cursor.free_obj = phongo_cursor_free_object;
phongo_handler_cursor.offset = offsetof(phongo_cursor_t, std);
}
static void phongo_cursor_init(zval* return_value, zval* manager, mongoc_cursor_t* cursor, zval* readPreference, zval* session)
{
PHONGO_INTERN_INIT_EX(cursor, 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)
{
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)
{
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.5.5/src/MongoDB/Cursor.h 0000644 0001751 0001751 00000002160 15264101572 013576 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.5.5/src/MongoDB/CursorInterface.c 0000644 0001751 0001751 00000001621 15264101572 015413 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 "phongo.h"
#include "CursorInterface_arginfo.h"
zend_class_entry* phongo_cursor_interface_ce;
void phongo_cursor_interface_init_ce(INIT_FUNC_ARGS)
{
phongo_cursor_interface_ce = register_class_MongoDB_Driver_CursorInterface(zend_ce_iterator);
}
mongodb-2.5.5/src/MongoDB/CursorInterface_arginfo.h 0000644 0001751 0001751 00000007251 15264101572 017132 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: a679a82c3245e125935b03359a1d8007dbd22b24 */
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[] = {
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("current", NULL, arginfo_class_MongoDB_Driver_CursorInterface_current, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("current", NULL, arginfo_class_MongoDB_Driver_CursorInterface_current, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("getId", NULL, arginfo_class_MongoDB_Driver_CursorInterface_getId, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("getId", NULL, arginfo_class_MongoDB_Driver_CursorInterface_getId, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("getServer", NULL, arginfo_class_MongoDB_Driver_CursorInterface_getServer, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("getServer", NULL, arginfo_class_MongoDB_Driver_CursorInterface_getServer, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("isDead", NULL, arginfo_class_MongoDB_Driver_CursorInterface_isDead, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("isDead", NULL, arginfo_class_MongoDB_Driver_CursorInterface_isDead, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("key", NULL, arginfo_class_MongoDB_Driver_CursorInterface_key, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("key", NULL, arginfo_class_MongoDB_Driver_CursorInterface_key, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("setTypeMap", NULL, arginfo_class_MongoDB_Driver_CursorInterface_setTypeMap, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("setTypeMap", NULL, arginfo_class_MongoDB_Driver_CursorInterface_setTypeMap, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
#if (PHP_VERSION_ID >= 80400)
ZEND_RAW_FENTRY("toArray", NULL, arginfo_class_MongoDB_Driver_CursorInterface_toArray, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT, NULL, NULL)
#else
ZEND_RAW_FENTRY("toArray", NULL, arginfo_class_MongoDB_Driver_CursorInterface_toArray, ZEND_ACC_PUBLIC|ZEND_ACC_ABSTRACT)
#endif
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.5.5/src/MongoDB/Cursor_arginfo.h 0000644 0001751 0001751 00000007662 15264101572 015317 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 78a1878cbe0b4ba92c8daa4385876643b6c191e7 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
zend_class_implements(class_entry, 1, class_entry_MongoDB_Driver_CursorInterface);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Manager.c 0000644 0001751 0001751 00000063137 15264101572 013701 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 "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* 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 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. 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 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);
phongo_read_preference_prep_tagsets(option);
continue;
}
if (!strcasecmp(ZSTR_VAL(string_key), MONGOC_URI_AUTHMECHANISMPROPERTIES)) {
ZVAL_DEREF(option);
SEPARATE_ZVAL_NOREF(option);
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 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)
{
PHONGO_INTERN_FROM_THIS(manager);
char* uri_string = NULL;
size_t uri_string_len = 0;
zval* options = NULL;
zval* driverOptions = NULL;
/* Separate the options zval, since it may be modified in
* phongo_manager_prep_uri_options(). Also separate driverOptions, since
* it may be modified in 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) {
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 (!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)
{
PHONGO_INTERN_FROM_THIS(manager);
zval* subscriber;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_OBJECT_OF_CLASS(subscriber, phongo_subscriber_ce)
PHONGO_PARSE_PARAMETERS_END();
if (instanceof_function(Z_OBJCE_P(subscriber), phongo_logsubscriber_ce)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "LogSubscriber instances cannot be registered with a Manager");
}
/* 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, 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)
{
PHONGO_INTERN_FROM_THIS(manager);
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(db, db_len)
Z_PARAM_OBJECT_OF_CLASS(command, phongo_command_ce)
Z_PARAM_OPTIONAL
Z_PARAM_ZVAL_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
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 (!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, db_len, command, options, server_id, return_value);
}
/* Execute a ReadCommand */
static PHP_METHOD(MongoDB_Driver_Manager, executeReadCommand)
{
PHONGO_INTERN_FROM_THIS(manager);
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(db, db_len)
Z_PARAM_OBJECT_OF_CLASS(command, phongo_command_ce)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
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 (!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, db_len, command, options, server_id, return_value);
}
/* Execute a WriteCommand */
static PHP_METHOD(MongoDB_Driver_Manager, executeWriteCommand)
{
PHONGO_INTERN_FROM_THIS(manager);
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(db, db_len)
Z_PARAM_OBJECT_OF_CLASS(command, phongo_command_ce)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
if (!phongo_parse_session(options, intern->client, NULL, &zsession)) {
/* Exception should already have been thrown */
return;
}
if (!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, db_len, command, options, server_id, return_value);
}
/* Execute a ReadWriteCommand */
static PHP_METHOD(MongoDB_Driver_Manager, executeReadWriteCommand)
{
PHONGO_INTERN_FROM_THIS(manager);
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(db, db_len)
Z_PARAM_OBJECT_OF_CLASS(command, phongo_command_ce)
Z_PARAM_OPTIONAL
Z_PARAM_ARRAY_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
if (!phongo_parse_session(options, intern->client, NULL, &zsession)) {
/* Exception should already have been thrown */
return;
}
if (!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, db_len, command, options, server_id, return_value);
}
/* Execute a Query */
static PHP_METHOD(MongoDB_Driver_Manager, executeQuery)
{
PHONGO_INTERN_FROM_THIS(manager);
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(namespace, namespace_len)
Z_PARAM_OBJECT_OF_CLASS(query, phongo_query_ce)
Z_PARAM_OPTIONAL
Z_PARAM_ZVAL_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
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 (!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, namespace_len, 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)
{
PHONGO_INTERN_FROM_THIS(manager);
char* namespace;
size_t namespace_len;
zval* zbulk;
phongo_bulkwrite_t* bulk;
zval* options = NULL;
uint32_t server_id = 0;
zval* zsession = NULL;
PHONGO_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STRING(namespace, namespace_len)
Z_PARAM_OBJECT_OF_CLASS(zbulk, phongo_bulkwrite_ce)
Z_PARAM_OPTIONAL
Z_PARAM_ZVAL_OR_NULL(options)
PHONGO_PARSE_PARAMETERS_END();
bulk = Z_BULKWRITE_OBJ_P(zbulk);
if (!phongo_parse_session(options, intern->client, NULL, &zsession)) {
/* Exception should already have been thrown */
return;
}
if (!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, namespace_len, bulk, options, server_id, return_value);
}
/* Executes a BulkWriteCommand (i.e. bulkWrite command for MongoDB 8.0+) */
static PHP_METHOD(MongoDB_Driver_Manager, executeBulkWriteCommand)
{
PHONGO_INTERN_FROM_THIS(manager);
zval* zbwc;
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, phongo_bulkwritecommand_ce)
Z_PARAM_OPTIONAL
Z_PARAM_ZVAL_OR_NULL(zoptions)
PHONGO_PARSE_PARAMETERS_END();
bwc = Z_BULKWRITECOMMAND_OBJ_P(zbwc);
if (!phongo_parse_session(zoptions, intern->client, NULL, &zsession)) {
/* Exception should already have been thrown */
return;
}
if (!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)
{
PHONGO_INTERN_FROM_THIS(manager);
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)
{
PHONGO_INTERN_FROM_THIS(manager);
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)
{
PHONGO_INTERN_FROM_THIS(manager);
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)
{
PHONGO_INTERN_FROM_THIS(manager);
mongoc_server_description_t** sds;
size_t i, n = 0;
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)
{
PHONGO_INTERN_FROM_THIS(manager);
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)
{
PHONGO_INTERN_FROM_THIS(manager);
zval* subscriber;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_OBJECT_OF_CLASS(subscriber, phongo_subscriber_ce)
PHONGO_PARSE_PARAMETERS_END();
/* 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)
{
PHONGO_INTERN_FROM_THIS(manager);
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, phongo_readpreference_ce)
PHONGO_PARSE_PARAMETERS_END();
if (!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)
{
PHONGO_INTERN_FROM_THIS(manager);
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;
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 phongo_handler_manager;
static void phongo_manager_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_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. */
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. */
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_release(intern->subscribers);
}
}
static zend_object* phongo_manager_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(manager, class_type);
PHONGO_SET_CREATED_BY_PID(intern);
intern->std.handlers = &phongo_handler_manager;
return &intern->std;
}
static HashTable* phongo_manager_get_debug_info(zend_object* object, int* is_temp)
{
phongo_manager_t* intern;
mongoc_server_description_t** sds;
size_t i, n = 0;
zval retval = ZVAL_STATIC_INIT;
zval cluster;
zval manager_zval;
*is_temp = 1;
intern = Z_OBJ_MANAGER(object);
array_init_size(&retval, 3);
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);
/* phongo_server_init requires a zval* but get_debug_info only provides a
* zend_object*. Wrap the object pointer in a temporary zval without
* incrementing the refcount, since phongo_server_init will do so itself
* when it stores the manager reference via ZVAL_ZVAL. */
ZVAL_OBJ(&manager_zval, object);
for (i = 0; i < n; i++) {
zval obj;
phongo_server_init(&obj, &manager_zval, mongoc_server_description_id(sds[i]));
add_next_index_zval(&cluster, &obj);
}
ADD_ASSOC_ZVAL_EX(&retval, "cluster", &cluster);
{
const char* crypt_shared_version = mongoc_client_get_crypt_shared_version(intern->client);
if (crypt_shared_version) {
ADD_ASSOC_STRING(&retval, "cryptSharedVersion", crypt_shared_version);
} else {
ADD_ASSOC_NULL_EX(&retval, "cryptSharedVersion");
}
}
mongoc_server_descriptions_destroy_all(sds, n);
return Z_ARRVAL(retval);
}
void phongo_manager_init_ce(INIT_FUNC_ARGS)
{
phongo_manager_ce = register_class_MongoDB_Driver_Manager();
phongo_manager_ce->create_object = phongo_manager_create_object;
memcpy(&phongo_handler_manager, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_manager.get_debug_info = phongo_manager_get_debug_info;
phongo_handler_manager.free_obj = phongo_manager_free_object;
phongo_handler_manager.offset = offsetof(phongo_manager_t, std);
}
mongodb-2.5.5/src/MongoDB/Manager_arginfo.h 0000644 0001751 0001751 00000017611 15264101572 015407 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 1fee3e4e276420cfc5b18ab7d6e076be94779105 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Query.c 0000644 0001751 0001751 00000034515 15264101572 013432 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 "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* 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 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 (Z_STRLEN_P(value) > PHONGO_BSON_MAX_LENGTH) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"%s\" option to be <= %" PRId32 " bytes, %zu given", opts_key, (int32_t) PHONGO_BSON_MAX_LENGTH, Z_STRLEN_P(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 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;
}
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 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 (!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 (!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 (!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 phongo_query_init_hint(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 phongo_query_init_readconcern(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), phongo_readconcern_ce)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"readConcern\" option to be %s, %s given", ZSTR_VAL(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 phongo_query_init_max_await_time_ms(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)
{
phongo_query_t* intern;
if (Z_ISUNDEF_P(return_value)) {
object_init_ex(return_value, phongo_query_ce);
}
if (Z_TYPE_P(return_value) != IS_OBJECT || !instanceof_function(Z_OBJCE_P(return_value), phongo_query_ce)) {
phongo_throw_exception(PHONGO_ERROR_UNEXPECTED_VALUE, "Expected initialization object to be %s, %s given", ZSTR_VAL(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) {
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 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 (!phongo_query_init_hint(intern, options)) {
return false;
}
if (!phongo_query_init_readconcern(intern, options)) {
return false;
}
if (!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 phongo_handler_query;
static void phongo_query_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_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* phongo_query_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(query, class_type);
intern->std.handlers = &phongo_handler_query;
return &intern->std;
}
static HashTable* phongo_query_get_debug_info(zend_object* object, int* is_temp)
{
PHONGO_INTERN_FROM_Z_OBJ(query, object);
zval retval = ZVAL_STATIC_INIT;
*is_temp = 1;
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 (!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 (!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;
phongo_readconcern_init(&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 phongo_query_init_ce(INIT_FUNC_ARGS)
{
phongo_query_ce = register_class_MongoDB_Driver_Query();
phongo_query_ce->create_object = phongo_query_create_object;
memcpy(&phongo_handler_query, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_query.get_debug_info = phongo_query_get_debug_info;
phongo_handler_query.free_obj = phongo_query_free_object;
phongo_handler_query.offset = offsetof(phongo_query_t, std);
}
mongodb-2.5.5/src/MongoDB/Query.h 0000644 0001751 0001751 00000001403 15264101572 013425 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.5.5/src/MongoDB/Query_arginfo.h 0000644 0001751 0001751 00000002156 15264101572 015140 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 7d990858002d8ef19dd1d6e081bd94e7baf9787b */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
return class_entry;
}
mongodb-2.5.5/src/MongoDB/ReadConcern.c 0000644 0001751 0001751 00000014313 15264101572 014502 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 "phongo.h"
#include "phongo_error.h"
#include "ReadConcern_arginfo.h"
zend_class_entry* phongo_readconcern_ce;
static void phongo_readconcern_update_properties(phongo_readconcern_t* intern)
{
const char* level = mongoc_read_concern_get_level(intern->read_concern);
if (level) {
zend_update_property_string(phongo_readconcern_ce, &intern->std, ZEND_STRL("level"), level);
} else {
zend_update_property_null(phongo_readconcern_ce, &intern->std, ZEND_STRL("level"));
}
}
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool phongo_readconcern_init_from_hash(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));
} else if (Z_TYPE_P(level) != IS_NULL) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"level\" string field", ZSTR_VAL(phongo_readconcern_ce->name));
goto failure;
}
}
phongo_readconcern_update_properties(intern);
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)
{
PHONGO_INTERN_FROM_THIS(readconcern);
char* level = NULL;
size_t level_len = 0;
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);
}
phongo_readconcern_update_properties(intern);
}
static PHP_METHOD(MongoDB_Driver_ReadConcern, __set_state)
{
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
PHONGO_INTERN_INIT_EX(readconcern, return_value);
props = Z_ARRVAL_P(array);
phongo_readconcern_init_from_hash(intern, props);
}
/* Returns the ReadConcern "level" option */
static PHP_METHOD(MongoDB_Driver_ReadConcern, getLevel)
{
PHONGO_INTERN_FROM_THIS(readconcern);
const char* level;
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)
{
PHONGO_INTERN_FROM_THIS(readconcern);
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_BOOL(mongoc_read_concern_is_default(intern->read_concern));
}
static PHP_METHOD(MongoDB_Driver_ReadConcern, bsonSerialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
array_init_size(return_value, 1);
{
zend_string* string_key;
zval* val;
ZEND_HASH_FOREACH_STR_KEY_VAL_IND(HASH_OF(getThis()), string_key, val)
{
if (Z_TYPE_P(val) == IS_NULL) {
continue;
}
Z_TRY_ADDREF_P(val);
add_assoc_zval(return_value, ZSTR_VAL(string_key), val);
}
ZEND_HASH_FOREACH_END();
}
convert_to_object(return_value);
}
static PHP_METHOD(MongoDB_Driver_ReadConcern, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
phongo_readconcern_init_from_hash(Z_READCONCERN_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\Driver\ReadConcern object handlers */
static zend_object_handlers phongo_handler_readconcern;
static void phongo_readconcern_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(readconcern, object);
zend_object_std_dtor(&intern->std);
if (intern->read_concern) {
mongoc_read_concern_destroy(intern->read_concern);
}
}
static zend_object* phongo_readconcern_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(readconcern, class_type);
intern->std.handlers = &phongo_handler_readconcern;
return &intern->std;
}
static zend_object* phongo_readconcern_clone_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(readconcern, object);
phongo_readconcern_t* new_intern;
zend_object* new_object;
new_object = phongo_readconcern_create_object(object->ce);
new_intern = Z_OBJ_READCONCERN(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
new_intern->read_concern = mongoc_read_concern_copy(intern->read_concern);
return new_object;
}
void phongo_readconcern_init_ce(INIT_FUNC_ARGS)
{
phongo_readconcern_ce = register_class_MongoDB_Driver_ReadConcern(phongo_serializable_ce);
phongo_readconcern_ce->create_object = phongo_readconcern_create_object;
memcpy(&phongo_handler_readconcern, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_readconcern.clone_obj = phongo_readconcern_clone_object;
phongo_handler_readconcern.free_obj = phongo_readconcern_free_object;
phongo_handler_readconcern.offset = offsetof(phongo_readconcern_t, std);
}
void phongo_readconcern_init(zval* return_value, const mongoc_read_concern_t* read_concern)
{
PHONGO_INTERN_INIT_EX(readconcern, return_value);
intern->read_concern = mongoc_read_concern_copy(read_concern);
phongo_readconcern_update_properties(intern);
}
const mongoc_read_concern_t* phongo_read_concern_from_zval(zval* zread_concern)
{
if (zread_concern) {
PHONGO_INTERN_FROM_ZVAL(readconcern, zread_concern);
if (intern) {
return intern->read_concern;
}
}
return NULL;
}
mongodb-2.5.5/src/MongoDB/ReadConcern.h 0000644 0001751 0001751 00000001627 15264101572 014513 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);
#endif /* PHONGO_READCONCERN_H */
mongodb-2.5.5/src/MongoDB/ReadConcern_arginfo.h 0000644 0001751 0001751 00000013320 15264101572 016211 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: dc2dbca018378c16253293bee52c6931e427c118 */
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()
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 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_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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
#endif
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);
zval property_level_default_value;
ZVAL_UNDEF(&property_level_default_value);
zend_string *property_level_name = zend_string_init("level", sizeof("level") - 1, 1);
zend_declare_typed_property(class_entry, property_level_name, &property_level_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING|MAY_BE_NULL));
zend_string_release(property_level_name);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/ReadPreference.c 0000644 0001751 0001751 00000047166 15264101572 015205 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 "phongo.h"
#include "phongo_bson_encode.h"
#include "phongo_error.h"
#include "MongoDB/ReadPreference.h"
#include "ReadPreference_arginfo.h"
zend_class_entry* phongo_readpreference_ce;
static const char* 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 "";
}
}
static void phongo_readpreference_update_properties(phongo_readpreference_t* intern)
{
const bson_t* bson;
zend_update_property_string(phongo_readpreference_ce, &intern->std, ZEND_STRL("mode"), phongo_readpreference_get_mode_string(intern->read_preference));
zend_update_property_long(phongo_readpreference_ce, &intern->std, ZEND_STRL("maxStalenessSeconds"), mongoc_read_prefs_get_max_staleness_seconds(intern->read_preference));
bson = mongoc_read_prefs_get_tags(intern->read_preference);
if (!bson_empty0(bson)) {
phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
state.map.root.type = PHONGO_TYPEMAP_NATIVE_ARRAY;
if (!phongo_bson_to_zval_ex(bson, &state)) {
// Exception already thrown
zval_ptr_dtor(&state.zchild);
return;
}
zend_update_property(phongo_readpreference_ce, &intern->std, ZEND_STRL("tags"), &state.zchild);
zval_ptr_dtor(&state.zchild);
} else {
zend_update_property_null(phongo_readpreference_ce, &intern->std, ZEND_STRL("tags"));
}
bson = mongoc_read_prefs_get_hedge(intern->read_preference);
if (!bson_empty0(bson)) {
phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
if (!phongo_bson_to_zval_ex(bson, &state)) {
// Exception already thrown
zval_ptr_dtor(&state.zchild);
return;
}
zend_update_property(phongo_readpreference_ce, &intern->std, ZEND_STRL("hedge"), &state.zchild);
zval_ptr_dtor(&state.zchild);
} else {
zend_update_property_null(phongo_readpreference_ce, &intern->std, ZEND_STRL("hedge"));
}
}
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool phongo_readpreference_init_from_hash(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(phongo_readpreference_ce->name));
return false;
}
} else {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"mode\" field to be string", ZSTR_VAL(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 phongo_read_preference_prep_tagsets may
* modify these tags. */
SEPARATE_ZVAL_NOREF(tagSets);
phongo_read_preference_prep_tagsets(tagSets);
phongo_zval_to_bson(tagSets, PHONGO_BSON_NONE, (bson_t*) tags, NULL);
if (!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(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(phongo_readpreference_ce->name));
bson_destroy(tags);
goto failure;
}
mongoc_read_prefs_set_tags(intern->read_preference, tags);
bson_destroy(tags);
} else if (Z_TYPE_P(tagSets) != IS_NULL) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"tags\" field to be array", ZSTR_VAL(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(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(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(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(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();
php_error_docref(NULL, E_DEPRECATED, "The \"hedge\" option is deprecated as of MongoDB 8.0 and will be removed in a future release");
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(phongo_readpreference_ce->name));
bson_destroy(hedge_doc);
goto failure;
}
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 if (Z_TYPE_P(hedge) != IS_NULL) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"hedge\" field to be an array or object", ZSTR_VAL(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;
}
phongo_readpreference_update_properties(intern);
return true;
failure:
mongoc_read_prefs_destroy(intern->read_preference);
intern->read_preference = NULL;
return false;
}
/* Constructs a new ReadPreference */
static PHP_METHOD(MongoDB_Driver_ReadPreference, __construct)
{
PHONGO_INTERN_FROM_THIS(readpreference);
zend_string* mode;
zval* tagSets = NULL;
zval* options = NULL;
/* Separate the tagSets zval, since we may end up modifying it in
* 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();
phongo_read_preference_prep_tagsets(tagSets);
phongo_zval_to_bson(tagSets, PHONGO_BSON_NONE, (bson_t*) tags, NULL);
if (!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();
php_error_docref(NULL, E_DEPRECATED, "The \"hedge\" option is deprecated as of MongoDB 8.0 and will be removed in a future release");
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;
}
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(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;
}
phongo_readpreference_update_properties(intern);
}
static PHP_METHOD(MongoDB_Driver_ReadPreference, __set_state)
{
HashTable* props;
zval* array;
/* Separate the zval, since we may end up modifying the "tags" element in
* phongo_read_preference_prep_tagsets(), which is called from
* phongo_readpreference_init_from_hash. */
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY_EX(array, 0, 1)
PHONGO_PARSE_PARAMETERS_END();
PHONGO_INTERN_INIT_EX(readpreference, return_value);
props = Z_ARRVAL_P(array);
phongo_readpreference_init_from_hash(intern, props);
}
/* Returns the ReadPreference hedge document */
static PHP_METHOD(MongoDB_Driver_ReadPreference, getHedge)
{
PHONGO_INTERN_FROM_THIS(readpreference);
const bson_t* hedge;
PHONGO_PARSE_PARAMETERS_NONE();
hedge = mongoc_read_prefs_get_hedge(intern->read_preference);
if (!bson_empty0(hedge)) {
phongo_bson_state state;
PHONGO_BSON_INIT_STATE(state);
if (!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)
{
PHONGO_INTERN_FROM_THIS(readpreference);
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)
{
PHONGO_INTERN_FROM_THIS(readpreference);
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_STRING(phongo_readpreference_get_mode_string(intern->read_preference));
}
/* Returns the ReadPreference tag sets */
static PHP_METHOD(MongoDB_Driver_ReadPreference, getTagSets)
{
PHONGO_INTERN_FROM_THIS(readpreference);
const bson_t* tags;
PHONGO_PARSE_PARAMETERS_NONE();
tags = mongoc_read_prefs_get_tags(intern->read_preference);
if (tags->len) {
phongo_bson_state state;
PHONGO_BSON_INIT_DEBUG_STATE(state);
if (!phongo_bson_to_zval_ex(tags, &state)) {
zval_ptr_dtor(&state.zchild);
return;
}
RETURN_ZVAL(&state.zchild, 0, 1);
} else {
RETURN_NULL();
}
}
static PHP_METHOD(MongoDB_Driver_ReadPreference, bsonSerialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
array_init_size(return_value, 4);
{
zend_string* string_key;
zval* val;
ZEND_HASH_FOREACH_STR_KEY_VAL_IND(HASH_OF(getThis()), string_key, val)
{
if (
(Z_TYPE_P(val) == IS_NULL) || (!strcmp(ZSTR_VAL(string_key), "maxStalenessSeconds") && Z_TYPE_P(val) == IS_LONG && Z_LVAL_P(val) == MONGOC_NO_MAX_STALENESS)) {
continue;
}
// Increase the refcount of our zval, as add_assoc_zval takes ownership, leading to the property value being
// freed once the return value goes out of scope
Z_TRY_ADDREF_P(val);
add_assoc_zval(return_value, ZSTR_VAL(string_key), val);
}
ZEND_HASH_FOREACH_END();
}
convert_to_object(return_value);
}
static PHP_METHOD(MongoDB_Driver_ReadPreference, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
phongo_readpreference_init_from_hash(Z_READPREFERENCE_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\Driver\ReadPreference object handlers */
static zend_object_handlers phongo_handler_readpreference;
static void phongo_readpreference_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(readpreference, object);
zend_object_std_dtor(&intern->std);
if (intern->read_preference) {
mongoc_read_prefs_destroy(intern->read_preference);
}
}
static zend_object* phongo_readpreference_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(readpreference, class_type);
intern->std.handlers = &phongo_handler_readpreference;
return &intern->std;
}
static zend_object* phongo_readpreference_clone_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(readpreference, object);
phongo_readpreference_t* new_intern;
zend_object* new_object;
new_object = phongo_readpreference_create_object(object->ce);
new_intern = Z_OBJ_READPREFERENCE(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
new_intern->read_preference = mongoc_read_prefs_copy(intern->read_preference);
return new_object;
}
static zval* phongo_readpreference_read_property(zend_object* zobj, zend_string* name, int type, void** cache_slot, zval* rv)
{
if (!strcmp(ZSTR_VAL(name), "hedge")) {
php_error_docref(NULL, E_DEPRECATED, "Property MongoDB\\Driver\\ReadPreference::hedge is deprecated");
}
return zend_std_read_property(zobj, name, type, cache_slot, rv);
}
void phongo_readpreference_init_ce(INIT_FUNC_ARGS)
{
phongo_readpreference_ce = register_class_MongoDB_Driver_ReadPreference(phongo_serializable_ce);
phongo_readpreference_ce->create_object = phongo_readpreference_create_object;
memcpy(&phongo_handler_readpreference, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_readpreference.clone_obj = phongo_readpreference_clone_object;
phongo_handler_readpreference.read_property = phongo_readpreference_read_property;
phongo_handler_readpreference.free_obj = phongo_readpreference_free_object;
phongo_handler_readpreference.offset = offsetof(phongo_readpreference_t, std);
}
void phongo_readpreference_init(zval* return_value, const mongoc_read_prefs_t* read_prefs)
{
PHONGO_INTERN_INIT_EX(readpreference, return_value);
intern->read_preference = mongoc_read_prefs_copy(read_prefs);
phongo_readpreference_update_properties(intern);
}
const mongoc_read_prefs_t* phongo_read_preference_from_zval(zval* zread_preference)
{
if (zread_preference) {
PHONGO_INTERN_FROM_ZVAL(readpreference, 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.
*
* phongo_read_preference_tags_are_valid() handles actual validation of the
* tag set structure. */
void 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 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.5.5/src/MongoDB/ReadPreference.h 0000644 0001751 0001751 00000002441 15264101572 015175 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 phongo_read_preference_prep_tagsets(zval* tagSets);
bool phongo_read_preference_tags_are_valid(const bson_t* tags);
#endif /* PHONGO_READPREFERENCE_H */
mongodb-2.5.5/src/MongoDB/ReadPreference_arginfo.h 0000644 0001751 0001751 00000021623 15264101572 016705 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: c96f44c362fe158f620b96b7ce44be7a048daf1d */
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()
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 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_ACC_DEPRECATED)
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_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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
#endif
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);
zval property_mode_default_value;
ZVAL_UNDEF(&property_mode_default_value);
zend_string *property_mode_name = zend_string_init("mode", sizeof("mode") - 1, 1);
zend_declare_typed_property(class_entry, property_mode_name, &property_mode_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zend_string_release(property_mode_name);
zval property_tags_default_value;
ZVAL_UNDEF(&property_tags_default_value);
zend_string *property_tags_name = zend_string_init("tags", sizeof("tags") - 1, 1);
zend_declare_typed_property(class_entry, property_tags_name, &property_tags_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_ARRAY|MAY_BE_NULL));
zend_string_release(property_tags_name);
zval property_maxStalenessSeconds_default_value;
ZVAL_UNDEF(&property_maxStalenessSeconds_default_value);
zend_string *property_maxStalenessSeconds_name = zend_string_init("maxStalenessSeconds", sizeof("maxStalenessSeconds") - 1, 1);
zend_declare_typed_property(class_entry, property_maxStalenessSeconds_name, &property_maxStalenessSeconds_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_maxStalenessSeconds_name);
zval property_hedge_default_value;
ZVAL_UNDEF(&property_hedge_default_value);
zend_string *property_hedge_name = zend_string_init("hedge", sizeof("hedge") - 1, 1);
zend_declare_typed_property(class_entry, property_hedge_name, &property_hedge_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_OBJECT|MAY_BE_NULL));
zend_string_release(property_hedge_name);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/Server.c 0000644 0001751 0001751 00000053372 15264101572 013575 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 "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* phongo_server_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_Server)
/* Executes a Command on this Server */
static PHP_METHOD(MongoDB_Driver_Server, executeCommand)
{
PHONGO_INTERN_FROM_THIS(server);
char* db;
size_t db_len;
zval* command;
zval* options = NULL;
PHONGO_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STRING(db, db_len)
Z_PARAM_OBJECT_OF_CLASS(command, 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, db_len, command, options, intern->server_id, return_value);
}
/* Executes a ReadCommand on this Server */
static PHP_METHOD(MongoDB_Driver_Server, executeReadCommand)
{
PHONGO_INTERN_FROM_THIS(server);
char* db;
size_t db_len;
zval* command;
zval* options = NULL;
PHONGO_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STRING(db, db_len)
Z_PARAM_OBJECT_OF_CLASS(command, 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, db_len, command, options, intern->server_id, return_value);
}
/* Executes a WriteCommand on this Server */
static PHP_METHOD(MongoDB_Driver_Server, executeWriteCommand)
{
PHONGO_INTERN_FROM_THIS(server);
char* db;
size_t db_len;
zval* command;
zval* options = NULL;
PHONGO_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STRING(db, db_len)
Z_PARAM_OBJECT_OF_CLASS(command, 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, db_len, command, options, intern->server_id, return_value);
}
/* Executes a ReadWriteCommand on this Server */
static PHP_METHOD(MongoDB_Driver_Server, executeReadWriteCommand)
{
PHONGO_INTERN_FROM_THIS(server);
char* db;
size_t db_len;
zval* command;
zval* options = NULL;
PHONGO_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STRING(db, db_len)
Z_PARAM_OBJECT_OF_CLASS(command, 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, db_len, command, options, intern->server_id, return_value);
}
/* Executes a Query on this Server */
static PHP_METHOD(MongoDB_Driver_Server, executeQuery)
{
PHONGO_INTERN_FROM_THIS(server);
char* namespace;
size_t namespace_len;
zval* query;
zval* options = NULL;
PHONGO_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STRING(namespace, namespace_len)
Z_PARAM_OBJECT_OF_CLASS(query, 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, namespace_len, 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)
{
PHONGO_INTERN_FROM_THIS(server);
char* namespace;
size_t namespace_len;
zval* zbulk;
phongo_bulkwrite_t* bulk;
zval* options = NULL;
PHONGO_PARSE_PARAMETERS_START(2, 3)
Z_PARAM_STRING(namespace, namespace_len)
Z_PARAM_OBJECT_OF_CLASS(zbulk, 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, namespace_len, 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)
{
PHONGO_INTERN_FROM_THIS(server);
zval* zbwc;
phongo_bulkwritecommand_t* bwc;
zval* zoptions = NULL;
PHONGO_PARSE_PARAMETERS_START(1, 2)
Z_PARAM_OBJECT_OF_CLASS(zbwc, phongo_bulkwritecommand_ce)
Z_PARAM_OPTIONAL
Z_PARAM_ZVAL_OR_NULL(zoptions)
PHONGO_PARSE_PARAMETERS_END();
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)
{
PHONGO_INTERN_FROM_THIS(server);
mongoc_server_description_t* sd;
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)
{
PHONGO_INTERN_FROM_THIS(server);
mongoc_server_description_t* sd;
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;
phongo_bson_state state;
PHONGO_BSON_INIT_DEBUG_STATE(state);
bson_iter_document(&iter, &len, &bytes);
if (!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)
{
PHONGO_INTERN_FROM_THIS(server);
mongoc_client_t* client;
mongoc_server_description_t* sd;
mongoc_server_description_t* handshake_sd = NULL;
const bson_t* hello_response;
phongo_bson_state state;
PHONGO_PARSE_PARAMETERS_NONE();
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), 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 (!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)
{
PHONGO_INTERN_FROM_THIS(server);
mongoc_server_description_t* sd;
PHONGO_PARSE_PARAMETERS_NONE();
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)
{
PHONGO_INTERN_FROM_THIS(server);
mongoc_server_description_t* sd;
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)
{
PHONGO_INTERN_FROM_THIS(server);
mongoc_server_description_t* server_description;
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)
{
PHONGO_INTERN_FROM_THIS(server);
mongoc_server_description_t* sd;
PHONGO_PARSE_PARAMETERS_NONE();
if ((sd = mongoc_client_get_server_description(Z_MANAGER_OBJ_P(&intern->manager)->client, intern->server_id))) {
RETVAL_LONG(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)
{
PHONGO_INTERN_FROM_THIS(server);
mongoc_server_description_t* sd;
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), 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)
{
PHONGO_INTERN_FROM_THIS(server);
mongoc_server_description_t* sd;
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), 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)
{
PHONGO_INTERN_FROM_THIS(server);
mongoc_server_description_t* sd;
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), 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)
{
PHONGO_INTERN_FROM_THIS(server);
mongoc_server_description_t* sd;
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)
{
PHONGO_INTERN_FROM_THIS(server);
mongoc_server_description_t* sd;
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 phongo_handler_server;
static int phongo_server_compare_objects(zval* o1, zval* o2)
{
phongo_server_t* intern1;
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 phongo_server_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(server, object);
zend_object_std_dtor(&intern->std);
if (!Z_ISUNDEF(intern->manager)) {
zval_ptr_dtor(&intern->manager);
}
}
static zend_object* phongo_server_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(server, class_type);
PHONGO_SET_CREATED_BY_PID(intern);
intern->std.handlers = &phongo_handler_server;
return &intern->std;
}
static HashTable* phongo_server_get_debug_info(zend_object* object, int* is_temp)
{
phongo_server_t* intern = NULL;
zval retval = ZVAL_STATIC_INIT;
mongoc_client_t* client;
mongoc_server_description_t* sd;
const mongoc_host_list_t* host;
const bson_t* hello_response;
bson_iter_t iter;
*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;
}
host = mongoc_server_description_host(sd);
hello_response = mongoc_server_description_hello_response(sd);
array_init(&retval);
ADD_ASSOC_STRING(&retval, "host", host->host);
ADD_ASSOC_LONG_EX(&retval, "port", host->port);
ADD_ASSOC_LONG_EX(&retval, "type", phongo_server_description_type(sd));
ADD_ASSOC_BOOL_EX(&retval, "is_primary", !strcmp(mongoc_server_description_type(sd), phongo_server_description_type_map[PHONGO_SERVER_RS_PRIMARY].name));
ADD_ASSOC_BOOL_EX(&retval, "is_secondary", !strcmp(mongoc_server_description_type(sd), phongo_server_description_type_map[PHONGO_SERVER_RS_SECONDARY].name));
ADD_ASSOC_BOOL_EX(&retval, "is_arbiter", !strcmp(mongoc_server_description_type(sd), 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;
phongo_bson_state state;
PHONGO_BSON_INIT_DEBUG_STATE(state);
bson_iter_document(&iter, &len, &bytes);
if (!phongo_bson_data_to_zval_ex(bytes, len, &state)) {
/* Exception already thrown */
zval_ptr_dtor(&state.zchild);
mongoc_server_description_destroy(sd);
zval_ptr_dtor(&retval);
return NULL;
}
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), 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 };
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);
mongoc_server_description_destroy(sd);
zval_ptr_dtor(&retval);
return NULL;
}
PHONGO_BSON_INIT_DEBUG_STATE(state);
handshake_response = mongoc_server_description_hello_response(handshake_sd);
if (!phongo_bson_to_zval_ex(handshake_response, &state)) {
/* Exception already thrown */
mongoc_server_description_destroy(handshake_sd);
zval_ptr_dtor(&state.zchild);
mongoc_server_description_destroy(sd);
zval_ptr_dtor(&retval);
return NULL;
}
ADD_ASSOC_ZVAL_EX(&retval, "last_hello_response", &state.zchild);
mongoc_server_description_destroy(handshake_sd);
} else {
phongo_bson_state state;
PHONGO_BSON_INIT_DEBUG_STATE(state);
if (!phongo_bson_to_zval_ex(hello_response, &state)) {
/* Exception already thrown */
zval_ptr_dtor(&state.zchild);
mongoc_server_description_destroy(sd);
zval_ptr_dtor(&retval);
return NULL;
}
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));
}
mongoc_server_description_destroy(sd);
return Z_ARRVAL(retval);
}
void phongo_server_init_ce(INIT_FUNC_ARGS)
{
phongo_server_ce = register_class_MongoDB_Driver_Server();
phongo_server_ce->create_object = phongo_server_create_object;
memcpy(&phongo_handler_server, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_server.compare = phongo_server_compare_objects;
phongo_handler_server.get_debug_info = phongo_server_get_debug_info;
phongo_handler_server.free_obj = phongo_server_free_object;
phongo_handler_server.offset = offsetof(phongo_server_t, std);
}
void phongo_server_init(zval* return_value, zval* manager, uint32_t server_id)
{
phongo_server_t* server;
object_init_ex(return_value, phongo_server_ce);
server = Z_SERVER_OBJ_P(return_value);
server->server_id = server_id;
ZVAL_ZVAL(&server->manager, manager, 1, 0);
}
mongodb-2.5.5/src/MongoDB/Server.h 0000644 0001751 0001751 00000001451 15264101572 013571 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);
#endif /* PHONGO_SERVER_H */
mongodb-2.5.5/src/MongoDB/ServerApi.c 0000644 0001751 0001751 00000017365 15264101572 014231 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 "phongo.h"
#include "phongo_error.h"
#include "ServerApi_arginfo.h"
zend_class_entry* phongo_serverapi_ce;
static bool 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 phongo_serverapi_init_from_hash(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(phongo_serverapi_ce->name));
return false;
}
if ((strict = zend_hash_str_find(props, ZEND_STRL("strict"))) && !Z_ISNULL_P(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(phongo_serverapi_ce->name));
return false;
}
}
if ((deprecation_errors = zend_hash_str_find(props, ZEND_STRL("deprecationErrors"))) && !Z_ISNULL_P(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(phongo_serverapi_ce->name));
return false;
}
}
return phongo_serverapi_create_libmongoc_object(
&intern->server_api,
Z_STR_P(version),
strict && !Z_ISNULL_P(strict),
strict && zend_is_true(strict),
deprecation_errors && !Z_ISNULL_P(deprecation_errors),
deprecation_errors && zend_is_true(deprecation_errors));
}
/* Constructs a new ServerApi object */
static PHP_METHOD(MongoDB_Driver_ServerApi, __construct)
{
PHONGO_INTERN_FROM_THIS(serverapi);
zend_string* version;
zend_bool strict = 0;
zend_bool strict_null = 1;
zend_bool deprecation_errors = 0;
zend_bool deprecation_errors_null = 1;
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
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)
{
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
PHONGO_INTERN_INIT_EX(serverapi, return_value);
props = Z_ARRVAL_P(array);
phongo_serverapi_init_from_hash(intern, props);
}
static HashTable* phongo_serverapi_get_properties_hash(zend_object* object, bool is_temp, bool include_null)
{
PHONGO_INTERN_FROM_Z_OBJ(serverapi, object);
HashTable* props;
zval version, strict, deprecation_errors;
bool is_set;
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_update(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_update(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_update(props, "deprecationErrors", sizeof("deprecationErrors") - 1, &deprecation_errors);
}
return props;
}
static PHP_METHOD(MongoDB_Driver_ServerApi, bsonSerialize)
{
PHONGO_PARSE_PARAMETERS_NONE();
ZVAL_ARR(return_value, 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(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();
phongo_serverapi_init_from_hash(Z_SERVERAPI_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\Driver\ServerApi object handlers */
static zend_object_handlers phongo_handler_serverapi;
static void phongo_serverapi_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(serverapi, object);
zend_object_std_dtor(&intern->std);
if (intern->properties) {
zend_hash_release(intern->properties);
}
if (intern->server_api) {
mongoc_server_api_destroy(intern->server_api);
}
}
static zend_object* phongo_serverapi_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(serverapi, class_type);
intern->std.handlers = &phongo_handler_serverapi;
return &intern->std;
}
static HashTable* phongo_serverapi_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return phongo_serverapi_get_properties_hash(object, true, true);
}
static HashTable* phongo_serverapi_get_properties(zend_object* object)
{
return phongo_serverapi_get_properties_hash(object, false, true);
}
void phongo_serverapi_init_ce(INIT_FUNC_ARGS)
{
phongo_serverapi_ce = register_class_MongoDB_Driver_ServerApi(phongo_serializable_ce);
phongo_serverapi_ce->create_object = phongo_serverapi_create_object;
memcpy(&phongo_handler_serverapi, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_serverapi.get_debug_info = phongo_serverapi_get_debug_info;
phongo_handler_serverapi.get_properties = phongo_serverapi_get_properties;
phongo_handler_serverapi.free_obj = phongo_serverapi_free_object;
phongo_handler_serverapi.offset = offsetof(phongo_serverapi_t, std);
}
mongodb-2.5.5/src/MongoDB/ServerApi_arginfo.h 0000644 0001751 0001751 00000006031 15264101572 015727 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: e9d2009a853e8e36f7ef9ae08f066456d56383b8 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
#endif
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.5.5/src/MongoDB/ServerDescription.c 0000644 0001751 0001751 00000021737 15264101572 016001 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 "phongo.h"
#include "phongo_error.h"
#include "MongoDB/ServerDescription.h"
#include "ServerDescription_arginfo.h"
zend_class_entry* phongo_serverdescription_ce;
phongo_server_description_type_map_t
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)
{
PHONGO_INTERN_FROM_THIS(serverdescription);
const bson_t* helloResponse;
phongo_bson_state state;
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 (!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)
{
PHONGO_INTERN_FROM_THIS(serverdescription);
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)
{
PHONGO_INTERN_FROM_THIS(serverdescription);
int64_t last_update_time;
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)
{
PHONGO_INTERN_FROM_THIS(serverdescription);
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)
{
PHONGO_INTERN_FROM_THIS(serverdescription);
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)
{
PHONGO_INTERN_FROM_THIS(serverdescription);
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRING(mongoc_server_description_type(intern->server_description));
}
/* MongoDB\Driver\ServerDescription object handlers */
static zend_object_handlers phongo_handler_serverdescription;
static void phongo_serverdescription_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(serverdescription, object);
zend_object_std_dtor(&intern->std);
if (intern->properties) {
zend_hash_release(intern->properties);
}
if (intern->server_description) {
mongoc_server_description_destroy(intern->server_description);
}
}
static zend_object* phongo_serverdescription_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(serverdescription, class_type);
intern->std.handlers = &phongo_handler_serverdescription;
return &intern->std;
}
HashTable* phongo_serverdescription_get_properties_hash(zend_object* object, bool is_debug)
{
PHONGO_INTERN_FROM_Z_OBJ(serverdescription, object);
HashTable* props;
PHONGO_GET_PROPERTY_HASH_INIT_PROPS(is_debug, intern, props, 6);
if (!intern->server_description) {
return props;
}
{
zval host, port, type;
const 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);
phongo_bson_state state;
PHONGO_BSON_INIT_DEBUG_STATE(state);
if (!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* phongo_serverdescription_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return phongo_serverdescription_get_properties_hash(object, true);
}
static HashTable* phongo_serverdescription_get_properties(zend_object* object)
{
return phongo_serverdescription_get_properties_hash(object, false);
}
void phongo_serverdescription_init_ce(INIT_FUNC_ARGS)
{
phongo_serverdescription_ce = register_class_MongoDB_Driver_ServerDescription();
phongo_serverdescription_ce->create_object = phongo_serverdescription_create_object;
memcpy(&phongo_handler_serverdescription, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_serverdescription.get_debug_info = phongo_serverdescription_get_debug_info;
phongo_handler_serverdescription.get_properties = phongo_serverdescription_get_properties;
phongo_handler_serverdescription.free_obj = phongo_serverdescription_free_object;
phongo_handler_serverdescription.offset = offsetof(phongo_serverdescription_t, std);
}
void phongo_serverdescription_init_ex(zval* return_value, mongoc_server_description_t* server_description, bool copy)
{
PHONGO_INTERN_INIT_EX(serverdescription, return_value);
intern->server_description = copy ? mongoc_server_description_new_copy(server_description) : server_description;
}
phongo_server_description_type_t 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, phongo_server_description_type_map[i].name)) {
return phongo_server_description_type_map[i].type;
}
}
return PHONGO_SERVER_UNKNOWN;
}
mongodb-2.5.5/src/MongoDB/ServerDescription.h 0000644 0001751 0001751 00000005030 15264101572 015772 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,
} phongo_server_description_type_t;
typedef struct {
phongo_server_description_type_t type;
const char* name;
} phongo_server_description_type_map_t;
extern phongo_server_description_type_map_t 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)
phongo_server_description_type_t phongo_server_description_type(mongoc_server_description_t* sd);
#endif /* PHONGO_SERVERDESCRIPTION_H */
mongodb-2.5.5/src/MongoDB/ServerDescription_arginfo.h 0000644 0001751 0001751 00000020774 15264101572 017513 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 471e09dc661f1a128415738d3204bb1fa30909ab */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
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.5.5/src/MongoDB/Server_arginfo.h 0000644 0001751 0001751 00000026565 15264101572 015313 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: bb19c587cfdda8bcc988184a2ae6256ffcdfbcd0 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
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.5.5/src/MongoDB/Session.c 0000644 0001751 0001751 00000047164 15264101572 013754 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 "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* 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 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* 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 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)
{
PHONGO_INTERN_FROM_THIS(session);
zval* zcluster_time;
bson_t cluster_time = BSON_INITIALIZER;
SESSION_CHECK_LIVELINESS(intern, "advanceClusterTime")
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY_OR_OBJECT(zcluster_time)
PHONGO_PARSE_PARAMETERS_END();
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)
{
PHONGO_INTERN_FROM_THIS(session);
zval* ztimestamp;
uint32_t timestamp = 0;
uint32_t increment = 0;
SESSION_CHECK_LIVELINESS(intern, "advanceOperationTime")
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_OBJECT_OF_CLASS(ztimestamp, phongo_timestamp_interface_ce)
PHONGO_PARSE_PARAMETERS_END();
if (!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)
{
PHONGO_INTERN_FROM_THIS(session);
const bson_t* cluster_time;
phongo_bson_state state;
PHONGO_BSON_INIT_NO_ODM_STATE(state);
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 (!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)
{
PHONGO_INTERN_FROM_THIS(session);
const bson_t* lsid;
phongo_bson_state state;
PHONGO_BSON_INIT_NO_ODM_STATE(state);
SESSION_CHECK_LIVELINESS(intern, "getLogicalSessionId")
PHONGO_PARSE_PARAMETERS_NONE();
lsid = mongoc_client_session_get_lsid(intern->client_session);
if (!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)
{
PHONGO_INTERN_FROM_THIS(session);
uint32_t timestamp, increment;
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)
{
PHONGO_INTERN_FROM_THIS(session);
uint32_t server_id = 0;
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)
{
PHONGO_INTERN_FROM_THIS(session);
SESSION_CHECK_LIVELINESS(intern, "getTransactionOptions")
PHONGO_PARSE_PARAMETERS_NONE();
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)
{
PHONGO_INTERN_FROM_THIS(session);
const char* state;
SESSION_CHECK_LIVELINESS(intern, "getTransactionState")
PHONGO_PARSE_PARAMETERS_NONE();
state = 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), phongo_readconcern_ce)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"readConcern\" option to be %s, %s given", ZSTR_VAL(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), phongo_readpreference_ce)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"readPreference\" option to be %s, %s given", ZSTR_VAL(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), phongo_writeconcern_ce)) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "Expected \"writeConcern\" option to be %s, %s given", ZSTR_VAL(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)
{
PHONGO_INTERN_FROM_THIS(session);
zval* options = NULL;
mongoc_transaction_opt_t* txn_options = NULL;
bson_error_t error;
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)
{
PHONGO_INTERN_FROM_THIS(session);
bson_error_t error;
bson_t reply;
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)
{
PHONGO_INTERN_FROM_THIS(session);
bson_error_t error;
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)
{
PHONGO_INTERN_FROM_THIS(session);
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)
{
PHONGO_INTERN_FROM_THIS(session);
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)
{
PHONGO_INTERN_FROM_THIS(session);
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 phongo_handler_session;
static void phongo_session_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_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* phongo_session_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(session, class_type);
PHONGO_SET_CREATED_BY_PID(intern);
intern->std.handlers = &phongo_handler_session;
return &intern->std;
}
static HashTable* phongo_session_get_debug_info(zend_object* object, int* is_temp)
{
PHONGO_INTERN_FROM_Z_OBJ(session, object);
zval retval = ZVAL_STATIC_INIT;
*is_temp = 1;
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);
phongo_bson_state state;
PHONGO_BSON_INIT_DEBUG_STATE(state);
if (!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) {
phongo_bson_state state;
PHONGO_BSON_INIT_DEBUG_STATE(state);
if (!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 = 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;
phongo_transaction_options_to_zval(intern->client_session, &txn_opts);
ADD_ASSOC_ZVAL_EX(&retval, "transactionOptions", &txn_opts);
}
done:
return Z_ARRVAL(retval);
}
void phongo_session_init_ce(INIT_FUNC_ARGS)
{
phongo_session_ce = register_class_MongoDB_Driver_Session();
phongo_session_ce->create_object = phongo_session_create_object;
memcpy(&phongo_handler_session, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_session.get_debug_info = phongo_session_get_debug_info;
phongo_handler_session.free_obj = phongo_session_free_object;
phongo_handler_session.offset = offsetof(phongo_session_t, std);
}
void phongo_session_init(zval* return_value, zval* manager, mongoc_client_session_t* client_session)
{
phongo_session_t* session;
object_init_ex(return_value, phongo_session_ce);
session = Z_SESSION_OBJ_P(return_value);
session->client_session = client_session;
ZVAL_ZVAL(&session->manager, manager, 1, 0);
}
mongodb-2.5.5/src/MongoDB/Session.h 0000644 0001751 0001751 00000002254 15264101572 013750 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.5.5/src/MongoDB/Session_arginfo.h 0000644 0001751 0001751 00000021160 15264101572 015452 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: f42d4c319eca5db335af6effdc192cab17d225e9 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
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.5.5/src/MongoDB/TopologyDescription.c 0000644 0001751 0001751 00000013551 15264101572 016342 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 "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* 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)
{
PHONGO_INTERN_FROM_THIS(topologydescription);
mongoc_server_description_t** sds;
size_t i, n = 0;
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)
{
PHONGO_INTERN_FROM_THIS(topologydescription);
const mongoc_read_prefs_t* read_preference = NULL;
zval* z_read_preference = NULL;
PHONGO_PARSE_PARAMETERS_START(0, 1)
Z_PARAM_OPTIONAL
Z_PARAM_OBJECT_OF_CLASS(z_read_preference, 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)
{
PHONGO_INTERN_FROM_THIS(topologydescription);
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)
{
PHONGO_INTERN_FROM_THIS(topologydescription);
PHONGO_PARSE_PARAMETERS_NONE();
RETVAL_STRING(mongoc_topology_description_type(intern->topology_description));
}
/* MongoDB\Driver\TopologyDescription object handlers */
static zend_object_handlers phongo_handler_topologydescription;
static void phongo_topologydescription_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(topologydescription, object);
zend_object_std_dtor(&intern->std);
if (intern->properties) {
zend_hash_release(intern->properties);
}
if (intern->topology_description) {
mongoc_topology_description_destroy(intern->topology_description);
}
}
static zend_object* phongo_topologydescription_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(topologydescription, class_type);
intern->std.handlers = &phongo_handler_topologydescription;
return &intern->std;
}
HashTable* phongo_topologydescription_get_properties_hash(zend_object* object, bool is_debug)
{
PHONGO_INTERN_FROM_Z_OBJ(topologydescription, object);
HashTable* props;
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* phongo_topologydescription_get_debug_info(zend_object* object, int* is_temp)
{
*is_temp = 1;
return phongo_topologydescription_get_properties_hash(object, true);
}
static HashTable* phongo_topologydescription_get_properties(zend_object* object)
{
return phongo_topologydescription_get_properties_hash(object, false);
}
void phongo_topologydescription_init_ce(INIT_FUNC_ARGS)
{
phongo_topologydescription_ce = register_class_MongoDB_Driver_TopologyDescription();
phongo_topologydescription_ce->create_object = phongo_topologydescription_create_object;
memcpy(&phongo_handler_topologydescription, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_topologydescription.get_debug_info = phongo_topologydescription_get_debug_info;
phongo_handler_topologydescription.get_properties = phongo_topologydescription_get_properties;
phongo_handler_topologydescription.free_obj = phongo_topologydescription_free_object;
phongo_handler_topologydescription.offset = offsetof(phongo_topologydescription_t, std);
}
void phongo_topologydescription_init(zval* return_value, mongoc_topology_description_t* topology_description)
{
PHONGO_INTERN_INIT_EX(topologydescription, return_value);
intern->topology_description = mongoc_topology_description_new_copy(topology_description);
}
mongodb-2.5.5/src/MongoDB/TopologyDescription.h 0000644 0001751 0001751 00000002462 15264101572 016346 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.5.5/src/MongoDB/TopologyDescription_arginfo.h 0000644 0001751 0001751 00000014035 15264101572 020052 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: cb65bdadb0f057bdc4e88fd8e1e60c3ef52a2b69 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
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.5.5/src/MongoDB/WriteConcern.c 0000644 0001751 0001751 00000032004 15264101572 014716 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 "phongo.h"
#include "phongo_error.h"
#include "phongo_util.h"
#include "MongoDB/WriteConcern.h"
#include "WriteConcern_arginfo.h"
zend_class_entry* phongo_writeconcern_ce;
static void phongo_writeconcern_update_properties(phongo_writeconcern_t* intern)
{
const char* wtag = mongoc_write_concern_get_wtag(intern->write_concern);
int32_t w = mongoc_write_concern_get_w(intern->write_concern);
int64_t wtimeout = mongoc_write_concern_get_wtimeout_int64(intern->write_concern);
if (wtag) {
zend_update_property_string(phongo_writeconcern_ce, &intern->std, ZEND_STRL("w"), wtag);
} else if (mongoc_write_concern_get_wmajority(intern->write_concern)) {
zend_update_property_string(phongo_writeconcern_ce, &intern->std, ZEND_STRL("w"), PHONGO_WRITE_CONCERN_W_MAJORITY);
} else if (w != MONGOC_WRITE_CONCERN_W_DEFAULT) {
zend_update_property_long(phongo_writeconcern_ce, &intern->std, ZEND_STRL("w"), w);
} else {
zend_update_property_null(phongo_writeconcern_ce, &intern->std, ZEND_STRL("w"));
}
if (mongoc_write_concern_journal_is_set(intern->write_concern)) {
zend_update_property_bool(phongo_writeconcern_ce, &intern->std, ZEND_STRL("j"), mongoc_write_concern_get_journal(intern->write_concern));
} else {
zend_update_property_null(phongo_writeconcern_ce, &intern->std, ZEND_STRL("j"));
}
#if SIZEOF_ZEND_LONG == 4
if (wtimeout > INT32_MAX || wtimeout < INT32_MIN) {
zend_update_property_long(phongo_writeconcern_ce, &intern->std, ZEND_STRL("wtimeout"), (zend_long) INT32_MAX);
} else {
zend_update_property_long(phongo_writeconcern_ce, &intern->std, ZEND_STRL("wtimeout"), (zend_long) wtimeout);
}
#else
zend_update_property_long(phongo_writeconcern_ce, &intern->std, ZEND_STRL("wtimeout"), (zend_long) wtimeout);
#endif
}
/* Initialize the object from a HashTable and return whether it was successful.
* An exception will be thrown on error. */
static bool phongo_writeconcern_init_from_hash(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(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 if (Z_TYPE_P(w) != IS_NULL) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"w\" field to be integer or string", ZSTR_VAL(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(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 (!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(phongo_writeconcern_ce->name));
return false;
}
mongoc_write_concern_set_wtimeout_int64(intern->write_concern, timeout);
} else if (Z_TYPE_P(wtimeout) != IS_NULL) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"wtimeout\" field to be integer or string", ZSTR_VAL(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)) {
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 if (Z_TYPE_P(j) != IS_NULL) {
phongo_throw_exception(PHONGO_ERROR_INVALID_ARGUMENT, "%s initialization requires \"j\" field to be boolean", ZSTR_VAL(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;
}
phongo_writeconcern_update_properties(intern);
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)
{
PHONGO_INTERN_FROM_THIS(writeconcern);
zval * w, *journal = NULL;
zend_long wtimeout = 0;
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)) {
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;
}
phongo_writeconcern_update_properties(intern);
}
static PHP_METHOD(MongoDB_Driver_WriteConcern, __set_state)
{
HashTable* props;
zval* array;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(array)
PHONGO_PARSE_PARAMETERS_END();
PHONGO_INTERN_INIT_EX(writeconcern, return_value);
props = Z_ARRVAL_P(array);
phongo_writeconcern_init_from_hash(intern, props);
}
/* Returns the WriteConcern "w" option */
static PHP_METHOD(MongoDB_Driver_WriteConcern, getW)
{
PHONGO_INTERN_FROM_THIS(writeconcern);
const char* wtag;
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)
{
PHONGO_INTERN_FROM_THIS(writeconcern);
int64_t wtimeout;
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)
{
PHONGO_INTERN_FROM_THIS(writeconcern);
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)
{
PHONGO_INTERN_FROM_THIS(writeconcern);
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_BOOL(mongoc_write_concern_is_default(intern->write_concern));
}
static PHP_METHOD(MongoDB_Driver_WriteConcern, bsonSerialize)
{
PHONGO_INTERN_FROM_THIS(writeconcern);
const char* wtag;
int32_t w;
int64_t wtimeout;
PHONGO_PARSE_PARAMETERS_NONE();
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);
array_init_size(return_value, 3);
if (wtag) {
ADD_ASSOC_STRING(return_value, "w", wtag);
} else if (mongoc_write_concern_get_wmajority(intern->write_concern)) {
ADD_ASSOC_STRING(return_value, "w", PHONGO_WRITE_CONCERN_W_MAJORITY);
} else if (w != MONGOC_WRITE_CONCERN_W_DEFAULT) {
ADD_ASSOC_LONG_EX(return_value, "w", w);
}
if (mongoc_write_concern_journal_is_set(intern->write_concern)) {
ADD_ASSOC_BOOL_EX(return_value, "j", mongoc_write_concern_get_journal(intern->write_concern));
}
if (wtimeout != 0) {
ADD_ASSOC_INT64(return_value, "wtimeout", wtimeout);
}
convert_to_object(return_value);
}
static PHP_METHOD(MongoDB_Driver_WriteConcern, __unserialize)
{
zval* data;
PHONGO_PARSE_PARAMETERS_START(1, 1)
Z_PARAM_ARRAY(data)
PHONGO_PARSE_PARAMETERS_END();
phongo_writeconcern_init_from_hash(Z_WRITECONCERN_OBJ_P(getThis()), Z_ARRVAL_P(data));
}
/* MongoDB\Driver\WriteConcern object handlers */
static zend_object_handlers phongo_handler_writeconcern;
static void phongo_writeconcern_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(writeconcern, object);
zend_object_std_dtor(&intern->std);
if (intern->write_concern) {
mongoc_write_concern_destroy(intern->write_concern);
}
}
static zend_object* phongo_writeconcern_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(writeconcern, class_type);
intern->std.handlers = &phongo_handler_writeconcern;
return &intern->std;
}
static zend_object* phongo_writeconcern_clone_object(zend_object* object)
{
PHONGO_INTERN_FROM_Z_OBJ(writeconcern, object);
phongo_writeconcern_t* new_intern;
zend_object* new_object;
new_object = phongo_writeconcern_create_object(object->ce);
new_intern = Z_OBJ_WRITECONCERN(new_object);
zend_objects_clone_members(&new_intern->std, &intern->std);
new_intern->write_concern = mongoc_write_concern_copy(intern->write_concern);
return new_object;
}
void phongo_writeconcern_init_ce(INIT_FUNC_ARGS)
{
phongo_writeconcern_ce = register_class_MongoDB_Driver_WriteConcern(phongo_serializable_ce);
phongo_writeconcern_ce->create_object = phongo_writeconcern_create_object;
memcpy(&phongo_handler_writeconcern, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_writeconcern.clone_obj = phongo_writeconcern_clone_object;
phongo_handler_writeconcern.free_obj = phongo_writeconcern_free_object;
phongo_handler_writeconcern.offset = offsetof(phongo_writeconcern_t, std);
}
void phongo_writeconcern_init(zval* return_value, const mongoc_write_concern_t* write_concern)
{
PHONGO_INTERN_INIT_EX(writeconcern, return_value);
intern->write_concern = mongoc_write_concern_copy(write_concern);
phongo_writeconcern_update_properties(intern);
}
const mongoc_write_concern_t* phongo_write_concern_from_zval(zval* zwrite_concern)
{
if (zwrite_concern) {
PHONGO_INTERN_FROM_ZVAL(writeconcern, zwrite_concern);
if (intern) {
return intern->write_concern;
}
}
return NULL;
}
mongodb-2.5.5/src/MongoDB/WriteConcern.h 0000644 0001751 0001751 00000001724 15264101572 014730 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);
#endif /* PHONGO_WRITECONCERN_H */
mongodb-2.5.5/src/MongoDB/WriteConcernError.c 0000644 0001751 0001751 00000006767 15264101572 015751 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 "phongo.h"
#include "phongo_error.h"
#include "MongoDB/WriteConcernError.h"
#include "WriteConcernError_arginfo.h"
zend_class_entry* phongo_writeconcernerror_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_WriteConcernError)
PHONGO_PROPERTY_GETTER(MongoDB_Driver_WriteConcernError, getCode, writeconcernerror, "code")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_WriteConcernError, getMessage, writeconcernerror, "message")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_WriteConcernError, getInfo, writeconcernerror, "info")
static bool phongo_writeconcernerror_update_properties(zend_object* object, const bson_t* bson)
{
bson_iter_t iter;
if (bson_iter_init_find(&iter, bson, "code") && BSON_ITER_HOLDS_INT32(&iter)) {
zend_update_property_long(phongo_writeconcernerror_ce, object, ZEND_STRL("code"), bson_iter_int32(&iter));
} else {
zend_update_property_long(phongo_writeconcernerror_ce, object, ZEND_STRL("code"), 0);
}
// 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* message = bson_iter_utf8(&iter, &errmsg_len);
zend_update_property_string(phongo_writeconcernerror_ce, object, ZEND_STRL("message"), message ? message : "");
} else {
zend_update_property_string(phongo_writeconcernerror_ce, object, ZEND_STRL("message"), "");
}
// 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;
zval zinfo;
bson_iter_document(&iter, &len, &data);
if (!phongo_bson_data_to_zval_internal(data, len, &zinfo)) {
/* Exception already thrown */
zval_ptr_dtor(&zinfo);
return false;
}
zend_update_property(phongo_writeconcernerror_ce, object, ZEND_STRL("info"), &zinfo);
zval_ptr_dtor(&zinfo);
} else {
zend_update_property_null(phongo_writeconcernerror_ce, object, ZEND_STRL("info"));
}
return true;
}
void phongo_writeconcernerror_init_ce(INIT_FUNC_ARGS)
{
phongo_writeconcernerror_ce = register_class_MongoDB_Driver_WriteConcernError();
}
/* 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)
{
PHONGO_OBJECT_INIT_EX(writeconcernerror, return_value);
return phongo_writeconcernerror_update_properties(object, bson);
}
mongodb-2.5.5/src/MongoDB/WriteConcernError.h 0000644 0001751 0001751 00000001502 15264101572 015734 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.5.5/src/MongoDB/WriteConcernError_arginfo.h 0000644 0001751 0001751 00000005770 15264101572 017454 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: f215bf4fccd5214875964d0f557ff2e923b61812 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
zval property_message_default_value;
ZVAL_UNDEF(&property_message_default_value);
zend_declare_typed_property(class_entry, ZSTR_KNOWN(ZEND_STR_MESSAGE), &property_message_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zval property_code_default_value;
ZVAL_UNDEF(&property_code_default_value);
zend_declare_typed_property(class_entry, ZSTR_KNOWN(ZEND_STR_CODE), &property_code_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zval property_info_default_value;
ZVAL_UNDEF(&property_info_default_value);
zend_string *property_info_name = zend_string_init("info", sizeof("info") - 1, 1);
zend_declare_typed_property(class_entry, property_info_name, &property_info_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_OBJECT|MAY_BE_NULL));
zend_string_release(property_info_name);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/WriteConcern_arginfo.h 0000644 0001751 0001751 00000012523 15264101572 016434 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: ad76e5683d263a0f0f0f07099d651dc8afd25199 */
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()
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 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_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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL;
#endif
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);
zval property_w_default_value;
ZVAL_UNDEF(&property_w_default_value);
zend_string *property_w_name = zend_string_init("w", sizeof("w") - 1, 1);
zend_declare_typed_property(class_entry, property_w_name, &property_w_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING|MAY_BE_LONG|MAY_BE_NULL));
zend_string_release(property_w_name);
zval property_j_default_value;
ZVAL_UNDEF(&property_j_default_value);
zend_string *property_j_name = zend_string_init("j", sizeof("j") - 1, 1);
zend_declare_typed_property(class_entry, property_j_name, &property_j_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_BOOL|MAY_BE_NULL));
zend_string_release(property_j_name);
zval property_wtimeout_default_value;
ZVAL_UNDEF(&property_wtimeout_default_value);
zend_string *property_wtimeout_name = zend_string_init("wtimeout", sizeof("wtimeout") - 1, 1);
zend_declare_typed_property(class_entry, property_wtimeout_name, &property_wtimeout_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_wtimeout_name);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/WriteError.c 0000644 0001751 0001751 00000010064 15264101572 014422 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 "phongo.h"
#include "phongo_error.h"
#include "MongoDB/WriteError.h"
#include "WriteError_arginfo.h"
zend_class_entry* phongo_writeerror_ce;
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_WriteError)
PHONGO_PROPERTY_GETTER(MongoDB_Driver_WriteError, getCode, writeerror, "code")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_WriteError, getIndex, writeerror, "index")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_WriteError, getMessage, writeerror, "message")
PHONGO_PROPERTY_GETTER(MongoDB_Driver_WriteError, getInfo, writeerror, "info")
static bool phongo_writeerror_update_properties(zend_object* object, const bson_t* bson, int32_t index)
{
bson_iter_t iter;
if (bson_iter_init_find(&iter, bson, "code") && BSON_ITER_HOLDS_INT32(&iter)) {
zend_update_property_long(phongo_writeerror_ce, object, ZEND_STRL("code"), bson_iter_int32(&iter));
} else {
zend_update_property_long(phongo_writeerror_ce, object, ZEND_STRL("code"), 0);
}
// 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* message = bson_iter_utf8(&iter, &errmsg_len);
zend_update_property_string(phongo_writeerror_ce, object, ZEND_STRL("message"), message ? message : "");
} else {
zend_update_property_string(phongo_writeerror_ce, object, ZEND_STRL("message"), "");
}
// 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;
zval zinfo;
bson_iter_document(&iter, &len, &data);
if (!phongo_bson_data_to_zval_internal(data, len, &zinfo)) {
/* Exception already thrown */
zval_ptr_dtor(&zinfo);
return false;
}
zend_update_property(phongo_writeerror_ce, object, ZEND_STRL("info"), &zinfo);
zval_ptr_dtor(&zinfo);
} else {
zend_update_property_null(phongo_writeerror_ce, object, ZEND_STRL("info"));
}
/* If the WriteError is initialized from mongoc_bulkwriteexception_t, an
* index should already have been specified. */
if (!index && bson_iter_init_find(&iter, bson, "index") && BSON_ITER_HOLDS_INT32(&iter)) {
index = bson_iter_int32(&iter);
}
zend_update_property_long(phongo_writeerror_ce, object, ZEND_STRL("index"), index);
return true;
}
void phongo_writeerror_init_ce(INIT_FUNC_ARGS)
{
phongo_writeerror_ce = register_class_MongoDB_Driver_WriteError();
}
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)
{
PHONGO_OBJECT_INIT_EX(writeerror, return_value);
return phongo_writeerror_update_properties(object, bson, index);
}
mongodb-2.5.5/src/MongoDB/WriteError.h 0000644 0001751 0001751 00000001575 15264101572 014436 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.5.5/src/MongoDB/WriteError_arginfo.h 0000644 0001751 0001751 00000007030 15264101572 016133 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 8a43b466269b8d85a2e790f69f0ec2e2cc3e4066 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
zval property_message_default_value;
ZVAL_UNDEF(&property_message_default_value);
zend_declare_typed_property(class_entry, ZSTR_KNOWN(ZEND_STR_MESSAGE), &property_message_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_STRING));
zval property_code_default_value;
ZVAL_UNDEF(&property_code_default_value);
zend_declare_typed_property(class_entry, ZSTR_KNOWN(ZEND_STR_CODE), &property_code_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zval property_index_default_value;
ZVAL_UNDEF(&property_index_default_value);
zend_string *property_index_name = zend_string_init("index", sizeof("index") - 1, 1);
zend_declare_typed_property(class_entry, property_index_name, &property_index_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG));
zend_string_release(property_index_name);
zval property_info_default_value;
ZVAL_UNDEF(&property_info_default_value);
zend_string *property_info_name = zend_string_init("info", sizeof("info") - 1, 1);
zend_declare_typed_property(class_entry, property_info_name, &property_info_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_OBJECT|MAY_BE_NULL));
zend_string_release(property_info_name);
return class_entry;
}
mongodb-2.5.5/src/MongoDB/WriteResult.c 0000644 0001751 0001751 00000032677 15264101572 014625 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 "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);
#define PHONGO_WRITERESULT_UPDATE_PROP(prop, field) \
if (mongoc_write_concern_is_acknowledged(intern->write_concern) && bson_iter_init_find(&iter, intern->reply, (field)) && BSON_ITER_HOLDS_INT32(&iter)) { \
zend_update_property_long(phongo_writeresult_ce, &intern->std, ZEND_STRL(prop), bson_iter_int32(&iter)); \
} else { \
zend_update_property_null(phongo_writeresult_ce, &intern->std, ZEND_STRL(prop)); \
}
zend_class_entry* 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(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(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 phongo_writeresult_get_error_replies(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);
phongo_bson_data_to_zval_internal(data, len, &error_reply);
add_next_index_zval(return_value, &error_reply);
}
}
return true;
}
static void phongo_writeresult_get_upserted_ids(phongo_writeresult_t* intern, zval* return_value)
{
bson_iter_t iter, child;
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;
phongo_bson_state state;
/* Use PHONGO_TYPEMAP_NATIVE_ARRAY for the root type so we can
* easily access the "index" and "_id" fields. Only the root type is
* overridden, so suppress ODM inference for the "_id" document
* rather than also forcing a document type. */
PHONGO_BSON_INIT_STATE(state);
state.map.root.type = PHONGO_TYPEMAP_NATIVE_ARRAY;
state.skip_odm = true;
if (!BSON_ITER_HOLDS_DOCUMENT(&child)) {
continue;
}
bson_iter_document(&child, &data_len, &data);
if (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);
}
}
}
PHONGO_DISABLED_CONSTRUCTOR(MongoDB_Driver_WriteResult)
/* Returns the number of documents that were inserted */
static PHP_METHOD(MongoDB_Driver_WriteResult, getInsertedCount)
{
PHONGO_INTERN_FROM_THIS(writeresult);
bson_iter_t iter;
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)
{
PHONGO_INTERN_FROM_THIS(writeresult);
bson_iter_t iter;
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)
{
PHONGO_INTERN_FROM_THIS(writeresult);
bson_iter_t iter;
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)
{
PHONGO_INTERN_FROM_THIS(writeresult);
bson_iter_t iter;
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)
{
PHONGO_INTERN_FROM_THIS(writeresult);
bson_iter_t iter;
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)
{
PHONGO_INTERN_FROM_THIS(writeresult);
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)
{
PHONGO_INTERN_FROM_THIS(writeresult);
PHONGO_PARSE_PARAMETERS_NONE();
PHONGO_WRITERESULT_CHECK_ACKNOWLEDGED("getUpsertedIds");
phongo_writeresult_get_upserted_ids(intern, return_value);
}
/* Return any write concern error that occurred */
static PHP_METHOD(MongoDB_Driver_WriteResult, getWriteConcernError)
{
PHONGO_INTERN_FROM_THIS(writeresult);
PHONGO_PARSE_PARAMETERS_NONE();
phongo_writeresult_get_writeconcernerror(intern, return_value);
}
/* Returns any write errors that occurred */
static PHP_METHOD(MongoDB_Driver_WriteResult, getWriteErrors)
{
PHONGO_INTERN_FROM_THIS(writeresult);
PHONGO_PARSE_PARAMETERS_NONE();
phongo_writeresult_get_writeerrors(intern, return_value);
}
static PHP_METHOD(MongoDB_Driver_WriteResult, getErrorReplies)
{
PHONGO_INTERN_FROM_THIS(writeresult);
PHONGO_PARSE_PARAMETERS_NONE();
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)
{
PHONGO_INTERN_FROM_THIS(writeresult);
PHONGO_PARSE_PARAMETERS_NONE();
RETURN_BOOL(mongoc_write_concern_is_acknowledged(intern->write_concern));
}
/* MongoDB\Driver\WriteResult object handlers */
static zend_object_handlers phongo_handler_writeresult;
static void phongo_writeresult_free_object(zend_object* object)
{
PHONGO_INTERN_FROM_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* phongo_writeresult_create_object(zend_class_entry* class_type)
{
PHONGO_INTERN_OBJECT_ALLOC(writeresult, class_type);
intern->std.handlers = &phongo_handler_writeresult;
return &intern->std;
}
static void phongo_writeresult_update_properties(phongo_writeresult_t* intern)
{
bson_iter_t iter;
PHONGO_WRITERESULT_UPDATE_PROP("insertedCount", "nInserted");
PHONGO_WRITERESULT_UPDATE_PROP("matchedCount", "nMatched");
PHONGO_WRITERESULT_UPDATE_PROP("modifiedCount", "nModified");
PHONGO_WRITERESULT_UPDATE_PROP("deletedCount", "nRemoved");
PHONGO_WRITERESULT_UPDATE_PROP("upsertedCount", "nUpserted");
{
zval upsertedIds;
phongo_writeresult_get_upserted_ids(intern, &upsertedIds);
zend_update_property(phongo_writeresult_ce, &intern->std, ZEND_STRL("upsertedIds"), &upsertedIds);
zval_ptr_dtor(&upsertedIds);
}
{
zval writeerrors;
phongo_writeresult_get_writeerrors(intern, &writeerrors);
zend_update_property(phongo_writeresult_ce, &intern->std, ZEND_STRL("writeErrors"), &writeerrors);
zval_ptr_dtor(&writeerrors);
}
{
zval writeconcernerror;
phongo_writeresult_get_writeconcernerror(intern, &writeconcernerror);
zend_update_property(phongo_writeresult_ce, &intern->std, ZEND_STRL("writeConcernError"), &writeconcernerror);
zval_ptr_dtor(&writeconcernerror);
}
if (intern->write_concern) {
zval write_concern;
phongo_writeconcern_init(&write_concern, intern->write_concern);
zend_update_property(phongo_writeresult_ce, &intern->std, ZEND_STRL("writeConcern"), &write_concern);
zval_ptr_dtor(&write_concern);
} else {
zend_update_property_null(phongo_writeresult_ce, &intern->std, ZEND_STRL("writeConcern"));
}
{
zval error_replies;
phongo_writeresult_get_error_replies(intern, &error_replies);
zend_update_property(phongo_writeresult_ce, &intern->std, ZEND_STRL("errorReplies"), &error_replies);
zval_ptr_dtor(&error_replies);
}
{
zval server;
phongo_server_init(&server, &intern->manager, intern->server_id);
zend_update_property(phongo_writeresult_ce, &intern->std, ZEND_STRL("server"), &server);
zval_ptr_dtor(&server);
}
}
void phongo_writeresult_init_ce(INIT_FUNC_ARGS)
{
phongo_writeresult_ce = register_class_MongoDB_Driver_WriteResult();
phongo_writeresult_ce->create_object = phongo_writeresult_create_object;
memcpy(&phongo_handler_writeresult, phongo_get_std_object_handlers(), sizeof(zend_object_handlers));
phongo_handler_writeresult.free_obj = phongo_writeresult_free_object;
phongo_handler_writeresult.offset = offsetof(phongo_writeresult_t, std);
}
void phongo_writeresult_init(zval* return_value, bson_t* reply, zval* manager, uint32_t server_id, const mongoc_write_concern_t* write_concern)
{
phongo_writeresult_t* writeresult;
object_init_ex(return_value, phongo_writeresult_ce);
writeresult = Z_WRITERESULT_OBJ_P(return_value);
writeresult->reply = bson_copy(reply);
writeresult->server_id = server_id;
writeresult->write_concern = mongoc_write_concern_copy(write_concern);
ZVAL_ZVAL(&writeresult->manager, manager, 1, 0);
phongo_writeresult_update_properties(writeresult);
}
#undef PHONGO_WRITERESULT_CHECK_ACKNOWLEDGED
#undef PHONGO_WRITERESULT_RETURN_LONG_FROM_BSON_INT32
#undef PHONGO_WRITERESULT_UPDATE_PROP
mongodb-2.5.5/src/MongoDB/WriteResult.h 0000644 0001751 0001751 00000001622 15264101572 014614 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"
void phongo_writeresult_init(zval* return_value, bson_t* reply, zval* manager, uint32_t server_id, const mongoc_write_concern_t* write_concern);
#endif /* PHONGO_WRITERESULT_H */
mongodb-2.5.5/src/MongoDB/WriteResult_arginfo.h 0000644 0001751 0001751 00000024360 15264101572 016325 0 ustar /* This is a generated file, edit the .stub.php file instead.
* Stub hash: 75d0ae9c2264b5e833f49af96ba474a64ce56bc3 */
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);
#if (PHP_VERSION_ID >= 80400)
class_entry = zend_register_internal_class_with_flags(&ce, NULL, ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE);
#else
class_entry = zend_register_internal_class_ex(&ce, NULL);
class_entry->ce_flags |= ZEND_ACC_FINAL|ZEND_ACC_NOT_SERIALIZABLE;
#endif
zval property_insertedCount_default_value;
ZVAL_UNDEF(&property_insertedCount_default_value);
zend_string *property_insertedCount_name = zend_string_init("insertedCount", sizeof("insertedCount") - 1, 1);
zend_declare_typed_property(class_entry, property_insertedCount_name, &property_insertedCount_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG|MAY_BE_NULL));
zend_string_release(property_insertedCount_name);
zval property_matchedCount_default_value;
ZVAL_UNDEF(&property_matchedCount_default_value);
zend_string *property_matchedCount_name = zend_string_init("matchedCount", sizeof("matchedCount") - 1, 1);
zend_declare_typed_property(class_entry, property_matchedCount_name, &property_matchedCount_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG|MAY_BE_NULL));
zend_string_release(property_matchedCount_name);
zval property_modifiedCount_default_value;
ZVAL_UNDEF(&property_modifiedCount_default_value);
zend_string *property_modifiedCount_name = zend_string_init("modifiedCount", sizeof("modifiedCount") - 1, 1);
zend_declare_typed_property(class_entry, property_modifiedCount_name, &property_modifiedCount_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG|MAY_BE_NULL));
zend_string_release(property_modifiedCount_name);
zval property_deletedCount_default_value;
ZVAL_UNDEF(&property_deletedCount_default_value);
zend_string *property_deletedCount_name = zend_string_init("deletedCount", sizeof("deletedCount") - 1, 1);
zend_declare_typed_property(class_entry, property_deletedCount_name, &property_deletedCount_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG|MAY_BE_NULL));
zend_string_release(property_deletedCount_name);
zval property_upsertedCount_default_value;
ZVAL_UNDEF(&property_upsertedCount_default_value);
zend_string *property_upsertedCount_name = zend_string_init("upsertedCount", sizeof("upsertedCount") - 1, 1);
zend_declare_typed_property(class_entry, property_upsertedCount_name, &property_upsertedCount_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_LONG|MAY_BE_NULL));
zend_string_release(property_upsertedCount_name);
zval property_server_default_value;
ZVAL_UNDEF(&property_server_default_value);
zend_string *property_server_name = zend_string_init("server", sizeof("server") - 1, 1);
zend_string *property_server_class_MongoDB_Driver_Server = zend_string_init("MongoDB\\Driver\\Server", sizeof("MongoDB\\Driver\\Server")-1, 1);
zend_declare_typed_property(class_entry, property_server_name, &property_server_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_server_class_MongoDB_Driver_Server, 0, 0));
zend_string_release(property_server_name);
zval property_upsertedIds_default_value;
ZVAL_UNDEF(&property_upsertedIds_default_value);
zend_string *property_upsertedIds_name = zend_string_init("upsertedIds", sizeof("upsertedIds") - 1, 1);
zend_declare_typed_property(class_entry, property_upsertedIds_name, &property_upsertedIds_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_ARRAY));
zend_string_release(property_upsertedIds_name);
zval property_writeErrors_default_value;
ZVAL_UNDEF(&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_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_ARRAY));
zend_string_release(property_writeErrors_name);
zval property_writeConcernError_default_value;
ZVAL_UNDEF(&property_writeConcernError_default_value);
zend_string *property_writeConcernError_name = zend_string_init("writeConcernError", sizeof("writeConcernError") - 1, 1);
zend_string *property_writeConcernError_class_MongoDB_Driver_WriteConcernError = zend_string_init("MongoDB\\Driver\\WriteConcernError", sizeof("MongoDB\\Driver\\WriteConcernError")-1, 1);
zend_declare_typed_property(class_entry, property_writeConcernError_name, &property_writeConcernError_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_writeConcernError_class_MongoDB_Driver_WriteConcernError, 0, MAY_BE_NULL));
zend_string_release(property_writeConcernError_name);
zval property_writeConcern_default_value;
ZVAL_UNDEF(&property_writeConcern_default_value);
zend_string *property_writeConcern_name = zend_string_init("writeConcern", sizeof("writeConcern") - 1, 1);
zend_string *property_writeConcern_class_MongoDB_Driver_WriteConcern = zend_string_init("MongoDB\\Driver\\WriteConcern", sizeof("MongoDB\\Driver\\WriteConcern")-1, 1);
zend_declare_typed_property(class_entry, property_writeConcern_name, &property_writeConcern_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_CLASS(property_writeConcern_class_MongoDB_Driver_WriteConcern, 0, MAY_BE_NULL));
zend_string_release(property_writeConcern_name);
zval property_errorReplies_default_value;
ZVAL_UNDEF(&property_errorReplies_default_value);
zend_string *property_errorReplies_name = zend_string_init("errorReplies", sizeof("errorReplies") - 1, 1);
zend_declare_typed_property(class_entry, property_errorReplies_name, &property_errorReplies_default_value, ZEND_ACC_PUBLIC|ZEND_ACC_READONLY, NULL, (zend_type) ZEND_TYPE_INIT_MASK(MAY_BE_ARRAY));
zend_string_release(property_errorReplies_name);
return class_entry;
}
mongodb-2.5.5/src/contrib/php_array_api.h 0000644 0001751 0001751 00000047710 15264101572 015324 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 = ! ZSTR_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.5.5/src/libmongoc/src/common/src/mlib/ckdint.h 0000644 0001751 0001751 00000070241 15264101572 020057 0 ustar /**
* @file mlib/ckdint.h
* @brief Checked integer arithmetic
* @date 2025-02-04
*
* This file implements the C23 checked-integer-arithmetic functions as macros.
*
* The function-like macros are defined:
*
* - `mlib_add(Dst, L, R)` / `mlib_add(Dst, A)`
* - `mlib_sub(Dst, L, R)` / `mlib_sub(Dst, A)`
* - `mlib_mul(Dst, L, R)` / `mlib_mul(Dst, A)`
* - `mlib_narrow(Dst, V)` (not from stdckdint, but defined as `mlib_add(Dst, V, 0)`)
*
* Where `Dst` is a pointer to integral storage, and `L` and `R` are arbitrary
* integral expressions. The two-argument variants treat `Dst` as the left-hand
* operand for in-place arithmetic.
*
* Each macro accepts arguments of arbitrary type at any position, and will "do
* the right thing", regardless of the parameter types. No funny integer promotion,
* sign extension, sign conversion, nor implicit narrowing. The macros return `false`
* if-and-only-if the result was lossless. They return `true` if-and-only-if the
* value written to `Dst` does not represent the true arithmetic result.
*
* The following additional macros are defined:
*
* - `mlib_assert_add(T, L, R)`
* - `mlib_assert_sub(T, L, R)`
* - `mlib_assert_mul(T, L, R)`
*
* Where `T` is an integer type. The macro will yield a value of that type, asserting
* that the operation on `L` and `R` does not overflow. If the operation overflows,
* the program will be terminated with a diagnostic to `stderr` pointing to the call site.
*
* For implementation details and a usage guide, see `ckdint.md`
*
* @copyright Copyright (c) 2025
*
* 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.
*/
#pragma once
#include
#include
#include
#include
#include
#include
#include
mlib_extern_c_begin();
/**
* @brief Perform integer addition
*
* @param Out A non-null pointer to a modifiable integer.
* @param A The left-hand addend of addition
* @param B The right-hand addend of addition
* @retval `true` if the value written to `Out` does not represent the true arithmetic sum.
* @retval `false` Otherwise.
*
* The sum `A + B` is written to `Out`. The operation is commutative.
*
* If the argument `B` is omitted, computes `*Out + A` (performs in-place addition).
*/
#define mlib_add(...) MLIB_ARGC_PICK(_mlib_ckdint, mlib_add, __VA_ARGS__)
/**
* @brief Perform integer subtraction
*
* @param Out A non-null pointer to a modifiable integer.
* @param A The left-hand operand of the subtraction (minuend)
* @param B The right-hand operand of subtraction (subtrahend)
* @retval `true` if the value written to `Out` does not represent the true arithmetic difference.
* @retval `false` Otherwise.
*
* The difference `A - B` will be written to `Out`.
*
* If the argument `B` is omitted, computes `*Out - A` (performs in-place subtraction)
*/
#define mlib_sub(...) MLIB_ARGC_PICK(_mlib_ckdint, mlib_sub, __VA_ARGS__)
/**
* @brief Perform integer multiplication
*
* @param Out A non-null pointer to a modifiable integer.
* @param A The left-hand factor of multiplication
* @param B The right-hand factor of multiplication
* @retval `true` if the value written to `Out` does not represent the true arithmetic product.
* @retval `false` Otherwise.
*
* The product `A × B` will be written to `Out`. The operation is commutative.
*
* If the argument `B` is omitted, computes `Out × A` (performs in-place multiplication)
*/
#define mlib_mul(...) MLIB_ARGC_PICK(_mlib_ckdint, mlib_mul, __VA_ARGS__)
/**
* @brief Perform narrowing assignment from one integer value to another.
*
* @param Out A non-null pointer to a modifiable integer.
* @param A The integer value to be narrowed.
* @retval `true` if the value written to `Out` is not equivalent to the value of `A`
* @retval `false` otherwise
*/
#define mlib_narrow(O, A) mlib_add((O), (A), 0)
/**
* @brief Perform an asserting addition, yielding the result
*
* @param T The target type of the operation
* @param A The left-hand addend for the addition
* @param B The right-hand addend for the addition
* @return The sum `A + B` as type `T`
*
* If the true arithmetic sum is not representable in `T`, the program terminates.
*/
#define mlib_assert_add(T, A, B) \
_mlib_assert_ckdint(T, A, B, &mlib_add, "mlib_assert_add", #T, #A, #B, mlib_this_source_location())
/**
* @brief Perform an asserting subtraction, yielding the result
*
* @param T The target type of the operation
* @param A The left-hand minuend for the subtraction
* @param B The right-hand subtrahend for the subtraction
* @return The difference `A - B` as type `T`
*
* If the true arithmetic difference is not representable in `T`, the program terminates.
*/
#define mlib_assert_sub(T, A, B) \
_mlib_assert_ckdint(T, A, B, &mlib_sub, "mlib_assert_sub", #T, #A, #B, mlib_this_source_location())
/**
* @brief Perform an asserting multiplication, yielding the result
*
* @param T The target type of the operation
* @param A The left-hand factor for the multiplication
* @param B The right-hand factor for the multiplication
* @return The product `A × B` as type `T`
*
* If the true arithmetic product is not representable in `T`, the program terminates.
*/
#define mlib_assert_mul(T, A, B) \
_mlib_assert_ckdint(T, A, B, &mlib_mul, "mlib_assert_mul", #T, #A, #B, mlib_this_source_location())
/**
* @brief Perform a runtime-checked cast of an integral value to another type.
*
* @param T A type specifier for a target integral type for the cast.
* @param Operand The integral value to be converted.
*
* If the cast would result in the operand value changing, the program will be
* terminated with a diagnostic.
*/
#define mlib_assert_narrow(T, Operand) \
(T) _mlib_checked_cast( \
mlib_minof(T), mlib_maxof(T), mlib_upsize_integer(Operand), #T, #Operand, mlib_this_source_location())
#define _mlib_ckdint_argc_3(Fn, Out, Arg) _mlib_ckdint_argc_4(Fn, Out, *(Out), Arg)
#define _mlib_ckdint_argc_4(Fn, O, A, B) \
_mlib_ckdint(O, \
sizeof(*(O)), \
_mlibClobberIsSigned(*(O), 0) ? (intmax_t)_mlibMinofSigned(*(O)) : _mlibMinofUnsigned(*(O)), \
_mlibClobberIsSigned(*(O), 1) ? _mlibMaxofSigned(*(O)) : _mlibMaxofUnsigned(*(O)), \
mlib_upsize_integer(A), \
mlib_upsize_integer(B), \
&Fn)
// Impl macro for the asserting checked arithmetic functions
#define _mlib_assert_ckdint(T, A, B, Fn, F_str, T_str, A_str, B_str, Here) \
((T)_mlib_assert_ckdint(sizeof(T), \
mlib_minof(T), \
mlib_maxof(T), \
mlib_upsize_integer(A), \
mlib_upsize_integer(B), \
Fn, \
F_str, \
T_str, \
A_str, \
B_str, \
Here))
// clang-format off
// Generates an 0b11111 bit pattern for appropriate size:
#define _mlibMaxofUnsigned(V) \
/* NOLINTNEXTLINE(bugprone-sizeof-expression) */ \
mlib_bits(mlib_bitsizeof((V)), 0)
// Generates an 0b01111 bit pattern for the two's complement max value:
#define _mlibMaxofSigned(V) \
/* NOLINTNEXTLINE(bugprone-sizeof-expression) */ \
mlib_bits(mlib_bitsizeof(V) - 1u, 0)
// Generates an 0b10000... bit pattern for the two's complement min value:
#define _mlibMinofSigned(V) \
/* NOLINTNEXTLINE(bugprone-sizeof-expression) */ \
(0 - mlib_bits(1, mlib_bitsizeof(V) - 1u))
// For completeness:
#define _mlibMinofUnsigned(V) 0
// Yields true iff the operand expression has a signed type, but requires that
// the operand is a modifiable l-value. The `N` must be 0 or 1, arbitrarily (see below).
#define _mlibClobberIsSigned(V, N) \
MLIB_IF_ELSE(mlib_have_typeof()) \
/* Prefer using typeof(), if we can. */ \
(mlib_is_signed(mlib_typeof(V))) \
/* Otherwise, do a dance: */ \
(( \
/* Save the value of V */ \
_mlibSignCheckTmp[N] = 0ull | (uintmax_t) (V), \
/* Set V to zero, and check whether decrementing results in a negative value */ \
(V) = 0, \
_mlibSignCheckResult[N] = (--(V) < 0), \
/* Restore the value of V (bit hacks to prevent conversion warnings) */ \
(V) = 0, \
(V) |= _mlibSignCheckTmp[N], \
/* Yield the sign-check result */ \
_mlibSignCheckResult[N] \
))
// Storage for `_mlibClobberIsSigned`. We use more than one storage space to prevent
// unsequenced-operation warnings when we use `_mlibClobberIsSigned` multiple times
// in a function argument list. GCC and Clang are able to easily elide these from
// an optimized TU. MSVC has trouble, but is still able to constant-fold where it matters.
static mlib_maybe_unused mlib_thread_local uintmax_t _mlibSignCheckTmp[2];
static mlib_maybe_unused mlib_thread_local bool _mlibSignCheckResult[2];
// clang-format on
// Compile-time assert that the compiler's integer conversions obey two's complement encoding
mlib_static_assert((intmax_t)UINTMAX_MAX == -1 //
&& (intmax_t)(UINTMAX_MAX - 5) == -6,
"This file requires two's complement signed integers");
/**
* @brief Function signature for checked arithmetic support functions
*
* The function operates on max-precision integers of either sign, and should
* return true iff the arithmetic operation overflows for the given sign configuration.
*
* @param dst The output parameter for the operation. Never a null pointer.
* @param dst_signed Whether to treat the result as a signed integer
* @param a_signed Whether to treat the `a` operand as signed
* @param a The left-hand operand of the operation
* @param b_signed Whether to treat the `b` operand as signed
* @param b The right-hand operand of the operation
*
* @note This was original written to use `mlib_upscaled_integer` for `a/b/dst`, but
* this defeats MSVC's ability to inline an indirect call through a constant-folded function
* pointer with this signature. GCC and Clang handle this fine, but for MSVC performance
* the more verbose signature is used.
*/
typedef bool (*_mlib_ckdint_arith_fn)(
uintmax_t *dst, bool dst_signed, bool a_signed, uintmax_t a, bool b_signed, uintmax_t b);
// Support function for the `mlib_add` macro
static inline bool(mlib_add)(uintmax_t *dst, bool dst_signed, bool a_signed, uintmax_t a, bool b_signed, uintmax_t b)
mlib_noexcept
{
// Perform regular wrapping arithmetic on the unsigned value. The bit pattern
// is equivalent if there is two's complement signed arithmetic.
const uintmax_t sum = *dst = a + b;
const uintmax_t signbit = mlib_bits(1, mlib_bitsizeof(uintmax_t) - 1u);
// Now we check whether that overflowed according to the sign configuration.
// We use some bit fiddling magic that treat the signbit as a boolean for
// "is this number negative?" or "is this number “large� (i.e. bigger than signed-max)?"
// The expanded verbose form of each bit-magic is written below the more esoteric cases
if (dst_signed) {
if (a_signed) {
if (b_signed) { // S = S + S
return signbit & (sum ^ a) & (sum ^ b);
// Expanded:
// Test whether the product sign is unequal to both input signs
// X ^ Y yields a negative value if the signs are unequal
// const bool a_signflipped = (intmax_t) (sum ^ a) < 0;
// const bool b_signflipped = (intmax_t) (sum ^ b) < 0;
// return a_signflipped && b_signflipped;
} else { // S = S + U
// Flip the sign bit of a, test whether that sum overflows
a ^= signbit;
return a + b < a;
}
} else {
if (b_signed) { // S = U + S
// Flip the sign bit of `b`, test whether that sum overflows
b ^= signbit;
return a + b < b;
} else { // S = U + U
// The signed sum must not be less than the addend, and not negative
return sum < a || (signbit & sum);
}
}
} else {
if (a_signed) {
if (b_signed) { // U = S + S
return signbit & (((sum | a) & b) | ((sum & a) & ~b));
// Expanded:
// const bool a_is_negative = (intmax_t) a < 0;
// const bool b_is_negative = (intmax_t) b < 0;
// const bool sum_is_large = sum > INTMAX_MAX;
// if (b_is_negative) {
// if (a_is_negative) {
// // The sum must be negative, and therefore cannot be stored in an unsigned
// return true;
// } else if (sum_is_large) {
// // We added a negative value B to a positive value A, but the sum
// // ended up larger than the max signed value, so we wrapped
// return true;
// }
// } else if (a_is_negative) {
// if (sum_is_large) {
// // Same as above case with sum_is_large
// return true;
// }
// }
// return false;
} else { // U = S + U
return signbit & (sum ^ a ^ signbit) & (sum ^ b);
// Expanded:
// const bool sum_is_large = sum > INTMAX_MAX;
// const bool b_is_large = b > INTMAX_MAX;
// const bool a_is_negative = (intmax_t) a < 0;
// if (!a_is_negative && b_is_large) {
// // We are adding a non-negative value to a large number, so the
// // sum must also be large
// if (!sum_is_large) {
// // We ended up with a smaller value, meaning that we must have wrapped
// return true;
// }
// }
// if (a_is_negative && !b_is_large) {
// // We subtracted a non-negative value from a non-large number, so
// // the result should not be large
// if (sum_is_large) {
// // We ended up with a large value, so we must have wrapped
// return true;
// }
// }
// return false;
}
} else {
if (b_signed) { // U = U + S --- (See [U = S + U] for an explanation)
return signbit & (sum ^ a) & (sum ^ b ^ signbit);
} else { // U = U + U (simple case)
return sum < a;
}
}
}
}
// Support for the `mlib_sub` macro
static inline bool(mlib_sub)(uintmax_t *dst, bool dst_signed, bool a_signed, uintmax_t a, bool b_signed, uintmax_t b)
mlib_noexcept
{
// Perform the subtraction using regular wrapping arithmetic
const uintmax_t diff = *dst = a - b;
const uintmax_t signbit = mlib_bits(1, mlib_bitsizeof(uintmax_t) - 1u);
// Test whether the operation overflowed for the given sign configuration
// (See mlib_add for more details on why we do this bit fiddling)
if (dst_signed) {
const bool diff_is_negative = signbit & diff;
if (a_signed) {
if (b_signed) { // S = S - S
return signbit & (a ^ b) & (diff ^ a);
// Explain:
// const bool a_is_negative = (intmax_t) a < 0;
// const bool b_is_negative = (intmax_t) b < 0;
// if (a_is_negative != b_is_negative) {
// // Given: Pos - Neg = Pos
// // ∧ Neg - Pos = Neg
// // We expect that the difference preserves the sign of the minuend
// if (diff_is_negative != a_is_negative) {
// return true;
// }
// }
// // Otherwise, `Pos - Pos` and `Neg - Neg` cannot possibly overflow
// return false;
} else { // S = S - U
// The diff overflows if the sign-bit-flipped minuend is smaller than the subtrahend
return (a ^ signbit) < b;
}
} else {
if (b_signed) { // S = U - S
// The diff overflows if the sign-bit-flipped subtrahend is greater than or equal to the minuend
return a >= (b ^ signbit);
} else { // S = U - U
const bool expect_negative = a < b;
return expect_negative != diff_is_negative;
}
}
} else {
if (a_signed) {
if (b_signed) { // U = S - S
return signbit & (((diff & a) & b) | ((diff | a) & ~b));
// Expanded:
// const bool a_is_negative = (intmax_t) a < 0;
// const bool b_is_negative = (intmax_t) b < 0;
// const bool diff_is_large = diff > INTMAX_MAX;
// if (!b_is_negative) {
// if (a_is_negative) {
// // We subtracted a non-negative from a negative value, so the difference
// // must be negative and cannot be stored as unsigned
// return true;
// }
// if (diff_is_large) {
// // We subtracted a positive value from a signed value, so we must not
// // end up with a large value
// return true;
// }
// }
// if (a_is_negative) {
// if (diff_is_large) {
// // A is negative, and there is no possible value that we can subtract
// // from it to obtain this large integer, so we must have overflowed
// return true;
// }
// }
// return false;
} else { //
return (b > a) || (signbit & a);
}
} else {
if (b_signed) { // U = U - S
return signbit & (a ^ b ^ signbit) & (diff ^ a);
// Explain:
// const bool a_is_large = a > INTMAX_MAX;
// const bool b_is_negative = (intmax_t) b < 0;
// const bool diff_is_large = diff > INTMAX_MAX;
// if (a_is_large && b_is_negative) {
// // The difference between a large value and a negative
// // value must also be a large value
// if (!diff_is_large) {
// // We expected another large value to appear.
// return true;
// }
// }
// if (!a_is_large && !b_is_negative) {
// // The difference between a non-large positive value and a non-negative value
// // must not be a large value
// if (diff_is_large) {
// // We did not expect a large difference
// return true;
// }
// }
// return false;
} else {
return a < b;
}
}
}
}
// Support for the `mlib_mul` macro
static inline bool(mlib_mul)(uintmax_t *dst, bool dst_signed, bool a_signed, uintmax_t a, bool b_signed, uintmax_t b)
mlib_noexcept
{
// Multiplication is a lot more subtle
const uintmax_t signbit = mlib_bits(1, mlib_bitsizeof(uintmax_t) - 1u);
if (dst_signed) {
if (a_signed) {
if (b_signed) {
// S = S × S
*dst = a * b;
if (((intmax_t)b == -1 && (intmax_t)a == INTMAX_MIN) || ((intmax_t)a == -1 && (intmax_t)b == INTMAX_MIN)) {
// MIN × -1 is undefined
return true;
}
if (a && (intmax_t)*dst / (intmax_t)a != (intmax_t)b) {
// Mult did not preserve the arithmetic identity
return true;
}
return false;
} else {
// S = S × U
*dst = a * b;
const bool a_is_negative = signbit & a;
const uintmax_t positive_a = a_is_negative ? (0 - a) : a;
const uintmax_t positive_prod = positive_a * b;
const bool did_overflow = positive_a && positive_prod / positive_a != b;
if (did_overflow) {
return true;
}
if (positive_prod > (uintmax_t)INTMAX_MAX + (unsigned)a_is_negative) {
return true;
}
return false;
}
} else {
if (b_signed) {
// S = U × S
// Swap args: [S = S × U]
return (mlib_mul)(dst, dst_signed, b_signed, b, a_signed, a);
} else {
// S = U × U
*dst = a * b;
const bool did_overflow = a && *dst / a != b;
if (did_overflow) {
return true;
}
if (signbit & *dst) {
// A negative product indicates wrapping
return true;
}
return false;
}
}
} else {
if (a_signed) {
if (b_signed) {
// U = S × S
// Is either operand the min?
bool either_min = false;
if (signbit & a & b) {
// Both negative: Flip the signs
a = 0 - a;
b = 0 - b;
// MIN is pathological: 0 - MIN = MIN, so we need to check that:
either_min = (intmax_t)a == INTMAX_MIN || (intmax_t)b == INTMAX_MIN;
}
// Check if the product would be a negative number
const bool neg_prod = (signbit & (a ^ b)) && a && b && !either_min;
*dst = a * b;
return neg_prod || (a && *dst / a != b);
} else {
// U = S × U
*dst = a * b;
const bool did_ovr = a && *dst / a != b;
const bool a_is_negative = signbit & a;
if (did_ovr || (a_is_negative && b)) {
return true;
}
return false;
}
} else {
if (b_signed) {
// U = U × S
// Swap to [U = S × U]
return (mlib_mul)(dst, dst_signed, b_signed, b, a_signed, a);
} else {
// U = U × U: Simple:
*dst = a * b;
return a && *dst / a != b;
}
}
}
}
/**
* @private
* @brief This function performs the narrowing checks around a ckdint funciton
*
* @param dst Pointer to the target interger
* @param dst_sz The size of the target integer, in bytes
* @param minval The minimum value for the result. If negative, the target is treated as signed
* @param maxval The maximum value for the result
* @param a The left-hand operand for the operation
* @param b The right-hand operand for the operation
* @param fn The arithmetic function that performs arithmetic on the max-precision integer
* @return true If the resulting value DOES NOT equal the true arithmetic result
* @return false If the resulting value represents the true arithmetic results
*/
static inline bool
_mlib_ckdint(void *dst,
int dst_sz,
intmax_t minval,
uintmax_t maxval,
struct mlib_upsized_integer a,
struct mlib_upsized_integer b,
_mlib_ckdint_arith_fn fn) mlib_noexcept
{
// Perform the arithmetic on uintmax_t, for wrapping behavior
uintmax_t tmp;
bool ovr = fn(&tmp, minval < 0, a.is_signed, a.bits.as_unsigned, b.is_signed, b.bits.as_unsigned);
// Endian-adjusting for writing the result
const char *copy_from = (const char *)&tmp;
if (!mlib_is_little_endian()) {
// We need to adjust the copy src in order to truncate the integer for big-endian encoding.
// Number of high bytes that we need to drop:
const int n_drop = (int)sizeof(tmp) - dst_sz;
// Adjust the copy pointer to so that we copy from the most significant byte that
// we wish to keep
copy_from += n_drop;
} else {
// For little-endian native, we don't need to adjust the bytes, since we can just
// truncate using the memcpy()
}
// Send the result to the destination
memcpy(dst, copy_from, (size_t)dst_sz);
// Final range check:
if (minval < 0) {
// Treat the target as signed:
intmax_t idst = (intmax_t)tmp;
return ovr || idst < minval || (idst > 0 && (uintmax_t)idst > maxval);
} else {
return ovr || tmp > maxval;
}
}
/**
* @internal
* @brief Implementation function for the asserting arithmetic functions
*/
static inline uintmax_t(_mlib_assert_ckdint)(size_t dst_sz,
intmax_t minval,
uintmax_t maxval,
struct mlib_upsized_integer a,
struct mlib_upsized_integer b,
_mlib_ckdint_arith_fn arith,
const char *fn_str,
const char *type_str,
const char *a_str,
const char *b_str,
struct mlib_source_location here) mlib_noexcept
{
uintmax_t tmp;
bool did_overflow = _mlib_ckdint(&tmp, dst_sz, minval, maxval, a, b, arith);
if (did_overflow) {
fprintf(stderr,
"%s:%d: [in %s]: Call of %s(%s, %s, %s) resulted in arithmetic overflow\n",
here.file,
here.lineno,
here.func,
fn_str,
type_str,
a_str,
b_str);
abort();
}
if (!mlib_is_little_endian()) {
// We unconditionally set the leading bytes of `tmp`, but big-endian expects
// the lower place values to be in the later bytes. If the target int is
// smaller than intmax, we must shift all the bits over to their proper
// position. This expression is trivially constant-folded by an optimizer.
tmp >>= ((size_t)CHAR_BIT * ((sizeof tmp) - dst_sz));
}
return tmp;
}
static inline uintmax_t
_mlib_checked_cast(intmax_t min_,
uintmax_t max_,
struct mlib_upsized_integer val,
const char *typename_,
const char *expr,
struct mlib_source_location here) mlib_noexcept
{
if (!(mlib_in_range)(min_, max_, val)) {
if (val.is_signed) {
fprintf(stderr,
"%s:%d: in [%s]: Checked integer cast of “%s� (value = %lld) to “%s� loses information\n",
here.file,
here.lineno,
here.func,
expr,
(long long)val.bits.as_signed,
typename_);
} else {
fprintf(stderr,
"%s:%d: in [%s]: Checked integer cast of “%s� (value = %llu) to “%s� loses information\n",
here.file,
here.lineno,
here.func,
expr,
(unsigned long long)val.bits.as_unsigned,
typename_);
}
fflush(stderr);
abort();
}
if (val.is_signed) {
return (uintmax_t)val.bits.as_signed;
}
return val.bits.as_unsigned;
}
mlib_extern_c_end();
mongodb-2.5.5/src/libmongoc/src/common/src/mlib/cmp.h 0000644 0001751 0001751 00000011573 15264101572 017365 0 ustar /**
* @file mlib/cmp.h
* @brief Safe integer comparison and range checking
* @date 2024-08-29
*
* This file provides safe and intuitive integer comparison macros that behave
* appropriately, regardless of the sign or precision of the integer operands.
*
* @copyright 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.
*/
#ifndef MLIB_CMP_H_INCLUDED
#define MLIB_CMP_H_INCLUDED
#include
#include
#include
#include
/**
* @brief Result type of comparing two integral values with `mlib_cmp`
*
* The enumerator values are chosen such that they can be compared with zero
*/
enum mlib_cmp_result {
// The two values are equivalent
mlib_equal = 0,
// The left-hand operand is less than the right-hand
mlib_less = -1,
// The left-hand operand is greater than the right-hand
mlib_greater = 1,
};
/**
* @brief Compare two integral values safely.
*
* This function can be called with two arguments or with three:
*
* - `mlib_cmp(a, b)` Returns a value of type `mlib_cmp_result`
* - `mlib_cmp(a, Op, b)` where `Op` is a relational operator. Evaluates to a boolean value.
*/
#define mlib_cmp(...) MLIB_ARGC_PICK(_mlib_cmp, __VA_ARGS__)
// Compare two integers, and return the result of that comparison:
#define _mlib_cmp_argc_2(L, R) mlib_cmp(mlib_upsize_integer((L)), mlib_upsize_integer((R)), 0)
// Compare two integers, but with an infix operator:
#define _mlib_cmp_argc_3(L, Op, R) (mlib_cmp(mlib_upsize_integer((L)), mlib_upsize_integer((R)), 0) Op 0)
// Impl for mlib_cmp
mlib_always_inline static enum mlib_cmp_result(mlib_cmp)(struct mlib_upsized_integer x,
struct mlib_upsized_integer y,
int always_zero) mlib_noexcept
{
(void)always_zero;
#if mlib_is_optimized_build() && !mlib_is_msvc() && \
!(defined(MLIB_DISABLE_INLINING_ASSERTIONS) && MLIB_DISABLE_INLINING_ASSERTIONS)
if (always_zero != 0) {
// All calls must pass zero for `always_zero`. In optimized builds, we assert that this function
// is always inlined, and that dead-code-elim triggers to delete this branch that calls
// a never-defined function.
extern void __assert_that_mlib_cmp_was_inlined(void);
// If you see a call to this function ↑ produce a link error here ↓, it means
// that inlining or DCE failed within the relevant translation unit.
__assert_that_mlib_cmp_was_inlined();
}
#endif
if (x.is_signed) {
if (y.is_signed) {
// Both signed
if (x.bits.as_signed < y.bits.as_signed) {
return mlib_less;
} else if (x.bits.as_signed > y.bits.as_signed) {
return mlib_greater;
}
} else {
// X signed, Y unsigned
if (x.bits.as_signed < 0 || (uintmax_t)x.bits.as_signed < y.bits.as_unsigned) {
return mlib_less;
} else if ((uintmax_t)x.bits.as_signed > y.bits.as_unsigned) {
return mlib_greater;
}
}
} else {
if (!y.is_signed) {
// Both unsigned
if (x.bits.as_unsigned < y.bits.as_unsigned) {
return mlib_less;
} else if (x.bits.as_unsigned > y.bits.as_unsigned) {
return mlib_greater;
}
} else {
// X unsigned, Y signed
if (y.bits.as_signed < 0 || x.bits.as_unsigned > (uintmax_t)y.bits.as_signed) {
return mlib_greater;
} else if (x.bits.as_unsigned < (uintmax_t)y.bits.as_signed) {
return mlib_less;
}
}
}
return mlib_equal;
}
/**
* @brief Test whether the given operand is within the range of some other integral type
*
* @param T A type specifier of the target integral type
* @param Operand the expression that is being inspected.
*
* @note This macro may evaluate the operand more than once
*/
#define mlib_in_range(T, Operand) \
mlib_in_range((intmax_t)mlib_minof(T), (uintmax_t)mlib_maxof(T), mlib_upsize_integer(Operand))
static inline bool(mlib_in_range)(intmax_t min_, uintmax_t max_, struct mlib_upsized_integer val) mlib_noexcept
{
if (val.is_signed) {
return mlib_cmp(val.bits.as_signed, >=, min_) && mlib_cmp(val.bits.as_signed, <=, max_);
} else {
return mlib_cmp(val.bits.as_unsigned, >=, min_) && mlib_cmp(val.bits.as_unsigned, <=, max_);
}
}
#endif // MLIB_CMP_H_INCLUDED
mongodb-2.5.5/src/libmongoc/src/common/src/mlib/config.h 0000644 0001751 0001751 00000036376 15264101572 020063 0 ustar /**
* @file mlib/config.h
* @brief Provides utility macros
* @date 2024-08-29
*
* @note This file is intented to be standalone-includable, with no dependencies
* other than the standard library and platform headers. This file (and other
* `mlib` files), are for internal use only, and should not be used in any public
* headers.
*
* @copyright 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.
*/
#ifndef MLIB_CONFIG_H_INCLUDED
#define MLIB_CONFIG_H_INCLUDED
#ifndef _WIN32
#include // Endian detection
#endif
/**
* @brief A function-like macro that always expands to nothing
*/
#define MLIB_NOTHING(...)
/**
* @brief A function macro that simply expands to its arguments unchanged
*/
#define MLIB_JUST(...) __VA_ARGS__
// Paste two tokens
#ifndef _MSC_VER
#define MLIB_PASTE(A, ...) _mlibPaste1(A, __VA_ARGS__)
#else
#define MLIB_PASTE(A, ...) MLIB_JUST(_mlibPaste1(A, __VA_ARGS__))
#endif
// Paste three tokens
#define MLIB_PASTE_3(A, B, ...) MLIB_PASTE(A, MLIB_PASTE(B, __VA_ARGS__))
// Paste four tokens
#define MLIB_PASTE_4(A, B, C, ...) MLIB_PASTE(A, MLIB_PASTE_3(B, C, __VA_ARGS__))
// Paste five tokens
#define MLIB_PASTE_5(A, B, C, D, ...) MLIB_PASTE(A, MLIB_PASTE_4(B, C, D, __VA_ARGS__))
#define _mlibPaste1(A, ...) A##__VA_ARGS__
/**
* @brief Convert the token sequence into a string after macro expansion
*/
#define MLIB_STR(...) _mlibStr(__VA_ARGS__)
#define _mlibStr(...) #__VA_ARGS__
#define MLIB_EVAL_32(...) MLIB_EVAL_16(MLIB_EVAL_16(__VA_ARGS__))
#define MLIB_EVAL_16(...) MLIB_EVAL_8(MLIB_EVAL_8(__VA_ARGS__))
#define MLIB_EVAL_8(...) MLIB_EVAL_4(MLIB_EVAL_4(__VA_ARGS__))
#define MLIB_EVAL_4(...) MLIB_EVAL_2(MLIB_EVAL_2(__VA_ARGS__))
#define MLIB_EVAL_2(...) MLIB_EVAL_1(MLIB_EVAL_1(__VA_ARGS__))
#define MLIB_EVAL_1(...) __VA_ARGS__
// clang-format off
/**
* @brief Expand to 1 if given no arguments, otherwise 0.
*
* This could be done trivially using __VA_OPT__, but we need to work on
* older compilers.
*/
#define MLIB_IS_EMPTY(...) \
_mlibIsEmpty_1( \
/* Expands to '1' if __VA_ARGS__ contains any top-level commas */ \
_mlibHasComma(__VA_ARGS__), \
/* Expands to '1' if __VA_ARGS__ begins with a parenthesis, because \
* that will cause an "invocation" of _mlibCommaIfParens, \
* which immediately expands to a single comma. */ \
_mlibHasComma(_mlibCommaIfParens __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 */ \
_mlibHasComma(__VA_ARGS__ ()), \
/* Expands to '1' if __VA_ARGS__ expands to nothing. */ \
_mlibHasComma(_mlibCommaIfParens __VA_ARGS__ ()))
// Expand to 1 if the argument list has a comma. The weird definition is to support
// old MSVC's bad preprocessor
#define _mlibHasComma(...) \
MLIB_JUST(_mlibPickSixteenth \
MLIB_NOTHING("MSVC workaround") \
(__VA_ARGS__, 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
#define _mlibCommaIfParens(...) ,
/**
* @brief Expands to `1` if the given macro argument is a parenthesized group of
* tokens, otherwise `0`
*/
#define MLIB_IS_PARENTHESIZED(X) \
_mlibHasComma(_mlibCommaIfParens X)
/**
* @brief Pass a function-like macro name, inhibiting its expansion until the
* next pass:
*
* #define func_macro(x) x
*
* MLIB_DEFERRED(func_macro)(foo) // Expands to "func_macro(foo)", not "foo"
*/
#define MLIB_DEFERRED(MacroName) \
/* Expand to the macro name: */ \
MacroName \
/*-
* Place a separator between the function macro name and whatever comes next
* in the file. Presumably, the next token will be the parens to invoke "MacroName",
* but this separator inhibits its expansion unless something else comes
* along to do another expansion pass
*/ \
MLIB_NOTHING("[separator]")
/**
* A helper for isEmpty(): If given (0, 0, 0, 1), expands as:
* - first: _mlibHasComma(_mlibIsEmptyCase_0001)
* - then: _mlibHasComma(,)
* - then: 1
* Given any other aruments:
* - first: _mlibHasComma(_mlibIsEmptyCase_)
* - then: 0
*/
#define _mlibIsEmpty_1(_1, _2, _3, _4) \
_mlibHasComma(MLIB_PASTE_5(_mlibIsEmptyCase_, _1, _2, _3, _4))
#define _mlibIsEmptyCase_0001 ,
#define MLIB_IS_NOT_EMPTY(...) MLIB_PASTE (_mlibNotEmpty_, MLIB_IS_EMPTY (__VA_ARGS__))
#define _mlibNotEmpty_1 0
#define _mlibNotEmpty_0 1
// clang-format on
/**
* @brief If the argument expands to `0`, `false`, or nothing, expands to `0`.
* Otherwise expands to `1`.
*/
#define MLIB_BOOLEAN(...) MLIB_IS_NOT_EMPTY(MLIB_PASTE_3(_mlib, Bool_, __VA_ARGS__))
#define _mlibBool_0
#define _mlibBool_false
#define _mlibBool_
/**
* @brief A ternary macro. Expects three parenthesized argument lists in
* sequence.
*
* If the first argument list is a truthy value, expands to the second argument
* list. Otherwise, expands to the third argument list. The unused argument list
* is not expanded and is discarded.
*/
#define MLIB_IF_ELSE(...) MLIB_PASTE(_mlibIfElseBranch_, MLIB_BOOLEAN(__VA_ARGS__))
#define _mlibIfElseBranch_1(...) __VA_ARGS__ MLIB_NOTHING
#define _mlibIfElseBranch_0(...) MLIB_JUST
/**
* @brief Expands to an integer literal corresponding to the number of macro
* arguments. Supports up to fifteen arguments.
*/
#define MLIB_ARG_COUNT(...) \
MLIB_IF_ELSE(MLIB_IS_EMPTY(__VA_ARGS__)) \
(0)(_mlibPickSixteenth(__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
#define _mlibPickSixteenth(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, ...) _16
/**
* @brief Expand to a call expression `Prefix##_argc_N(...)`, where `N` is the
* number of macro arguments.
*
* XXX: The `MLIB_JUST` forces an additional expansion pass that works around a
* bug in the old MSVC preprocessor, but is not required in a conforming preprocessor.
*/
#define MLIB_ARGC_PICK(Prefix, ...) MLIB_JUST(MLIB_ARGC_PASTE(Prefix, __VA_ARGS__)(__VA_ARGS__))
#define MLIB_ARGC_PASTE(Prefix, ...) MLIB_PASTE_3(Prefix, _argc_, MLIB_ARG_COUNT(__VA_ARGS__))
#ifdef __cplusplus
#define mlib_is_cxx() 1
#define mlib_is_not_cxx() 0
#define MLIB_IF_CXX(...) __VA_ARGS__
#define MLIB_IF_NOT_CXX(...)
#else
#define mlib_is_cxx() 0
#define mlib_is_not_cxx() 1
#define MLIB_IF_CXX(...)
#define MLIB_IF_NOT_CXX(...) __VA_ARGS__
#endif
#define MLIB_LANG_PICK MLIB_IF_ELSE(mlib_is_not_cxx())
/**
* @brief Use as the prefix of a braced initializer within C headers, allowing
* the initializer to appear as a compound-init in C and an equivalent braced
* aggregate-init in C++
*/
#define mlib_init(T) MLIB_LANG_PICK((T))(T)
/**
* @brief Expands to `noexcept` when compiled as C++, otherwise expands to
* nothing
*/
#define mlib_noexcept MLIB_IF_CXX(noexcept)
#if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__)
#define mlib_is_little_endian() (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
#elif defined(__BYTE_ORDER) && defined(__LITTLE_ENDIAN)
#define mlib_is_little_endian() (__BYTE_ORDER == __LITTLE_ENDIAN)
#elif defined(_WIN32)
#define mlib_is_little_endian() 1
#else
#error "Do not know how to detect endianness on this platform."
#endif
// clang-format off
/**
* @brief Expands to a static assertion declaration.
*
* When supported, this can be replaced with `_Static_assert` or `static_assert`
*/
#define mlib_static_assert(...) MLIB_ARGC_PICK (_mlib_static_assert, __VA_ARGS__)
#define _mlib_static_assert_argc_1(Expr) \
_mlib_static_assert_argc_2 ((Expr), "Static assertion failed")
#define _mlib_static_assert_argc_2(Expr, Msg) \
extern int \
MLIB_PASTE (_mlib_static_assert_placeholder, __COUNTER__)[(Expr) ? 2 : -1] \
MLIB_IF_GNU_LIKE (__attribute__ ((unused)))
// clang-format on
#define mlib_extern_c_begin() MLIB_IF_CXX(extern "C" {) mlib_static_assert(1, "")
#define mlib_extern_c_end() MLIB_IF_CXX( \
}) mlib_static_assert(1, "")
#ifdef __GNUC__
#define mlib_is_gnu_like() 1
#ifdef __clang__
#define mlib_is_gcc() 0
#define mlib_is_clang() 1
#else
#define mlib_is_gcc() 1
#define mlib_is_clang() 0
#endif
#define mlib_is_msvc() 0
#elif defined(_MSC_VER)
#define mlib_is_gnu_like() 0
#define mlib_is_clang() 0
#define mlib_is_gcc() 0
#define mlib_is_msvc() 1
#endif
#if defined(_WIN32)
#define mlib_is_win32() 1
#define mlib_is_unix() 0
#else
#define mlib_is_unix() 1
#define mlib_is_win32() 0
#endif
#define MLIB_IF_CLANG(...) MLIB_IF_ELSE(mlib_is_clang())(__VA_ARGS__)(MLIB_NOTHING(#__VA_ARGS__))
#define MLIB_IF_GCC(...) MLIB_IF_ELSE(mlib_is_gcc())(__VA_ARGS__)(MLIB_NOTHING(#__VA_ARGS__))
#define MLIB_IF_GNU_LIKE(...) MLIB_IF_GCC(__VA_ARGS__) MLIB_IF_CLANG(__VA_ARGS__) MLIB_NOTHING(#__VA_ARGS__)
#define MLIB_IF_UNIX_LIKE(...) MLIB_IF_ELSE(mlib_is_unix())(__VA_ARGS__)(MLIB_NOTHING(#__VA_ARGS__))
// note: Bug on GCC preprocessor prevents us from using if/else trick to omit MSVC code
#if mlib_is_msvc()
#define MLIB_IF_MSVC(...) __VA_ARGS__
#define mlib_pragma(...) __pragma(__VA_ARGS__) mlib_static_assert(1, "")
#else
#define MLIB_IF_MSVC(...) MLIB_NOTHING(#__VA_ARGS__)
#define mlib_pragma(...) _Pragma(#__VA_ARGS__) mlib_static_assert(1, "")
#endif
#define MLIB_PRAGMA_IF_CLANG(...) MLIB_IF_CLANG(_Pragma(#__VA_ARGS__))
#define MLIB_PRAGMA_IF_GCC(...) MLIB_IF_GCC(_Pragma(#__VA_ARGS__))
#define MLIB_PRAGMA_IF_GNU_LIKE(...) MLIB_IF_GNU_LIKE(_Pragma(#__VA_ARGS__))
#define MLIB_PRAGMA_IF_UNIX_LIKE(...) MLIB_IF_UNIX_LIKE(_Pragma(#__VA_ARGS__))
#define MLIB_PRAGMA_IF_MSVC(...) MLIB_IF_MSVC(__pragma(__VA_ARGS__))
#define MLIB_FUNC MLIB_IF_GNU_LIKE(__func__) MLIB_IF_MSVC(__FUNCTION__)
#define mlib_diagnostic_push() \
MLIB_IF_GNU_LIKE(mlib_pragma(GCC diagnostic push);) \
MLIB_IF_MSVC(mlib_pragma(warning(push));) \
mlib_static_assert(1, "")
#define mlib_diagnostic_pop() \
MLIB_IF_GNU_LIKE(mlib_pragma(GCC diagnostic pop);) \
MLIB_IF_MSVC(mlib_pragma(warning(pop));) \
mlib_static_assert(1, "")
#define mlib_gcc_warning_disable(Warning) \
MLIB_IF_GCC(mlib_pragma(GCC diagnostic ignored Warning);) \
mlib_static_assert(1, "")
#define mlib_gnu_warning_disable(Warning) \
MLIB_IF_GNU_LIKE(mlib_pragma(GCC diagnostic ignored Warning);) \
mlib_static_assert(1, "")
#define mlib_msvc_warning(...) \
MLIB_IF_MSVC(mlib_pragma(warning(__VA_ARGS__));) \
mlib_static_assert(1, "")
/**
* @brief Attribute macro that forces the function to be inlined at all call sites.
*
* Don't use this unless you really know that you need it, lest you generate code
* bloat when the compiler's heuristics would do a better job.
*/
#define mlib_always_inline MLIB_IF_GNU_LIKE(__attribute__((always_inline)) inline) MLIB_IF_MSVC(__forceinline)
// Annotate a variable as thread-local
#define mlib_thread_local MLIB_IF_GNU_LIKE(__thread) MLIB_IF_MSVC(__declspec(thread))
// Annotate an entiry that might be unused
#define mlib_maybe_unused MLIB_IF_GNU_LIKE(__attribute__((unused)))
// clang-format off
/**
* @brief Expand to `1` if the current build configuration matches the given token.
*
* If the token is not a known valid build configuration, generates a compilation
* error (check your spelling!)
*
* Requires that `_MLIB_BUILD_CONFIG` is defined, otherwise always expands to `0`
*/
#define mlib_build_config_is(Config) \
/* If `Config` is a recognized config, this line will disappear, */ \
/* other wise it will be a "call to undefined macro": */ \
MLIB_PASTE_4 (_mlibTestBuildConfig_, Config, _, Config) () \
/* If `Config` is the same token as `_MLIB_BUILD_CONFIG`, this will */ \
/* expand to `1`, otherwise it will expand to `0` */ \
MLIB_IS_EMPTY (MLIB_PASTE_4 (_mlibTestBuildConfig_, Config, _, _MLIB_BUILD_CONFIG) ())
// clang-format on
// Known build configurations:
#define _mlibTestBuildConfig_Release_Release()
#define _mlibTestBuildConfig_Debug_Debug()
#define _mlibTestBuildConfig_RelWithDebInfo_RelWithDebInfo()
#define _mlibTestBuildConfig_MinSizeRel_MinSizeRel()
/**
* @brief Emit a _Pragma that will disable warnings about the use of deprecated entities.
*/
#define mlib_disable_deprecation_warnings() \
mlib_gnu_warning_disable("-Wdeprecated-declarations"); \
mlib_msvc_warning(disable : 4996)
/**
* @brief Function-like macro that expands to `1` if we are certain that we are
* compiling with optimizations enabled.
*
* This may yield `0` if we cannot determine whether optimization is turned on.
*
* This macro should be used with care, as different translation units can see different values,
* but still be linked together in the final program. Beware generating ODR violations.
*/
#define mlib_is_optimized_build() _mlibIsOptimizedBuild()
#if mlib_build_config_is(Release) || mlib_build_config_is(RelWithDebInfo) || mlib_build_config_is(MinSizeRel) || \
(defined(__OPTIMIZE__) && __OPTIMIZE__)
// Preproc definition __OPTIMIZE__set by GCC ang Clang when the optimizer is enabled.
// MSVC has no such definition, so we rely on CMake to tell us when we are compiling in release mode
#define _mlibIsOptimizedBuild() 1
#else
#define _mlibIsOptimizedBuild() 0
#endif
#if mlib_is_gnu_like()
#define mlib_have_typeof() 1
#elif defined _MSC_VER && _MSC_VER >= 1939 && !__cplusplus
// We can __typeof__ in MSVC 19.39+
#define mlib_have_typeof() 1
#else
#define mlib_have_typeof() 0
#endif
/**
* @brief Equivalent to C23's `typeof()`, if it is supported by the current compiler.
*
* This expands to `__typeof__`, which is supported even on newer MSVC compilers,
* even when not in C23 mode.
*/
#define mlib_typeof(...) MLIB_IF_ELSE(mlib_have_typeof())(__typeof__)(__mlib_typeof_is_not_supported)(__VA_ARGS__)
/**
* @brief Disable warnings for constant conditional expressions.
*/
#define mlib_disable_constant_conditional_expression_warnings() mlib_msvc_warning(disable : 4127)
/**
* @brief Disable warnings for potentially unused parameters.
*/
#define mlib_disable_unused_parameter_warnings() \
MLIB_IF_GNU_LIKE(mlib_gnu_warning_disable("-Wunused-parameter");) \
MLIB_IF_MSVC(mlib_msvc_warning(disable : 4100);) mlib_static_assert(1, "")
#if mlib_is_clang()
#define mlib_printf_attribute(f, v) __attribute__((format(printf, f, v)))
#elif mlib_is_gcc()
#define mlib_printf_attribute(f, v) __attribute__((format(gnu_printf, f, v)))
#else
#define mlib_printf_attribute(f, v)
#endif
/**
* @brief Annotate a boolean expression as "likely to be true" to guide the optimizer.
* Use this very sparingly.
*/
#define mlib_likely(...) MLIB_IF_ELSE(mlib_is_gnu_like())(__builtin_expect(!!(__VA_ARGS__), 1))((__VA_ARGS__))
/**
* @brief Annotate a boolean expression as "likely to be untrue" to guide the optimizer.
* Use this very sparingly.
*/
#define mlib_unlikely(...) MLIB_IF_ELSE(mlib_is_gnu_like())(__builtin_expect(!!(__VA_ARGS__), 0))((__VA_ARGS__))
#endif // MLIB_CONFIG_H_INCLUDED
mongodb-2.5.5/src/libmongoc/src/common/src/mlib/duration.h 0000644 0001751 0001751 00000032163 15264101572 020431 0 ustar /**
* @file mlib/duration.h
* @brief Duration types and functions
* @date 2025-04-17
*
* This file contains types and functions for working with a "duration" type,
* which represents an elapsed amount of time, possibly negative.
*
* The type `mlib_duration_rep_t` is a typedef of the intregral type that is
* used to represent duration units.
*
* The `mlib_duration` is a trivial object that represents a duration of time.
* The internal representation should not be inspected outside of this file.
*
* @copyright 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.
*/
#ifndef MLIB_DURATION_H_INCLUDED
#define MLIB_DURATION_H_INCLUDED
#include
#include
#include