#include "call/echo_zval.h"

#include "php_embed_runtime.h"

#include <Zend/zend.h>
#include <Zend/zend_operators.h>

gboolean
valaphp_embed_echo_zval(Phpzval *value, char **error_message)
{
    if (!valaphp_embed_ensure_initialized(error_message))
        return FALSE;

    zval zend_value;
    valaphp_embed_zval_to_zend_zval(value, &zend_value);

    if (Z_TYPE(zend_value) == IS_STRING) {
        zend_string *str = Z_STR(zend_value);
        if (ZSTR_LEN(str) != 0)
            zend_write(ZSTR_VAL(str), ZSTR_LEN(str));
    } else {
        zend_string *str = zval_get_string_func(&zend_value);
        if (ZSTR_LEN(str) != 0)
            zend_write(ZSTR_VAL(str), ZSTR_LEN(str));
        zend_string_release_ex(str, 0);
    }

    zval_ptr_dtor(&zend_value);
    return TRUE;
}

gboolean
valaphp_embed_echo_string(const char *value, char **error_message)
{
    if (!valaphp_embed_ensure_initialized(error_message))
        return FALSE;

    const char *safe_value = value != NULL ? value : "";
    size_t length = strlen(safe_value);
    if (length != 0)
        zend_write(safe_value, length);
    return TRUE;
}
