using Php;

namespace PhpNative {
    public string substr_static (string value, int offset, int length, string php_file, int php_line) throws Error {
        int start = offset >= 0 ? offset : value.length + offset;
        if (start < 0) {
            start = 0;
        }
        if (start >= value.length) {
            return "";
        }

        int real_length = length;
        if (real_length < 0) {
            real_length = value.length - start + real_length;
        }
        if (real_length <= 0) {
            return "";
        }
        if (start + real_length > value.length) {
            real_length = value.length - start;
        }

        return value.substring (start, real_length);
    }

    public zval substr_zval (zval value, zval offset, zval length, string php_file, int php_line) throws Error {
        return zval.string_value (substr_static (zval_to_string (value), zval_to_int (offset), zval_to_int (length), php_file, php_line));
    }
}
