/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you 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 <string>
#include <fstream>
#include <iostream>
#include <vector>

#include <stdlib.h>
#include <sys/stat.h>
#include <sstream>
#include "thrift/platform.h"
#include "thrift/generate/t_oop_generator.h"

using std::map;
using std::ostream;
using std::ostringstream;
using std::string;
using std::stringstream;
using std::vector;

#define NSGLOBAL (nsglobal_.size() ? nsglobal_ : "")
#define NSGLOBAL_A ("\\" + NSGLOBAL)
#define NSGLOBAL_B (NSGLOBAL + "\\")
#define NSGLOBAL_AB ("\\" + NSGLOBAL + "\\")

/**
 * PHP code generator.
 *
 */
class t_php_generator : public t_oop_generator {
public:
  t_php_generator(t_program* program,
                  const std::map<std::string, std::string>& parsed_options,
                  const std::string& option_string)
    : t_oop_generator(program) {
    (void)option_string;
    std::map<std::string, std::string>::const_iterator iter;

    binary_inline_ = false;
    rest_ = false;
    phps_ = false;
    oop_ = false;
    validate_ = false;
    json_serializable_ = false;
    getters_setters_ = false;

    nsglobal_ = ""; // by default global namespace is empty
    classmap_ = false;
    for (iter = parsed_options.begin(); iter != parsed_options.end(); ++iter) {
      if (iter->first.compare("inlined") == 0) {
        binary_inline_ = true;
      } else if (iter->first.compare("rest") == 0) {
        rest_ = true;
      } else if (iter->first.compare("server") == 0) {
        phps_ = true;
      } else if (iter->first.compare("oop") == 0) {
        oop_ = true;
      } else if (iter->first.compare("validate") == 0) {
        validate_ = true;
      } else if (iter->first.compare("json") == 0) {
        json_serializable_ = true;
      } else if (iter->first.compare("nsglobal") == 0) {
        nsglobal_ = iter->second;
      } else if (iter->first.compare("classmap") == 0) {
        classmap_ = true;
      } else if (iter->first.compare("psr4") == 0) {
        if(classmap_){
          throw "psr4 and classmap are mutually exclusive.";
        } else {
          pwarning(0, "psr4 is default option! needn't add psr4 option!\n");
        }
      } else if (iter->first.compare("getters_setters") == 0) {
        getters_setters_ = true;
      } else {
        throw "unknown option php:" + iter->first;
      }
    }

    if (oop_ && binary_inline_) {
      throw "oop and inlined are mutually exclusive.";
    }

    update_keywords_for_validation();
    out_dir_base_ = (binary_inline_ ? "gen-phpi" : "gen-php");
    escape_['$'] = "\\$";
  }

  std::string indent_str() const override {
    return "    ";
  }

  /**
   * Build a PHP file-level docblock. Optional `phpcs_disables` are
   * spliced into the same docblock as `phpcs:disable <Sniff>` lines so
   * downstream projects running PSR-12 / Squiz sniffs against the
   * generated code get clean output without per-project configuration.
   * The three sniffs we ever disable (see PHPCS_*_DISABLES below) cover
   * cross-Thrift naming conventions that must remain consistent with
   * the other Thrift language generators; they are passed through only
   * for the file shapes that actually contain those identifiers. Plain
   * struct / enum / interface / REST files emit a clean docblock.
   */
  std::string php_autogen_comment(const std::vector<std::string>& phpcs_disables) {
    std::string s = t_oop_generator::autogen_comment();
    if (phpcs_disables.empty()) {
      return s;
    }
    auto closer = s.rfind(" */");
    std::string block = " *\n";
    for (const auto& rule : phpcs_disables) {
      block += " * phpcs:disable " + rule + "\n";
    }
    return s.substr(0, closer) + block + s.substr(closer);
  }

  std::string autogen_comment() override {
    return php_autogen_comment({});
  }

  // Cross-Thrift naming conventions whose violations must be silenced
  // per file shape. Hoisted to one place so a future rename or addition
  // is a one-line edit.
  const std::vector<std::string> PHPCS_DISABLES_CLASSMAP = {
      "PSR1.Classes.ClassDeclaration.MultipleClasses",
      "PSR1.Methods.CamelCapsMethodName",
      "Squiz.Classes.ValidClassName",
  };
  const std::vector<std::string> PHPCS_DISABLES_SNAKE_CASE_METHODS = {
      "PSR1.Methods.CamelCapsMethodName",
  };
  const std::vector<std::string> PHPCS_DISABLES_SERVICE_HELPERS = {
      "Squiz.Classes.ValidClassName",
  };

  static bool is_valid_namespace(const std::string& sub_namespace);

  /**
   * Init and close methods
   */

  void init_generator() override;
  void close_generator() override;
  std::string display_name() const override;

  /**
   * Program-level generation functions
   */

  void generate_typedef(t_typedef* ttypedef) override;
  void generate_enum(t_enum* tenum) override;
  void generate_consts(vector<t_const*> consts) override;
  void generate_struct(t_struct* tstruct) override;
  void generate_xception(t_struct* txception) override;
  void generate_service(t_service* tservice) override;

  std::string render_const_value(t_type* type, t_const_value* value);
  std::set<std::string> lang_keywords_for_validation() const override;

  /**
   * Structs!
   */

  void generate_php_struct(t_struct* tstruct, bool is_exception);
  void generate_php_struct_definition(std::ostream& out,
                                      t_struct* tstruct,
                                      bool is_xception = false,
                                      bool is_result = false);
  void generate_php_struct_reader(std::ostream& out, t_struct* tstruct, bool is_result);
  void generate_php_struct_writer(std::ostream& out, t_struct* tstruct, bool is_result);
  void generate_php_function_helpers(t_service* tservice, t_function* tfunction);
  void generate_php_struct_required_validator(ostream& out,
                                              t_struct* tstruct,
                                              std::string method_name,
                                              bool write_mode);
  void generate_php_struct_read_validator(ostream& out, t_struct* tstruct);
  void generate_php_struct_write_validator(ostream& out, t_struct* tstruct);
  void generate_php_struct_json_serialize(ostream& out, t_struct* tstruct, bool is_result);
  bool needs_php_write_validator(t_struct* tstruct, bool is_result);
  bool needs_php_read_validator(t_struct* tstruct, bool is_result);
  int get_php_num_required_fields(const vector<t_field*>& fields, bool write_mode);

  void generate_php_type_spec(std::ostream& out, t_type* t);
  void generate_php_struct_spec(std::ostream& out, t_struct* tstruct);
  void generate_generic_field_getters_setters(std::ostream& out, t_struct* tstruct);

  void generate_reflection_setters(ostringstream& out, string field_name, string cap_name);
  void generate_reflection_getters(ostringstream& out, string field_name, string cap_name);

  std::string get_cap_name(std::string name);


  /**
   * Service-level generation functions
   */

  void generate_service_helpers(t_service* tservice);
  void generate_service_interface(t_service* tservice);
  void generate_service_rest(t_service* tservice);
  void generate_service_client(t_service* tservice);
  void generate_service_processor(t_service* tservice);
  void generate_process_function(std::ostream& out, t_service* tservice, t_function* tfunction);
  void emit_file_header(const t_program* program,
                        std::ostream& file,
                        const std::vector<std::string>& phpcs_disables);
  void generate_service_header(t_service* tservice,
                               std::ostream& file,
                               const std::vector<std::string>& phpcs_disables = {});
  void generate_program_header(std::ostream& file,
                               const std::vector<std::string>& phpcs_disables = {});

  /**
   * Serialization constructs
   */

  void generate_deserialize_field(std::ostream& out,
                                  t_field* tfield,
                                  std::string prefix = "",
                                  bool inclass = false);

  void generate_deserialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = "");

  void generate_deserialize_container(std::ostream& out, t_type* ttype, std::string prefix = "");

  void generate_deserialize_set_element(std::ostream& out, t_set* tset, std::string prefix = "");

  void generate_deserialize_map_element(std::ostream& out, t_map* tmap, std::string prefix = "");

  void generate_deserialize_list_element(std::ostream& out,
                                         t_list* tlist,
                                         std::string prefix = "");

  void generate_serialize_field(std::ostream& out, t_field* tfield, std::string prefix = "");

  void generate_serialize_struct(std::ostream& out, t_struct* tstruct, std::string prefix = "");

  void generate_serialize_container(std::ostream& out, t_type* ttype, std::string prefix = "");

  void generate_serialize_map_element(std::ostream& out,
                                      t_map* tmap,
                                      std::string kiter,
                                      std::string viter);

  void generate_serialize_set_element(std::ostream& out, t_set* tmap, std::string iter);

  void generate_serialize_list_element(std::ostream& out, t_list* tlist, std::string iter);

  void emit_array_key_recast(std::ostream& out, t_type* ttype, const std::string& var);

  void generate_php_doc(std::ostream& out, t_doc* tdoc);

  void generate_php_doc(std::ostream& out, t_field* tfield);

  void generate_php_doc(std::ostream& out, t_function* tfunction);

  void generate_php_docstring_comment(std::ostream& out, string contents);

  /**
   * Helper rendering functions
   */

  std::string php_includes();
  std::string declare_field(t_field* tfield, bool init = false, bool obj = false);
  std::string function_signature(t_function* tfunction, std::string prefix = "");
  std::string argument_list(t_struct* tstruct, bool addTypeHints = true);
  std::string type_to_return(t_type* ttype);
  std::string type_to_cast(t_type* ttype);
  std::string type_to_enum(t_type* ttype);
  std::string type_to_phpdoc(t_type* ttype);
  std::string type_to_native(t_type* ttype);

  bool php_is_scalar(t_type *ttype) {
    ttype = ttype->get_true_type();
    if(ttype->is_base_type()) {
      return true;
    } else if(ttype->is_enum()) {
      return true;
    } else {
      return false;
    }
  }

  std::string php_namespace_base(const t_program* p) {
    std::string ns = p->get_namespace("php");
    const char* delimiter = "\\";
    size_t position = ns.find('.');
    while (position != string::npos) {
      ns.replace(position, 1, delimiter);
      position = ns.find('.', position + 1);
    }
    return ns;
  }

  // general use namespace prefixing: \my\namespace\ or my_namespace_
  string php_namespace(const t_program* p) {
    string ns = php_namespace_base(p);
    return (nsglobal_.size() ? NSGLOBAL_AB : NSGLOBAL_B) + (ns.size() ? (ns + "\\") : "");
  }

  // return the namespace of a file:
  // global\ns\sub\ns or global\ns or sub\ns
  string php_namespace_suffix(const t_program* p) {
    string ns = php_namespace_base(p);

    return NSGLOBAL
      + (ns.size() && NSGLOBAL.size() ? "\\" : "")
      + ns;
  }

  // add a directory to already existing namespace
  string php_namespace_directory(string directory, bool end = true) {
    (void)directory;
    if (end) {
      return ";";
    } else {
      return "";
    }
  }

  // writing an autload identifier into globa;ls: my\namespace\ or my_namespace_
  string php_namespace_autoload(const t_program* p) {
    std::string ns = php_namespace_base(p);
    return (nsglobal_.size() ? NSGLOBAL_B : NSGLOBAL) + (ns.size() ? (ns + "\\") : "");
  }

  // declaring a type: typename or my_namespace_typename
  string php_namespace_declaration(t_type* t) { return t->get_name(); }

  std::string php_path(t_program* p) {
    std::string ns = p->get_namespace("php.path");
    if (ns.empty()) {
      return p->get_name();
    }

    // Transform the java-style namespace into a path.
    for (char & n : ns) {
      if (n == '.') {
        n = '/';
      }
    }

    return ns + '/';
  }

  /**
   * Transform class_method into ClassMethod
   *
   * @param str
   * @return stirng
   */
  string classify(string str) {
    string classe = "";

    vector<string> x = split(str, '_');

    for (const auto & i : x) {
      classe = classe + capitalize(i);
    }

    return classe;
  }

  /**
   * Split method
   * @param s
   * @param delim
   * @param elems
   * @return
   */
  vector<string>& split(const string& s, char delim, vector<string>& elems) {
    stringstream ss(s);
    string item;

    while (getline(ss, item, delim)) {
      elems.push_back(item);
    }

    return elems;
  }

  vector<string> split(const string& s, char delim) {
    vector<string> elems;

    return split(s, delim, elems);
  }

  /**
   * Capitalize method
   * @param str
   * @return
   */
  string capitalize(string str) {
    string::iterator it(str.begin());

    if (it != str.end())
      str[0] = toupper((unsigned char)str[0]);

    //    while(++it != str.end())
    //    {
    //      *it = tolower((unsigned char)*it);
    //    }
    return str;
  }

private:
  /**
   * File streams
   */
  ofstream_with_content_based_conditional_update f_types_;
  ofstream_with_content_based_conditional_update f_service_;

  std::string package_dir_;
  /**
   * Generate protocol-independent template? Or Binary inline code?
   */
  bool binary_inline_;

  /**
   * Generate a REST handler class
   */
  bool rest_;

  /**
   * Generate stubs for a PHP server
   */
  bool phps_;

  /**
   * Whether to use OOP base class TBase
   */
  bool oop_;

  /**
   * Whether to generate old-style PHP file to use classmap autoloading
   */
  bool classmap_;

  /**
   * Whether to generate validator code
   */
  bool validate_;

  /**
   * Whether to generate JsonSerializable classes
   */
  bool json_serializable_;

  /**
   * Global namespace for PHP 5.3
   */
  std::string nsglobal_;

  /**
   * Whether to generate getters and setters
   */
  bool getters_setters_;
};

std::set<std::string> t_php_generator::lang_keywords_for_validation() const {
  std::string keywords[] = { "BEGIN", "END", "__CLASS__", "__DIR__", "__FILE__", "__FUNCTION__",
      "__LINE__", "__METHOD__", "__NAMESPACE__", "abstract", "alias", "and", "args", "as",
      "assert", "begin", "break", "case", "catch", "class", "clone", "continue", "declare",
      "def", "default", "del", "delete", "do", "dynamic", "elif", "else", "elseif", "elsif",
      "end", "enddeclare", "endfor", "endforeach", "endif", "endswitch", "endwhile", "ensure",
      "except", "exec", "finally", "float", "for", "foreach", "from", "function", "global",
      "goto", "if", "implements", "import", "in", "inline", "instanceof", "interface", "is",
      "lambda", "module", "native", "new", "next", "nil", "not", "or", "package", "pass",
      "public", "print", "private", "protected", "raise", "redo", "rescue", "retry", "register",
      "return", "self", "sizeof", "static", "super", "switch", "synchronized", "then", "this",
      "throw", "transient", "try", "undef", "unless", "unsigned", "until", "use", "var",
      "virtual", "volatile", "when", "while", "with", "xor", "yield" };
  return std::set<std::string>(keywords, keywords + sizeof(keywords)/sizeof(keywords[0]) );
}

bool t_php_generator::is_valid_namespace(const std::string& sub_namespace) {
  return sub_namespace == "path";
}

/**
 * Prepares for file generation by opening up the necessary file output
 * streams.
 *
 * @param tprogram The program to generate
 */
void t_php_generator::init_generator() {
  // Make output directory
  MKDIR(get_out_dir().c_str());

  // Create Real directory Namespaces
  vector<string> NSx = split(php_namespace_suffix(get_program()), '\\');
  package_dir_ = get_out_dir();

  for (const auto & i : NSx) {
    package_dir_ = package_dir_ + "/" + i + "/";
    MKDIR(package_dir_.c_str());
  }

  // Prepare output file for all the types in classmap mode
  if (classmap_) {
    // Make output file
    string f_types_name = package_dir_ + "Types.php";
    f_types_.open(f_types_name.c_str());
    generate_program_header(f_types_, PHPCS_DISABLES_CLASSMAP);
  }
}

/**
 * Prints standard php includes
 */
string t_php_generator::php_includes() {
  string includes = "use Thrift\\Base\\TBase;\n"
                    "use Thrift\\Type\\TType;\n"
                    "use Thrift\\Type\\TMessageType;\n"
                    "use Thrift\\Exception\\TException;\n"
                    "use Thrift\\Exception\\TProtocolException;\n"
                    "use Thrift\\Protocol\\TProtocol;\n"
                    "use Thrift\\Protocol\\TBinaryProtocol;\n"
                    "use Thrift\\Protocol\\TBinaryProtocolAccelerated;\n"
                    "use Thrift\\Exception\\TApplicationException;\n";

  if (binary_inline_) {
    includes += "use Thrift\\Transport\\TTransport;\n";
  }

  if (json_serializable_) {
    includes += "use JsonSerializable;\n"
                "use stdClass;\n";
  }

  return includes;
}

/**
 * Close up (or down) some filez.
 */
void t_php_generator::close_generator() {
  if (classmap_) {
    // Close types file
    f_types_.close();
  }
}

/**
 * Generates a typedef. This is not done in PHP, types are all implicit.
 *
 * @param ttypedef The type definition
 */
void t_php_generator::generate_typedef(t_typedef* ttypedef) {
  (void)ttypedef;
}

/**
 * Emits the standard `<?php` + autogen-docblock + namespace + use block at the
 * top of a generated file. Both `generate_program_header` and
 * `generate_service_header` funnel through here; they only differ in which
 * `t_program` they pull the namespace suffix from.
 */
void t_php_generator::emit_file_header(const t_program* program,
                                       std::ostream& file,
                                       const std::vector<std::string>& phpcs_disables) {
  file << "<?php" << '\n' << '\n'
       << php_autogen_comment(phpcs_disables) << '\n'
       << "declare(strict_types=1);" << '\n' << '\n';
  if (!php_namespace_suffix(program).empty()) {
    file << "namespace " << php_namespace_suffix(program) << ";" << '\n' << '\n';
  }
  file << php_includes() << '\n';
}

void t_php_generator::generate_service_header(t_service* tservice,
                                              std::ostream& file,
                                              const std::vector<std::string>& phpcs_disables) {
  emit_file_header(tservice->get_program(), file, phpcs_disables);
}

void t_php_generator::generate_program_header(std::ostream& file,
                                              const std::vector<std::string>& phpcs_disables) {
  emit_file_header(get_program(), file, phpcs_disables);
}

/**
 * Generates code for an enumerated type. Since define is expensive to lookup
 * in PHP, we use a global array for this.
 *
 * @param tenum The enumeration
 */
void t_php_generator::generate_enum(t_enum* tenum) {
  ofstream_with_content_based_conditional_update& f_enum = f_types_;
  if (!classmap_) {
    string f_enum_name = package_dir_ + tenum->get_name() + ".php";
    f_enum.open(f_enum_name.c_str());
    generate_program_header(f_enum);
  }

  vector<t_enum_value*> constants = tenum->get_constants();
  vector<t_enum_value*>::iterator c_iter;

  // We're also doing it this way to see how it performs. It's more legible
  // code but you can't do things like an 'extract' on it, which is a bit of
  // a downer.
  generate_php_doc(f_enum, tenum);
  f_enum << "final class " << tenum->get_name() << '\n'
         << "{" << '\n';
  indent_up();

  for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) {
    int value = (*c_iter)->get_value();
    generate_php_doc(f_enum, *c_iter);
    indent(f_enum) << "public const " << (*c_iter)->get_name() << " = " << value << ";" << '\n'
                   << '\n';
  }

  indent(f_enum) << "public static $names = [" << '\n';

  indent_up();
  for (c_iter = constants.begin(); c_iter != constants.end(); ++c_iter) {
    int value = (*c_iter)->get_value();
    indent(f_enum) << value << " => '" << (*c_iter)->get_name() << "'," << '\n';
  }
  indent_down();
  indent(f_enum) << "];" << '\n';

  indent_down();

  f_enum << "}" << '\n';
  if (!classmap_) {
    f_enum.close();
  }
}

/**
 * Generate constant class
 *
 * Override the one from t_generator
 */
void t_php_generator::generate_consts(vector<t_const*> consts) {
  vector<t_const*>::iterator c_iter;

  // Create class only if needed
  if (consts.size() > 0) {

    ofstream_with_content_based_conditional_update& f_consts = f_types_;
    if (!classmap_) {
      string f_consts_name = package_dir_ + "Constant.php";
      f_consts.open(f_consts_name.c_str());
      generate_program_header(f_consts, PHPCS_DISABLES_SNAKE_CASE_METHODS);
    }
    f_consts << "final class Constant extends \\Thrift\\Type\\TConstant"<< '\n'
             << "{" << '\n';

    indent_up();

    // Create static property
    for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
      string name = (*c_iter)->get_name();

      indent(f_consts) << "protected static $" << name << ";" << '\n';
    }

    // Create init function
    for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
      string name = (*c_iter)->get_name();

      f_consts << '\n';

      f_consts << indent() << "protected static function init_" << name << "()" << '\n'
               << indent() << "{" << '\n';
      indent_up();

      indent(f_consts) << "return ";
      generate_php_doc(f_consts, *c_iter);
      f_consts << render_const_value((*c_iter)->get_type(), (*c_iter)->get_value());
      f_consts << ";" << '\n';

      indent_down();
      indent(f_consts) << "}" << '\n';
    }

    indent_down();
    f_consts << "}" << '\n';
    if (!classmap_) {
      f_consts.close();
    }
  }
}

/**
 * Prints the value of a constant with the given type. Note that type checking
 * is NOT performed in this function as it is always run beforehand using the
 * validate_types method in main.cc
 */
string t_php_generator::render_const_value(t_type* type, t_const_value* value) {
  std::ostringstream out;
  type = get_true_type(type);
  if (type->is_base_type()) {
    t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
    switch (tbase) {
    case t_base_type::TYPE_STRING:
      out << '"' << get_escaped_string(value) << '"';
      break;
    case t_base_type::TYPE_BOOL:
      out << (value->get_integer() > 0 ? "true" : "false");
      break;
    case t_base_type::TYPE_I8:
    case t_base_type::TYPE_I16:
    case t_base_type::TYPE_I32:
    case t_base_type::TYPE_I64:
      out << value->get_integer();
      break;
    case t_base_type::TYPE_DOUBLE:
      if (value->get_type() == t_const_value::CV_INTEGER) {
        out << value->get_integer();
      } else {
        out << value->get_double();
      }
      break;
    case t_base_type::TYPE_UUID:
      out << '"' << get_escaped_string(value) << '"';
      break;
    default:
      throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase);
    }
  } else if (type->is_enum()) {
    indent(out) << value->get_integer();
  } else if (type->is_struct() || type->is_xception()) {
    out << "new " << php_namespace(type->get_program()) << type->get_name() << "([" << '\n';
    indent_up();
    const vector<t_field*>& fields = ((t_struct*)type)->get_members();
    vector<t_field*>::const_iterator f_iter;
    const map<t_const_value*, t_const_value*, t_const_value::value_compare>& val = value->get_map();
    map<t_const_value*, t_const_value*, t_const_value::value_compare>::const_iterator v_iter;
    for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
      t_type* field_type = nullptr;
      for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
        if ((*f_iter)->get_name() == v_iter->first->get_string()) {
          field_type = (*f_iter)->get_type();
        }
      }
      if (field_type == nullptr) {
        throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string();
      }
      out << indent();
      out << render_const_value(g_type_string, v_iter->first);
      out << " => ";
      out << render_const_value(field_type, v_iter->second);
      out << "," << '\n';
    }
    indent_down();
    indent(out) << "])";
  } else if (type->is_map()) {
    t_type* ktype = ((t_map*)type)->get_key_type();
    t_type* vtype = ((t_map*)type)->get_val_type();
    out << "[" << '\n';
    indent_up();
    const map<t_const_value*, t_const_value*, t_const_value::value_compare>& val = value->get_map();
    map<t_const_value*, t_const_value*, t_const_value::value_compare>::const_iterator v_iter;
    for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
      out << indent();
      out << render_const_value(ktype, v_iter->first);
      out << " => ";
      out << render_const_value(vtype, v_iter->second);
      out << "," << '\n';
    }
    indent_down();
    indent(out) << "]";
  } else if (type->is_list() || type->is_set()) {
    t_type* etype;
    if (type->is_list()) {
      etype = ((t_list*)type)->get_elem_type();
    } else {
      etype = ((t_set*)type)->get_elem_type();
    }
    out << "[" << '\n';
    indent_up();
    const vector<t_const_value*>& val = value->get_list();
    vector<t_const_value*>::const_iterator v_iter;
    for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
      out << indent();
      out << render_const_value(etype, *v_iter);
      if (type->is_set()) {
        out << " => true";
      }
      out << "," << '\n';
    }
    indent_down();
    indent(out) << "]";
  }
  return out.str();
}

/**
 * Make a struct
 */
void t_php_generator::generate_struct(t_struct* tstruct) {
  generate_php_struct(tstruct, false);
}

/**
 * Generates a struct definition for a thrift exception. Basically the same
 * as a struct but extends the Exception class.
 *
 * @param txception The struct definition
 */
void t_php_generator::generate_xception(t_struct* txception) {
  generate_php_struct(txception, true);
}

/**
 * Structs can be normal or exceptions.
 */
void t_php_generator::generate_php_struct(t_struct* tstruct, bool is_exception) {
  ofstream_with_content_based_conditional_update& f_struct = f_types_;
  if (!classmap_) {
    string f_struct_name = package_dir_ + tstruct->get_name() + ".php";
    f_struct.open(f_struct_name.c_str());
    generate_program_header(f_struct);
  }
  generate_php_struct_definition(f_struct, tstruct, is_exception);
  if (!classmap_) {
    f_struct.close();
  }
}

void t_php_generator::generate_php_type_spec(ostream& out, t_type* t) {
  t = get_true_type(t);
  indent(out) << "'type' => " << type_to_enum(t) << "," << '\n';

  if (t->is_base_type()) {
    // Noop, type is all we need
  } else if (t->is_struct() || t->is_xception() || t->is_enum()) {
    indent(out) << "'class' => '" << php_namespace(t->get_program()) << t->get_name() << "',"
                << '\n';
  } else if (t->is_map()) {
    t_type* ktype = get_true_type(((t_map*)t)->get_key_type());
    t_type* vtype = get_true_type(((t_map*)t)->get_val_type());
    indent(out) << "'ktype' => " << type_to_enum(ktype) << "," << '\n';
    indent(out) << "'vtype' => " << type_to_enum(vtype) << "," << '\n';
    indent(out) << "'key' => [" << '\n';
    indent_up();
    generate_php_type_spec(out, ktype);
    indent_down();
    indent(out) << "]," << '\n';
    indent(out) << "'val' => [" << '\n';
    indent_up();
    generate_php_type_spec(out, vtype);
    indent_down();
    indent(out) << "]," << '\n';
  } else if (t->is_list() || t->is_set()) {
    t_type* etype;
    if (t->is_list()) {
      etype = get_true_type(((t_list*)t)->get_elem_type());
    } else {
      etype = get_true_type(((t_set*)t)->get_elem_type());
    }
    indent(out) << "'etype' => " << type_to_enum(etype) << "," << '\n';
    indent(out) << "'elem' => [" << '\n';
    indent_up();
    generate_php_type_spec(out, etype);
    indent_down();
    indent(out) << "]," << '\n';
  } else {
    throw "compiler error: no type for php struct spec field";
  }
}

/**
 * Generates the struct specification structure, which fully qualifies enough
 * type information to generalize serialization routines.
 */
void t_php_generator::generate_php_struct_spec(ostream& out, t_struct* tstruct) {
  indent(out) << "public static array $tspec = [" << '\n';
  indent_up();

  const vector<t_field*>& members = tstruct->get_members();
  vector<t_field*>::const_iterator m_iter;
  for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
    t_type* t = get_true_type((*m_iter)->get_type());
    indent(out) << (*m_iter)->get_key() << " => [" << '\n';
    indent_up();
    out << indent() << "'var' => '" << (*m_iter)->get_name() << "'," << '\n';
    out << indent() << "'isRequired' => " << ((*m_iter)->get_req() == t_field::T_REQUIRED ? "true" : "false") << "," << '\n';
    generate_php_type_spec(out, t);
    indent_down();
    indent(out) << "]," << '\n';
  }

  indent_down();
  indent(out) << "];" << '\n';
}
/**
 * Generates necessary accessors and mutators for the fields
 */
void t_php_generator::generate_generic_field_getters_setters(std::ostream& out,
                                                              t_struct* tstruct) {
  std::ostringstream getter_stream;
  std::ostringstream setter_stream;

  // build up the bodies of both the getter and setter at once
  const vector<t_field*>& fields = tstruct->get_members();
  vector<t_field*>::const_iterator f_iter;
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
    t_field* field = *f_iter;
    std::string field_name = field->get_name();
    std::string cap_name = get_cap_name(field_name);

    indent_up();
    generate_reflection_setters(setter_stream, field_name, cap_name);
    generate_reflection_getters(getter_stream, field_name, cap_name);
    indent_down();
  }

  indent(out) << '\n';
  out << getter_stream.str();
  out << setter_stream.str();
  indent(out) << '\n';
}
/**
 * Generates a getter for the generated private fields
 */
void t_php_generator::generate_reflection_getters(ostringstream& out,
                                                   string field_name,
                                                   string cap_name) {


  out << indent() << "public function " << "get" << cap_name << "()" << '\n'
      << indent() << "{" << '\n';

  indent_up();

  out << indent() << "return $this->" << field_name << ";" << '\n';

  indent_down();
  out << indent() << "}" << '\n';
  out << '\n';
}
/**
 * Generates a setter for the generated private fields
 */
void t_php_generator::generate_reflection_setters(ostringstream& out,
                          string field_name,
                          string cap_name) {

  out << indent() << "public function set" << cap_name << "(" << "$" << field_name << ")" << '\n'
      << indent() << "{" << '\n';

  indent_up();

  out << indent() << "$this->" << field_name << " = $" << field_name << ";" << '\n';


  indent_down();
  out << indent() << "}" << '\n';
  out << '\n';
}
/**
 * Gets the first-letter capitalized name for the field
 *
 * @param std::string name of the field
 */
std::string t_php_generator::get_cap_name(std::string name) {
  name[0] = toupper(name[0]);
  return name;
}
/**
 * Generates a struct definition for a thrift data type. This is nothing in PHP
 * where the objects are all just associative arrays (unless of course we
 * decide to start using objects for them...)
 *
 * @param tstruct The struct definition
 */
void t_php_generator::generate_php_struct_definition(ostream& out,
                                                     t_struct* tstruct,
                                                     bool is_exception,
                                                     bool is_result) {
  const vector<t_field*>& members = tstruct->get_members();
  vector<t_field*>::const_iterator m_iter;

  generate_php_doc(out, tstruct);
  out << "class " << php_namespace_declaration(tstruct);
  if (is_exception) {
    out << " extends "
        << "TException";
  } else if (oop_) {
    out << " extends "
        << "TBase";
  }
  if (json_serializable_) {
    out << " implements JsonSerializable";
  }
  out << '\n'
      << "{" << '\n';
  indent_up();

  out << indent() << "public static bool $isValidate = " << (validate_ ? "true" : "false") << ";" << '\n' << '\n';

  generate_php_struct_spec(out, tstruct);
  out << '\n';

  // Internal C-implementation slots on \Exception that PHP forbids
  // subclasses from re-typing ("Type of … must not be defined").
  static const std::set<std::string> kExceptionInheritedSlots = {
      "message", "code", "file", "line"};

  for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
    string dval = "null";
    t_type* t = (*m_iter)->get_type()->get_true_type();
    if ((*m_iter)->get_value() != nullptr && !(t->is_struct() || t->is_xception())) {
      dval = render_const_value((*m_iter)->get_type(), (*m_iter)->get_value());
    }
    generate_php_doc(out, *m_iter);
    string access = (getters_setters_) ? "private" : "public";
    const string& fname = (*m_iter)->get_name();
    bool inherits_untyped = is_exception && kExceptionInheritedSlots.count(fname);
    string native = inherits_untyped ? "" : ("?" + type_to_native(t) + " ");
    indent(out) << access << " " << native << "$" << fname << " = " << dval << ";" << '\n';
  }

  if (!members.empty()) {
    out << '\n';
  }

  // Generate constructor from array
  string param = (members.size() > 0) ? "?array $vals = null" : "";
  out << indent() << "public function __construct(" << param << ")"<< '\n'
      << indent() << "{" << '\n';
  indent_up();

  if (members.size() > 0) {
    for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
      t_type* t = get_true_type((*m_iter)->get_type());
      if ((*m_iter)->get_value() != nullptr && (t->is_struct() || t->is_xception())) {
        indent(out) << "$this->" << (*m_iter)->get_name() << " = "
                    << render_const_value(t, (*m_iter)->get_value()) << ";" << '\n';
      }
    }
    out << indent() << "if (is_array($vals)) {" << '\n';
    indent_up();
    if (oop_) {
      out << indent() << "parent::__construct(self::$tspec, $vals);" << '\n';
    } else {
      for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
        const string& fname = (*m_iter)->get_name();
        // Cast incoming scalar to the declared property type so `new X([...])`
        // tolerates loose-typed user input (e.g. '1' -> true) the way PHP did
        // before declare(strict_types=1) + typed properties became the contract.
        // type_to_cast() returns "" for struct/container types, leaving them
        // as straight assignments.
        const string cast = type_to_cast((*m_iter)->get_type());
        out << indent() << "if (isset($vals['" << fname << "'])) {" << '\n';

        indent_up();
        out << indent() << "$this->" << fname << " = " << cast << "$vals['"
            << fname << "'];" << '\n';

        indent_down();
        out << indent() << "}" << '\n';
      }
    }
    indent_down();
    out << indent() << "}" << '\n';
  }
  scope_down(out);
  out << '\n';

  out << indent() << "public function getName(): string" << '\n'
      << indent() << "{" << '\n';

  indent_up();
  out << indent() << "return '" << tstruct->get_name() << "';" << '\n';

  indent_down();
  out << indent() << "}" << '\n' << '\n';

  if (getters_setters_) {
    generate_generic_field_getters_setters(out, tstruct);
  }
  generate_php_struct_reader(out, tstruct, is_result);
  out << '\n';
  generate_php_struct_writer(out, tstruct, is_result);
  if (needs_php_read_validator(tstruct, is_result)) {
    out << '\n';
    generate_php_struct_read_validator(out, tstruct);
  }
  if (needs_php_write_validator(tstruct, is_result)) {
    out << '\n';
    generate_php_struct_write_validator(out, tstruct);
  }
  if (json_serializable_) {
    out << '\n';
    generate_php_struct_json_serialize(out, tstruct, is_result);
  }

  indent_down();
  out << indent() << "}" << '\n';
}

/**
 * Generates the read() method for a struct
 */
void t_php_generator::generate_php_struct_reader(ostream& out, t_struct* tstruct, bool is_result) {
  const vector<t_field*>& fields = tstruct->get_members();
  vector<t_field*>::const_iterator f_iter;

  if (binary_inline_) {
    // Inline mode reads from a raw TTransport (string buffer), not a TProtocol.
    indent(out) << "public function read(TTransport $input): int" << '\n';
  } else {
    indent(out) << "public function read(TProtocol $input): int" << '\n';
  }
  scope_up(out);

  if (oop_) {
    if (needs_php_read_validator(tstruct, is_result)) {
      indent(out) << "$tmp = $this->readStruct('" << tstruct->get_name() << "', self::$tspec, $input);"
                  << '\n';
      indent(out) << "$this->validateForRead();" << '\n';
      indent(out) << "return $tmp;" << '\n';
    } else {
      indent(out) << "return $this->readStruct('" << tstruct->get_name() << "', self::$tspec, $input);"
                  << '\n';
    }
    scope_down(out);
    return;
  }

  out << indent() << "$xfer = 0;" << '\n' << indent() << "$fname = null;" << '\n' << indent()
      << "$ftype = 0;" << '\n' << indent() << "$fid = 0;" << '\n';

  // Declare stack tmp variables
  if (!binary_inline_) {
    indent(out) << "$input->incrementRecursionDepth();" << '\n';
    indent(out) << "try {" << '\n';
    indent_up();
    indent(out) << "$xfer += $input->readStructBegin($fname);" << '\n';
  }

  // Loop over reading in fields
  indent(out) << "while (true) {" << '\n';

  indent_up();

  // Read beginning field marker
  if (binary_inline_) {
    t_field fftype(g_type_i8, "ftype");
    t_field ffid(g_type_i16, "fid");
    generate_deserialize_field(out, &fftype);
    out << indent() << "if ($ftype == "
        << "TType::STOP) {" << '\n' << indent() << "    break;" << '\n' << indent() << "}" << '\n';
    generate_deserialize_field(out, &ffid);
  } else {
    indent(out) << "$xfer += $input->readFieldBegin($fname, $ftype, $fid);" << '\n';
    // Check for field STOP marker and break
    indent(out) << "if ($ftype == "
                << "TType::STOP) {" << '\n';
    indent_up();
    indent(out) << "break;" << '\n';
    indent_down();
    indent(out) << "}" << '\n';
  }

  // Switch statement on the field we are reading
  indent(out) << "switch ($fid) {" << '\n';

  indent_up();

  // Generate deserialization code for known cases
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
    indent(out) << "case " << (*f_iter)->get_key() << ":" << '\n';
    indent_up();
    indent(out) << "if ($ftype == " << type_to_enum((*f_iter)->get_type()) << ") {" << '\n';
    indent_up();
    generate_deserialize_field(out, *f_iter, "this->");
    indent_down();
    out << indent() << "} else {" << '\n';

    indent_up();
    if (binary_inline_) {
      indent(out) << "$xfer += TProtocol::skipBinary($input, $ftype);" << '\n';
    } else {
      indent(out) << "$xfer += $input->skip($ftype);" << '\n';
    }

    indent_down();
    out << indent() << "}" << '\n' << indent() << "break;" << '\n';
    indent_down();
  }

  // In the default case we skip the field
  indent(out) << "default:" << '\n';

  indent_up();
  if (binary_inline_) {
    indent(out) << "$xfer += "
                << "TProtocol::skipBinary($input, $ftype);" << '\n';
  } else {
    indent(out) << "$xfer += $input->skip($ftype);" << '\n';
  }
  indent(out) << "break;" << '\n';
  indent_down();

  scope_down(out);

  if (!binary_inline_) {
    // Read field end marker
    indent(out) << "$xfer += $input->readFieldEnd();" << '\n';
  }

  scope_down(out);

  if (!binary_inline_) {
    indent(out) << "$xfer += $input->readStructEnd();" << '\n';
    indent_down();
    indent(out) << "} finally {" << '\n';
    indent_up();
    indent(out) << "$input->decrementRecursionDepth();" << '\n';
    indent_down();
    indent(out) << "}" << '\n';
  }

  if (needs_php_read_validator(tstruct, is_result)) {
    indent(out) << "$this->validateForRead();" << '\n';
  }

  out << '\n';
  indent(out) << "return $xfer;" << '\n';

  indent_down();
  out << indent() << "}" << '\n';
}

/**
 * Generates the write() method for a struct
 */
void t_php_generator::generate_php_struct_writer(ostream& out, t_struct* tstruct, bool is_result) {
  string name = tstruct->get_name();
  const vector<t_field*>& fields = tstruct->get_sorted_members();
  vector<t_field*>::const_iterator f_iter;

  if (binary_inline_) {
    indent(out) << "public function write(string &$output): int" << '\n';
  } else {
    indent(out) << "public function write(TProtocol $output): int" << '\n';
  }
  indent(out) << "{" << '\n';
  indent_up();

  if (needs_php_write_validator(tstruct, is_result)) {
    indent(out) << "$this->validateForWrite();" << '\n';
  }

  if (oop_) {
    indent(out) << "return $this->writeStruct('" << tstruct->get_name() << "', self::$tspec, $output);"
                << '\n';
    scope_down(out);
    return;
  }

  indent(out) << "$xfer = 0;" << '\n';

  if (!binary_inline_) {
    indent(out) << "$output->incrementRecursionDepth();" << '\n';
    indent(out) << "try {" << '\n';
    indent_up();
    indent(out) << "$xfer += $output->writeStructBegin('" << name << "');" << '\n';
  }

  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
    out << indent() << "if ($this->" << (*f_iter)->get_name() << " !== null) {" << '\n';
    indent_up();

    t_type* type = get_true_type((*f_iter)->get_type());
    string expect;
    if (type->is_container()) {
      expect = "array";
    } else if (type->is_struct()) {
      expect = "object";
    }
    if (!expect.empty()) {
      out << indent() << "if (!is_" << expect << "($this->" << (*f_iter)->get_name() << ")) {"
          << '\n';
      indent_up();
      out << indent() << "throw new "
          << "TProtocolException('Bad type in structure.', "
          << "TProtocolException::INVALID_DATA);" << '\n';
      scope_down(out);
    }

    // Write field header
    if (binary_inline_) {
      out << indent() << "$output .= pack('c', " << type_to_enum((*f_iter)->get_type()) << ");"
          << '\n' << indent() << "$output .= pack('n', " << (*f_iter)->get_key() << ");" << '\n';
    } else {
      indent(out) << "$xfer += $output->writeFieldBegin("
                  << "'" << (*f_iter)->get_name() << "', " << type_to_enum((*f_iter)->get_type())
                  << ", " << (*f_iter)->get_key() << ");" << '\n';
    }

    // Write field contents
    generate_serialize_field(out, *f_iter, "this->");

    // Write field closer
    if (!binary_inline_) {
      indent(out) << "$xfer += $output->writeFieldEnd();" << '\n';
    }

    indent_down();
    indent(out) << "}" << '\n';
  }

  if (binary_inline_) {
    out << indent() << "$output .= pack('c', "
        << "TType::STOP);" << '\n';
  } else {
    out << indent() << "$xfer += $output->writeFieldStop();" << '\n' << indent()
        << "$xfer += $output->writeStructEnd();" << '\n';
    indent_down();
    out << indent() << "} finally {" << '\n';
    indent_up();
    out << indent() << "$output->decrementRecursionDepth();" << '\n';
    indent_down();
    out << indent() << "}" << '\n';
  }

  out << '\n';
  out << indent() << "return $xfer;" << '\n';

  indent_down();
  out << indent() << "}" << '\n';
}

void t_php_generator::generate_php_struct_read_validator(ostream& out, t_struct* tstruct) {
  generate_php_struct_required_validator(out, tstruct, "validateForRead", false);
}

void t_php_generator::generate_php_struct_write_validator(ostream& out, t_struct* tstruct) {
  generate_php_struct_required_validator(out, tstruct, "validateForWrite", true);
}

void t_php_generator::generate_php_struct_required_validator(ostream& out,
                                                             t_struct* tstruct,
                                                             std::string method_name,
                                                             bool write_mode) {
  indent(out) << "private function " << method_name << "(): void" << '\n';
  indent(out) << "{" << '\n';
  indent_up();

  const vector<t_field*>& fields = tstruct->get_members();

  if (fields.size() > 0) {
    vector<t_field*>::const_iterator f_iter;

    for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
      t_field* field = (*f_iter);
      if (field->get_req() == t_field::T_REQUIRED
          || (field->get_req() == t_field::T_OPT_IN_REQ_OUT && write_mode)) {
        indent(out) << "if ($this->" << field->get_name() << " === null) {" << '\n';
        indent_up();
        indent(out) << "throw new TProtocolException('Required field " << tstruct->get_name() << "."
                    << field->get_name() << " is unset!');" << '\n';
        indent_down();
        indent(out) << "}" << '\n';
      }
    }
  }

  indent_down();
  indent(out) << "}" << '\n';
}

void t_php_generator::generate_php_struct_json_serialize(ostream& out,
                                                         t_struct* tstruct,
                                                         bool is_result) {
  indent(out) << "public function jsonSerialize(): mixed" << '\n';
  indent(out) << "{" << '\n';
  indent_up();

  if (needs_php_write_validator(tstruct, is_result)) {
    indent(out) << "$this->validateForWrite();" << '\n';
  }

  indent(out) << "$json = new stdClass();" << '\n';

  const vector<t_field*>& fields = tstruct->get_members();

  if (fields.size() > 0) {
    vector<t_field*>::const_iterator f_iter;
    for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
      t_field* field = (*f_iter);
      t_type* type = field->get_type();
      const string& name = field->get_name();
      if (type->is_map()) {
        t_type* key_type = ((t_map*)type)->get_key_type();
        if (!(key_type->is_base_type() || key_type->is_enum())) {
          // JSON object keys must be strings. PHP's json_encode()
          // function will convert any scalar key to strings, but
          // we skip thrift maps with non-scalar keys.
          continue;
        }
      }
      indent(out) << "if ($this->" << name << " !== null) {" << '\n';
      indent_up();
      indent(out) << "$json->" << name << " = ";
      if (type->is_map()) {
        out << "(object)";
      } else {
        out << type_to_cast(type);
      }
      out << "$this->" << name << ";" << '\n';
      indent_down();
      indent(out) << "}" << '\n';
    }
  }

  indent(out) << "return $json;" << '\n';
  indent_down();

  indent(out) << "}" << '\n';
}

int t_php_generator::get_php_num_required_fields(const vector<t_field*>& fields, bool write_mode) {
  int num_req = 0;

  if (fields.size() > 0) {
    vector<t_field*>::const_iterator f_iter;
    for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
      if ((*f_iter)->get_req() == t_field::T_REQUIRED
          || ((*f_iter)->get_req() == t_field::T_OPT_IN_REQ_OUT && write_mode)) {
        ++num_req;
      }
    }
  }
  return num_req;
}

bool t_php_generator::needs_php_write_validator(t_struct* tstruct, bool is_result) {
  return (validate_ && !is_result && !tstruct->is_union()
          && get_php_num_required_fields(tstruct->get_members(), true) > 0);
}

bool t_php_generator::needs_php_read_validator(t_struct* tstruct, bool is_result) {
  return (validate_ && !is_result
          && (get_php_num_required_fields(tstruct->get_members(), false) > 0));
}

/**
 * Generates a thrift service.
 *
 * @param tservice The service definition
 */
void t_php_generator::generate_service(t_service* tservice) {
  if(classmap_) {
    string f_service_name = package_dir_ + service_name_ + ".php";
    f_service_.open(f_service_name.c_str());
    generate_service_header(tservice, f_service_, PHPCS_DISABLES_CLASSMAP);
  }

  // Generate the three main parts of the service (well, two for now in PHP)
  generate_service_interface(tservice);
  if (rest_) {
    generate_service_rest(tservice);
  }
  generate_service_client(tservice);
  generate_service_helpers(tservice);
  if (phps_) {
    generate_service_processor(tservice);
  }

  if(classmap_) {
    f_service_.close();
  }
}

/**
 * Generates a service server definition.
 *
 * @param tservice The service to generate a server for.
 */
void t_php_generator::generate_service_processor(t_service* tservice) {
  ofstream_with_content_based_conditional_update& f_service_processor = f_service_;
  if (!classmap_) {
    string f_service_processor_name = package_dir_ + service_name_ + "Processor.php";
    f_service_processor.open(f_service_processor_name.c_str());
    generate_service_header(tservice, f_service_processor, PHPCS_DISABLES_SNAKE_CASE_METHODS);
  }

  // Generate the dispatch methods
  vector<t_function*> functions = tservice->get_functions();
  vector<t_function*>::iterator f_iter;

  string extends = "";
  string extends_processor = "";
  if (tservice->get_extends() != nullptr) {
    extends = tservice->get_extends()->get_name();
    extends_processor = " extends " + php_namespace(tservice->get_extends()->get_program())
                        + extends + "Processor";
  }

  // Generate the header portion
  f_service_processor << "class " << service_name_ << "Processor" << extends_processor << '\n'
                      << "{" << '\n';
  indent_up();

  if (extends.empty()) {
    f_service_processor << indent() << "protected ?object $handler_ = null;" << '\n';
  }

  f_service_processor << indent() << "public function __construct(object $handler)"<< '\n'
                      << indent() << "{" << '\n';

  indent_up();
  if (extends.empty()) {
    f_service_processor << indent() << "$this->handler_ = $handler;" << '\n';
  } else {
    f_service_processor << indent() << "parent::__construct($handler);" << '\n';
  }

  indent_down();
  f_service_processor << indent() << "}" << '\n' << '\n';

  // Generate the server implementation
  f_service_processor << indent() << "public function process(TProtocol $input, TProtocol $output): bool" << '\n'
                      << indent() << "{" << '\n';
  indent_up();

  f_service_processor << indent() << "$rseqid = 0;" << '\n' << indent() << "$fname = null;" << '\n'
                      << indent() << "$mtype = 0;" << '\n' << '\n';

  if (binary_inline_) {
    t_field ffname(g_type_string, "fname");
    t_field fmtype(g_type_i8, "mtype");
    t_field fseqid(g_type_i32, "rseqid");
    generate_deserialize_field(f_service_processor, &ffname, "", true);
    generate_deserialize_field(f_service_processor, &fmtype, "", true);
    generate_deserialize_field(f_service_processor, &fseqid, "", true);
  } else {
    f_service_processor << indent() << "$input->readMessageBegin($fname, $mtype, $rseqid);" << '\n';
  }

  // HOT: check for method implementation
  f_service_processor << indent() << "$methodname = 'process_' . $fname;" << '\n'
                      << indent() << "if (!method_exists($this, $methodname)) {" << '\n';

  indent_up();
  if (binary_inline_) {
    f_service_processor << indent() << "throw new \\Exception('Function ' . $fname . ' not implemented.');" << '\n';
  } else {
    f_service_processor << indent() << "$input->skip(TType::STRUCT);" << '\n'
                        << indent() << "$input->readMessageEnd();" << '\n'
                        << indent() << "$x = new TApplicationException("
                        << "'Function ' . $fname . ' not implemented.', "
                        << "TApplicationException::UNKNOWN_METHOD);" << '\n'
                        << indent() << "$output->writeMessageBegin($fname, "
                        << "TMessageType::EXCEPTION, $rseqid);" << '\n'
                        << indent() << "$x->write($output);" << '\n'
                        << indent() << "$output->writeMessageEnd();" << '\n'
                        << indent() << "$output->getTransport()->flush();" << '\n'
                        << indent() << "return false;" << '\n';
  }

  indent_down();
  f_service_processor << indent() << "}" << '\n'
                      << indent() << "$this->$methodname($rseqid, $input, $output);" << '\n'
                      << indent() << "return true;" << '\n';

  indent_down();
  f_service_processor << indent() << "}" << '\n' << '\n';

  // Generate the process subfunctions
  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
    generate_process_function(f_service_processor, tservice, *f_iter);
  }

  indent_down();
  f_service_processor << "}" << '\n';

  if (!classmap_) {
    f_service_processor.close();
  }
}

/**
 * Generates a process function definition.
 *
 * @param tfunction The function to write a dispatcher for
 */
void t_php_generator::generate_process_function(std::ostream& out, t_service* tservice, t_function* tfunction) {
  // Open function
  out << indent() << "protected function process_" << tfunction->get_name()
      << "(int $seqid, TProtocol $input, TProtocol $output): void" << '\n'
      << indent() << "{" << '\n';
  indent_up();

  string argsname = php_namespace(tservice->get_program()) + service_name_ + "_"
                    + tfunction->get_name() + "_args";
  string resultname = php_namespace(tservice->get_program()) + service_name_ + "_"
                      + tfunction->get_name() + "_result";

  out << indent() << "$bin_accel = ($input instanceof "
             << "TBinaryProtocolAccelerated) && function_exists('thrift_protocol_read_binary_after_message_begin');"
             << '\n';
  out << indent() << "if ($bin_accel) {" << '\n';
  indent_up();

  out << indent() << "$args = thrift_protocol_read_binary_after_message_begin(" << '\n';

  indent_up();
  out << indent() << "$input," << '\n'
      << indent() << "'" << argsname << "'," << '\n'
      << indent() << "$input->isStrictRead()" << '\n';

  indent_down();
  out << indent() <<");" << '\n';

  indent_down();
  out << indent() << "} else {" << '\n';

  indent_up();
  out << indent() << "$args = new " << argsname << "();" << '\n'
      << indent() << "$args->read($input);" << '\n';

  indent_down();
  out << indent() << "}" << '\n';

  if (!binary_inline_) {
    out << indent() << "$input->readMessageEnd();" << '\n';
  }

  t_struct* xs = tfunction->get_xceptions();
  const std::vector<t_field*>& xceptions = xs->get_members();
  vector<t_field*>::const_iterator x_iter;

  // Declare result for non oneway function
  if (!tfunction->is_oneway()) {
    out << indent() << "$result = new " << resultname << "();" << '\n';
  }

  // Wrap handler invocations so undeclared runtime failures become
  // TApplicationException responses instead of crashing the PHP test server.
  out << indent() << "try {" << '\n';
  indent_up();

  // Generate the function call
  t_struct* arg_struct = tfunction->get_arglist();
  const std::vector<t_field*>& fields = arg_struct->get_members();
  vector<t_field*>::const_iterator f_iter;

  out << indent();
  if (!tfunction->is_oneway() && !tfunction->get_returntype()->is_void()) {
    out << "$result->success = ";
  }
  out << "$this->handler_->" << tfunction->get_name() << "(";
  bool first = true;
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
    if (first) {
      first = false;
    } else {
      out << ", ";
    }
    out << "$args->" << (*f_iter)->get_name();
  }
  out << ");" << '\n';

  indent_down();
  for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
    out << indent() << "} catch ("
               << php_namespace(get_true_type((*x_iter)->get_type())->get_program())
               << (*x_iter)->get_type()->get_name() << " $" << (*x_iter)->get_name() << ") {"
               << '\n';
    if (!tfunction->is_oneway()) {
      indent_up();
      out << indent() << "$result->" << (*x_iter)->get_name() << " = $"
                 << (*x_iter)->get_name() << ";" << '\n';
      indent_down();
    }
  }
  out << indent() << "} catch (TApplicationException $ex) {" << '\n';
  indent_up();
  if (!tfunction->is_oneway()) {
    out << indent() << "$output->writeMessageBegin('" << tfunction->get_name()
        << "', TMessageType::EXCEPTION, $seqid);" << '\n'
        << indent() << "$ex->write($output);" << '\n'
        << indent() << "$output->writeMessageEnd();" << '\n'
        << indent() << "$output->getTransport()->flush();" << '\n';
  }
  out << indent() << "return;" << '\n';
  indent_down();
  out << indent() << "} catch (\\Throwable $ex) {" << '\n';
  indent_up();
  if (!tfunction->is_oneway()) {
    out << indent() << "$x = new TApplicationException($ex->getMessage(), "
        << "TApplicationException::INTERNAL_ERROR);" << '\n'
        << indent() << "$output->writeMessageBegin('" << tfunction->get_name()
        << "', TMessageType::EXCEPTION, $seqid);" << '\n'
        << indent() << "$x->write($output);" << '\n'
        << indent() << "$output->writeMessageEnd();" << '\n'
        << indent() << "$output->getTransport()->flush();" << '\n';
  }
  out << indent() << "return;" << '\n';
  indent_down();
  out << indent() << "}" << '\n';

  // Shortcut out here for oneway functions
  if (tfunction->is_oneway()) {
    out << indent() << "return;" << '\n';
    indent_down();
    out << indent() << "}" << '\n';
    return;
  }

  out << indent() << "$bin_accel = ($output instanceof "
             << "TBinaryProtocolAccelerated) && function_exists('thrift_protocol_write_binary');"
             << '\n';

  out << indent() << "if ($bin_accel) {" << '\n';
  indent_up();

  out << indent() << "thrift_protocol_write_binary(" << '\n';

  indent_up();
  out << indent() << "$output,"<< '\n'
      << indent() << "'" << tfunction->get_name()<< "'," << '\n'
      << indent() << "TMessageType::REPLY,"<< '\n'
      << indent() << "$result," << '\n'
      << indent() << "$seqid," << '\n'
      << indent() << "$output->isStrictWrite()"<< '\n';

  indent_down();
  out << indent() << ");" << '\n';

  indent_down();
  out << indent() << "} else {" << '\n';
  indent_up();

  // Serialize the request header
  if (binary_inline_) {
    out << indent() << "$buff = pack('N', (TBinaryProtocol::VERSION_1 | "
        << "TMessageType::REPLY)); " << '\n' << indent() << "$buff .= pack('N', strlen('"
        << tfunction->get_name() << "'));" << '\n' << indent() << "$buff .= '"
        << tfunction->get_name() << "';" << '\n' << indent() << "$buff .= pack('N', $seqid);"
        << '\n' << indent() << "$result->write($buff);" << '\n' << indent()
        << "$output->write($buff);" << '\n' << indent() << "$output->flush();" << '\n';
  } else {
    out << indent() << "$output->writeMessageBegin('" << tfunction->get_name() << "', "
        << "TMessageType::REPLY, $seqid);" << '\n' << indent() << "$result->write($output);"
        << '\n' << indent() << "$output->writeMessageEnd();" << '\n' << indent()
        << "$output->getTransport()->flush();" << '\n';
  }

  scope_down(out);

  // Close function
  indent_down();
  out << indent() << "}" << '\n';
}

/**
 * Generates helper functions for a service.
 *
 * @param tservice The service to generate a header definition for
 */
void t_php_generator::generate_service_helpers(t_service* tservice) {
  vector<t_function*> functions = tservice->get_functions();
  vector<t_function*>::iterator f_iter;

  ofstream_with_content_based_conditional_update& f_struct_definition = f_service_;
  if (classmap_) {
    f_struct_definition << "// HELPER FUNCTIONS AND STRUCTURES" << '\n' << '\n';
  }

  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
    t_struct* ts = (*f_iter)->get_arglist();
    string name = ts->get_name();
    ts->set_name(service_name_ + "_" + name);

    if (!classmap_) {
      string f_struct_definition_name = package_dir_ + service_name_ + "_" + name + ".php";
      f_struct_definition.open(f_struct_definition_name.c_str());
      generate_service_header(tservice, f_struct_definition, PHPCS_DISABLES_SERVICE_HELPERS);
    }

    generate_php_struct_definition(f_struct_definition, ts);
    if (!classmap_) {
      f_struct_definition.close();
    }

    generate_php_function_helpers(tservice, *f_iter);
    ts->set_name(name);
  }
}

/**
 * Generates a struct and helpers for a function.
 *
 * @param tfunction The function
 */
void t_php_generator::generate_php_function_helpers(t_service* tservice, t_function* tfunction) {
  if (!tfunction->is_oneway()) {
    t_struct result(program_, service_name_ + "_" + tfunction->get_name() + "_result");
    t_field success(tfunction->get_returntype(), "success", 0);
    if (!tfunction->get_returntype()->is_void()) {
      result.append(&success);
    }

    t_struct* xs = tfunction->get_xceptions();
    const vector<t_field*>& fields = xs->get_members();
    vector<t_field*>::const_iterator f_iter;
    for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
      result.append(*f_iter);
    }

    ofstream_with_content_based_conditional_update& f_struct_helper = f_service_;
    if (!classmap_) {
      string f_struct_helper_name = package_dir_ + result.get_name() + ".php";
      f_struct_helper.open(f_struct_helper_name.c_str());
      generate_service_header(tservice, f_struct_helper, PHPCS_DISABLES_SERVICE_HELPERS);
    }
    generate_php_struct_definition(f_struct_helper, &result, false, true);
    if (!classmap_) {
      f_struct_helper.close();
    }
  }
}

/**
 * Generates a service interface definition.
 *
 * @param tservice The service to generate a header definition for
 */
void t_php_generator::generate_service_interface(t_service* tservice) {
  ofstream_with_content_based_conditional_update& f_service_interface = f_service_;
  if (!classmap_) {
    string f_service_interface_name = package_dir_ + service_name_ + "If.php";
    f_service_interface.open(f_service_interface_name.c_str());
    generate_service_header(tservice, f_service_interface);
  }

  string extends = "";
  string extends_if = "";
  if (tservice->get_extends() != nullptr) {
    extends = " extends " + php_namespace(tservice->get_extends()->get_program())
              + tservice->get_extends()->get_name();
    extends_if = " extends " + php_namespace(tservice->get_extends()->get_program())
                 + tservice->get_extends()->get_name() + "If";
  }
  generate_php_doc(f_service_interface, tservice);
  f_service_interface << "interface " << php_namespace_declaration(tservice) << "If" << extends_if << '\n'
                      << "{" << '\n';

  indent_up();
  vector<t_function*> functions = tservice->get_functions();
  vector<t_function*>::iterator f_iter;
  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
    generate_php_doc(f_service_interface, *f_iter);
    indent(f_service_interface) << "public function " << function_signature(*f_iter) << ";" << '\n';
  }
  indent_down();
  f_service_interface << "}" << '\n';

  // Close service interface file
  if (!classmap_) {
    f_service_interface.close();
  }
}

/**
 * Generates a REST interface
 */
void t_php_generator::generate_service_rest(t_service* tservice) {
  ofstream_with_content_based_conditional_update& f_service_rest = f_service_;
  if (!classmap_) {
    string f_service_rest_name = package_dir_ + service_name_ + "Rest.php";
    f_service_rest.open(f_service_rest_name.c_str());
    generate_service_header(tservice, f_service_rest);
  }

  string extends = "";
  string extends_if = "";
  if (tservice->get_extends() != nullptr) {
    extends = " extends " + php_namespace(tservice->get_extends()->get_program())
              + tservice->get_extends()->get_name();
    extends_if = " extends " + php_namespace(tservice->get_extends()->get_program())
                 + tservice->get_extends()->get_name() + "Rest";
  }
  f_service_rest << "class " << service_name_ << "Rest" << extends_if << '\n'
                 << "{" << '\n';
  indent_up();

  if (extends.empty()) {
    f_service_rest << indent() << "protected object $impl;" << '\n' << '\n';
  }

  f_service_rest << indent() << "public function __construct(object $impl)" << '\n'
                 << indent() << "{" << '\n'
                 << indent() << "    $this->impl = $impl;" << '\n'
                 << indent() << "}" << '\n' << '\n';

  vector<t_function*> functions = tservice->get_functions();
  vector<t_function*>::iterator f_iter;
  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
    indent(f_service_rest) << "public function " << (*f_iter)->get_name()
                           << "(array $request)" << type_to_return((*f_iter)->get_returntype()) << '\n';
    indent(f_service_rest) << "{" << '\n';
    indent_up();
    const vector<t_field*>& args = (*f_iter)->get_arglist()->get_members();
    vector<t_field*>::const_iterator a_iter;
    for (a_iter = args.begin(); a_iter != args.end(); ++a_iter) {
      t_type* atype = get_true_type((*a_iter)->get_type());
      string cast = type_to_cast(atype);
      string req = "$request['" + (*a_iter)->get_name() + "']";
      if (atype->is_bool()) {
        f_service_rest << indent() << "$" << (*a_iter)->get_name() << " = " << cast << "(!empty(" << req
                   << ") && (" << req << " !== 'false'));" << '\n';
      } else {
        f_service_rest << indent() << "$" << (*a_iter)->get_name() << " = isset(" << req << ") ? "
                   << cast << req << " : null;" << '\n';
      }
      /* slist no longer supported
      if (atype->is_string() && ((t_base_type*)atype)->is_string_list()) {
        f_service_rest << indent() << "$" << (*a_iter)->get_name() << " = explode(',', $"
                       << (*a_iter)->get_name() << ");" << '\n';
      } else */
      if (atype->is_map() || atype->is_list()) {
        f_service_rest << indent() << "$" << (*a_iter)->get_name() << " = json_decode($"
                       << (*a_iter)->get_name() << ", true);" << '\n';
      } else if (atype->is_set()) {
        f_service_rest << indent() << "$" << (*a_iter)->get_name() << " = array_fill_keys(json_decode($"
                       << (*a_iter)->get_name() << ", true), 1);" << '\n';
      } else if (atype->is_struct() || atype->is_xception()) {
        f_service_rest << indent() << "if ($" << (*a_iter)->get_name() << " !== null) {" << '\n'
                       << indent() << "    $" << (*a_iter)->get_name() << " = new "
                       << php_namespace(atype->get_program()) << atype->get_name() << "(json_decode($"
                       << (*a_iter)->get_name() << ", true));" << '\n' << indent() << "}" << '\n';
      }
    }
    const std::string return_kw = (*f_iter)->get_returntype()->is_void() ? "" : "return ";
    f_service_rest << indent() << return_kw << "$this->impl->" << (*f_iter)->get_name() << "("
               << argument_list((*f_iter)->get_arglist(), false) << ");" << '\n';
    indent_down();
    indent(f_service_rest) << "}" << '\n';
  }
  indent_down();
  f_service_rest << "}" << '\n';

  // Close service rest file
  f_service_rest << '\n';
  if (!classmap_) {
    f_service_rest.close();
  }
}

/**
 * Generates a service client definition.
 *
 * @param tservice The service to generate a server for.
 */
void t_php_generator::generate_service_client(t_service* tservice) {
  ofstream_with_content_based_conditional_update& f_service_client = f_service_;
  if (!classmap_) {
    string f_service_client_name = package_dir_ + service_name_ + "Client.php";
    f_service_client.open(f_service_client_name.c_str());
    generate_service_header(tservice, f_service_client, PHPCS_DISABLES_SNAKE_CASE_METHODS);
  }

  string extends = "";
  string extends_client = "";
  if (tservice->get_extends() != nullptr) {
    extends = tservice->get_extends()->get_name();
    extends_client = " extends " + php_namespace(tservice->get_extends()->get_program()) + extends
                     + "Client";
  }

  f_service_client << "class " << php_namespace_declaration(tservice) << "Client" << extends_client
             << " implements " << php_namespace(tservice->get_program()) << service_name_ << "If" << '\n'
             <<"{"<< '\n';
  indent_up();

  // Private members
  if (extends.empty()) {
    f_service_client << indent() << "protected ?TProtocol $input = null;" << '\n' << indent()
               << "protected ?TProtocol $output = null;" << '\n' << '\n';
    f_service_client << indent() << "protected int $seqid = 0;" << '\n' << '\n';
  }

  // Constructor function
  f_service_client << indent() << "public function __construct(TProtocol $input, ?TProtocol $output = null)" << '\n'
                   << indent() << "{" << '\n';

  indent_up();
  if (!extends.empty()) {
    f_service_client << indent() << "parent::__construct($input, $output);" << '\n';
  } else {
    f_service_client << indent() << "$this->input = $input;" << '\n'
                     << indent() << "$this->output = $output ? $output : $input;" << '\n';
  }

  indent_down();
  f_service_client << indent() << "}" << '\n' << '\n';

  // Generate client method implementations
  vector<t_function*> functions = tservice->get_functions();
  vector<t_function*>::const_iterator f_iter;
  for (f_iter = functions.begin(); f_iter != functions.end(); ++f_iter) {
    t_struct* arg_struct = (*f_iter)->get_arglist();
    const vector<t_field*>& fields = arg_struct->get_members();
    vector<t_field*>::const_iterator fld_iter;
    string funname = (*f_iter)->get_name();

    f_service_client << '\n';

    // Open function
    indent(f_service_client) << "public function " << function_signature(*f_iter) << '\n';
    scope_up(f_service_client);
    indent(f_service_client) << "$this->send_" << funname << "(";

    bool first = true;
    for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
      if (first) {
        first = false;
      } else {
        f_service_client << ", ";
      }
      f_service_client << "$" << (*fld_iter)->get_name();
    }
    f_service_client << ");" << '\n';

    if (!(*f_iter)->is_oneway()) {
      f_service_client << indent();
      if (!(*f_iter)->get_returntype()->is_void()) {
        f_service_client << "return ";
      }
      f_service_client << "$this->recv_" << funname << "();" << '\n';
    }
    scope_down(f_service_client);
    f_service_client << '\n';

    t_function send_function(g_type_void, "send_" + funname, (*f_iter)->get_arglist());
    indent(f_service_client) << "public function " << function_signature(&send_function) << '\n';
    scope_up(f_service_client);

    std::string argsname = php_namespace(tservice->get_program()) + service_name_ + "_"
                           + (*f_iter)->get_name() + "_args";

    f_service_client << indent() << "$args = new " << argsname << "();" << '\n';

    for (fld_iter = fields.begin(); fld_iter != fields.end(); ++fld_iter) {
      f_service_client << indent() << "$args->" << (*fld_iter)->get_name() << " = $"
                 << (*fld_iter)->get_name() << ";" << '\n';
    }

    f_service_client << indent() << "$bin_accel = ($this->output instanceof "
               << "TBinaryProtocolAccelerated) && function_exists('thrift_protocol_write_binary');"
               << '\n';

    f_service_client << indent() << "if ($bin_accel) {" << '\n';
    indent_up();

    string messageType = (*f_iter)->is_oneway() ? "TMessageType::ONEWAY" : "TMessageType::CALL";

    f_service_client << indent() << "thrift_protocol_write_binary(" << '\n';

    indent_up();
    f_service_client << indent() << "$this->output," << '\n'
               << indent() << "'" << (*f_iter)->get_name() << "'," << '\n'
               << indent() << messageType << "," << '\n'
               << indent() << "$args," << '\n'
               << indent() << "$this->seqid," << '\n'
               << indent() << "$this->output->isStrictWrite()" << '\n';

    indent_down();
    f_service_client << indent() << ");" << '\n';

    indent_down();
    f_service_client << indent() << "} else {" << '\n';
    indent_up();

    // Serialize the request header
    if (binary_inline_) {
      f_service_client << indent() << "$buff = pack('N', (TBinaryProtocol::VERSION_1 | " << messageType << "));" << '\n'
                       << indent() << "$buff .= pack('N', strlen('" << funname << "'));" << '\n'
                       << indent() << "$buff .= '" << funname << "';" << '\n' << indent()
                       << "$buff .= pack('N', $this->seqid);" << '\n';
    } else {
      f_service_client << indent() << "$this->output->writeMessageBegin('" << (*f_iter)->get_name()
                       << "', " << messageType << ", $this->seqid);" << '\n';
    }

    // Write to the stream
    if (binary_inline_) {
      f_service_client << indent() << "$args->write($buff);" << '\n' << indent()
                       << "$this->output->write($buff);" << '\n' << indent()
                       << "$this->output->flush();" << '\n';
    } else {
      f_service_client << indent() << "$args->write($this->output);" << '\n' << indent()
                       << "$this->output->writeMessageEnd();" << '\n' << indent()
                       << "$this->output->getTransport()->flush();" << '\n';
    }

    scope_down(f_service_client);

    scope_down(f_service_client);

    if (!(*f_iter)->is_oneway()) {
      std::string resultname = php_namespace(tservice->get_program()) + service_name_ + "_"
                               + (*f_iter)->get_name() + "_result";
      t_struct noargs(program_);

      t_function recv_function((*f_iter)->get_returntype(),
                               string("recv_") + (*f_iter)->get_name(),
                               &noargs);
      // Open function
      f_service_client << '\n' << indent() << "public function " << function_signature(&recv_function)
                       << '\n';
      scope_up(f_service_client);

      f_service_client << indent() << "$bin_accel = ($this->input instanceof "
                       << "TBinaryProtocolAccelerated)"
                       << " && function_exists('thrift_protocol_read_binary');" << '\n';

      f_service_client << indent() << "if ($bin_accel) {" << '\n';

      indent_up();
      f_service_client << indent() << "$result = thrift_protocol_read_binary(" << '\n';

      indent_up();
      f_service_client << indent() << "$this->input," << '\n'
                       << indent() << "'" << resultname << "'," << '\n'
                       << indent() << "$this->input->isStrictRead()" << '\n';

      indent_down();
      f_service_client << indent() << ");" << '\n';

      indent_down();
      f_service_client << indent() << "} else {" << '\n';

      indent_up();
      f_service_client << indent() << "$rseqid = 0;" << '\n'
                       << indent() << "$fname = null;" << '\n'
                       << indent() << "$mtype = 0;" << '\n' << '\n';

      if (binary_inline_) {
        t_field ffname(g_type_string, "fname");
        t_field fseqid(g_type_i32, "rseqid");
        f_service_client << indent() << "$ver = unpack('N', $this->input->readAll(4));" << '\n'
                         << indent() << "$ver = $ver[1];" << '\n' << indent() << "$mtype = $ver & 0xff;"
                         << '\n' << indent() << "$ver = $ver & TBinaryProtocol::VERSION_MASK;" << '\n'
                         << indent() << "if ($ver != TBinaryProtocol::VERSION_1) {" << '\n'
                         << indent() << "    throw new TProtocolException('Bad version identifier: ' . $ver, "
                         << "TProtocolException::BAD_VERSION);" << '\n'
                         << indent() << "}" << '\n';
        generate_deserialize_field(f_service_client, &ffname, "", true);
        generate_deserialize_field(f_service_client, &fseqid, "", true);
      } else {
        f_service_client << indent() << "$this->input->readMessageBegin($fname, $mtype, $rseqid);" << '\n'
                         << indent() << "if ($mtype == TMessageType::EXCEPTION) {" << '\n';

        indent_up();
        f_service_client << indent() << "$x = new TApplicationException();" << '\n'
                         << indent() << "$x->read($this->input);" << '\n'
                         << indent() << "$this->input->readMessageEnd();" << '\n'
                         << indent() << "throw $x;" << '\n';
        indent_down();
        f_service_client << indent() << "}" << '\n';
      }

      f_service_client << indent() << "$result = new " << resultname << "();" << '\n'
                       << indent() << "$result->read($this->input);" << '\n';

      if (!binary_inline_) {
        f_service_client << indent() << "$this->input->readMessageEnd();" << '\n';
      }

      scope_down(f_service_client);

      // Careful, only return result if not a void function
      if (!(*f_iter)->get_returntype()->is_void()) {
        f_service_client << indent() << "if ($result->success !== null) {" << '\n';

        indent_up();
        f_service_client << indent() << "return $result->success;" << '\n';

        indent_down();
        f_service_client << indent() << "}" << '\n';
      }

      t_struct* xs = (*f_iter)->get_xceptions();
      const std::vector<t_field*>& xceptions = xs->get_members();
      vector<t_field*>::const_iterator x_iter;
      for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
        f_service_client << indent() << "if ($result->" << (*x_iter)->get_name() << " !== null) {" << '\n';

        indent_up();
        f_service_client << indent() << "throw $result->" << (*x_iter)->get_name() << ";" << '\n';

        indent_down();
        f_service_client << indent() << "}" << '\n';
      }

      // Careful, only return _result if not a void function
      if ((*f_iter)->get_returntype()->is_void()) {
        indent(f_service_client) << "return;" << '\n';
      } else {
        f_service_client << indent() << "throw new \\Exception(\"" << (*f_iter)->get_name()
                         << " failed: unknown result\");" << '\n';
      }

      // Close function
      scope_down(f_service_client);
    }
  }

  indent_down();
  f_service_client << "}" << '\n';

  // Close service client file
  if (!classmap_) {
    f_service_client.close();
  }
}

/**
 * Deserializes a field of any type.
 */
void t_php_generator::generate_deserialize_field(ostream& out,
                                                 t_field* tfield,
                                                 string prefix,
                                                 bool inclass) {
  t_type* type = get_true_type(tfield->get_type());

  if (type->is_void()) {
    throw "CANNOT GENERATE DESERIALIZE CODE FOR void TYPE: " + prefix + tfield->get_name();
  }

  string name = prefix + tfield->get_name();

  if (type->is_struct() || type->is_xception()) {
    generate_deserialize_struct(out, (t_struct*)type, name);
  } else {

    if (type->is_container()) {
      generate_deserialize_container(out, type, name);
    } else if (type->is_base_type() || type->is_enum()) {

      if (binary_inline_) {
        std::string itrans = (inclass ? "$this->input" : "$input");

        if (type->is_base_type()) {
          t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
          switch (tbase) {
          case t_base_type::TYPE_VOID:
            throw "compiler error: cannot serialize void field in a struct: " + name;
            break;
          case t_base_type::TYPE_STRING:
            out << indent() << "$len = unpack('N', " << itrans << "->readAll(4));" << '\n'
                << indent() << "$len = $len[1];" << '\n' << indent() << "if ($len > 0x7fffffff) {"
                << '\n' << indent() << "    $len = 0 - (($len - 1) ^ 0xffffffff);" << '\n' << indent()
                << "}" << '\n' << indent() << "$" << name << " = " << itrans << "->readAll($len);"
                << '\n';
            break;
          case t_base_type::TYPE_BOOL:
            // Stage through a local; the typed property would reject the
            // intermediate `array|false` returned by unpack().
            out << indent() << "$val = unpack('c', " << itrans << "->readAll(1));"
                << '\n' << indent() << "$" << name << " = (bool)$val[1];" << '\n';
            break;
          case t_base_type::TYPE_I8:
            out << indent() << "$val = unpack('c', " << itrans << "->readAll(1));"
                << '\n' << indent() << "$" << name << " = $val[1];" << '\n';
            break;
          case t_base_type::TYPE_I16:
            out << indent() << "$val = unpack('n', " << itrans << "->readAll(2));" << '\n'
                << indent() << "$val = $val[1];" << '\n' << indent() << "if ($val > 0x7fff) {"
                << '\n' << indent() << "    $val = 0 - (($val - 1) ^ 0xffff);" << '\n' << indent()
                << "}" << '\n' << indent() << "$" << name << " = $val;" << '\n';
            break;
          case t_base_type::TYPE_I32:
            out << indent() << "$val = unpack('N', " << itrans << "->readAll(4));" << '\n'
                << indent() << "$val = $val[1];" << '\n' << indent() << "if ($val > 0x7fffffff) {"
                << '\n' << indent() << "    $val = 0 - (($val - 1) ^ 0xffffffff);" << '\n' << indent()
                << "}" << '\n' << indent() << "$" << name << " = $val;" << '\n';
            break;
          case t_base_type::TYPE_I64:
            out << indent() << "$arr = unpack('N2', " << itrans << "->readAll(8));" << '\n'
                << indent() << "if ($arr[1] & 0x80000000) {" << '\n' << indent()
                << "    $arr[1] = $arr[1] ^ 0xFFFFFFFF;" << '\n' << indent()
                << "    $arr[2] = $arr[2] ^ 0xFFFFFFFF;" << '\n' << indent() << "    $" << name
                << " = 0 - $arr[1] * 4294967296 - $arr[2] - 1;" << '\n' << indent() << "} else {"
                << '\n' << indent() << "    $" << name << " = $arr[1] * 4294967296 + $arr[2];" << '\n'
                << indent() << "}" << '\n';
            break;
          case t_base_type::TYPE_DOUBLE:
            out << indent() << "$arr = unpack('d', strrev(" << itrans << "->readAll(8)));" << '\n'
                << indent() << "$" << name << " = $arr[1];" << '\n';
            break;
          case t_base_type::TYPE_UUID:
            out << indent() << "$uuidBin = " << itrans << "->readAll(16);" << '\n'
                << indent() << "$uuidHex = bin2hex($uuidBin);" << '\n'
                << indent() << "$" << name << " = substr($uuidHex, 0, 8) . '-' . "
                << "substr($uuidHex, 8, 4) . '-' . "
                << "substr($uuidHex, 12, 4) . '-' . "
                << "substr($uuidHex, 16, 4) . '-' . "
                << "substr($uuidHex, 20, 12);" << '\n';
            break;
          default:
            throw "compiler error: no PHP name for base type " + t_base_type::t_base_name(tbase)
                + tfield->get_name();
          }
        } else if (type->is_enum()) {
          out << indent() << "$val = unpack('N', " << itrans << "->readAll(4));" << '\n' << indent()
              << "$val = $val[1];" << '\n' << indent() << "if ($val > 0x7fffffff) {" << '\n'
              << indent() << "    $val = 0 - (($val - 1) ^ 0xffffffff);" << '\n' << indent() << "}"
              << '\n' << indent() << "$" << name << " = $val;" << '\n';
        }
      } else {

        indent(out) << "$xfer += $input->";

        if (type->is_base_type()) {
          t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
          switch (tbase) {
          case t_base_type::TYPE_VOID:
            throw "compiler error: cannot serialize void field in a struct: " + name;
            break;
          case t_base_type::TYPE_STRING:
            out << "readString($" << name << ");";
            break;
          case t_base_type::TYPE_BOOL:
            out << "readBool($" << name << ");";
            break;
          case t_base_type::TYPE_I8:
            out << "readByte($" << name << ");";
            break;
          case t_base_type::TYPE_I16:
            out << "readI16($" << name << ");";
            break;
          case t_base_type::TYPE_I32:
            out << "readI32($" << name << ");";
            break;
          case t_base_type::TYPE_I64:
            out << "readI64($" << name << ");";
            break;
          case t_base_type::TYPE_DOUBLE:
            out << "readDouble($" << name << ");";
            break;
          case t_base_type::TYPE_UUID:
            out << "readUuid($" << name << ");";
            break;
          default:
            throw "compiler error: no PHP name for base type " + t_base_type::t_base_name(tbase);
          }
        } else if (type->is_enum()) {
          out << "readI32($" << name << ");";
        }
        out << '\n';
      }
    } else {
      printf("DO NOT KNOW HOW TO DESERIALIZE FIELD '%s' TYPE '%s'\n",
             tfield->get_name().c_str(),
             type->get_name().c_str());
    }
  }
}

/**
 * Generates an unserializer for a variable. This makes two key assumptions,
 * first that there is a const char* variable named data that points to the
 * buffer for deserialization, and that there is a variable protocol which
 * is a reference to a TProtocol serialization object.
 */
void t_php_generator::generate_deserialize_struct(ostream& out, t_struct* tstruct, string prefix) {
  out << indent() << "$" << prefix << " = new " << php_namespace(tstruct->get_program())
      << tstruct->get_name() << "();" << '\n' << indent() << "$xfer += $" << prefix
      << "->read($input);" << '\n';
}

void t_php_generator::generate_deserialize_container(ostream& out, t_type* ttype, string prefix) {
  string size = tmp("_size");
  string ktype = tmp("_ktype");
  string vtype = tmp("_vtype");
  string etype = tmp("_etype");

  t_field fsize(g_type_i32, size);
  t_field fktype(g_type_i8, ktype);
  t_field fvtype(g_type_i8, vtype);
  t_field fetype(g_type_i8, etype);

  out << indent() << "$" << prefix << " = [];" << '\n' << indent() << "$" << size << " = 0;"
      << '\n';

  // Declare variables, read header
  if (ttype->is_map()) {
    out << indent() << "$" << ktype << " = 0;" << '\n' << indent() << "$" << vtype << " = 0;"
        << '\n';
    if (binary_inline_) {
      generate_deserialize_field(out, &fktype);
      generate_deserialize_field(out, &fvtype);
      generate_deserialize_field(out, &fsize);
    } else {
      out << indent() << "$xfer += $input->readMapBegin("
          << "$" << ktype << ", $" << vtype << ", $" << size << ");" << '\n';
    }
  } else if (ttype->is_set()) {
    if (binary_inline_) {
      generate_deserialize_field(out, &fetype);
      generate_deserialize_field(out, &fsize);
    } else {
      out << indent() << "$" << etype << " = 0;" << '\n' << indent()
          << "$xfer += $input->readSetBegin("
          << "$" << etype << ", $" << size << ");" << '\n';
    }
  } else if (ttype->is_list()) {
    if (binary_inline_) {
      generate_deserialize_field(out, &fetype);
      generate_deserialize_field(out, &fsize);
    } else {
      out << indent() << "$" << etype << " = 0;" << '\n' << indent()
          << "$xfer += $input->readListBegin("
          << "$" << etype << ", $" << size << ");" << '\n';
    }
  }

  // For loop iterates over elements
  string i = tmp("_i");
  indent(out) << "for ($" << i << " = 0; $" << i << " < $" << size << "; ++$" << i << ") {" << '\n';

  indent_up();

  if (ttype->is_map()) {
    generate_deserialize_map_element(out, (t_map*)ttype, prefix);
  } else if (ttype->is_set()) {
    generate_deserialize_set_element(out, (t_set*)ttype, prefix);
  } else if (ttype->is_list()) {
    generate_deserialize_list_element(out, (t_list*)ttype, prefix);
  }

  scope_down(out);

  if (!binary_inline_) {
    // Read container end
    if (ttype->is_map()) {
      indent(out) << "$xfer += $input->readMapEnd();" << '\n';
    } else if (ttype->is_set()) {
      indent(out) << "$xfer += $input->readSetEnd();" << '\n';
    } else if (ttype->is_list()) {
      indent(out) << "$xfer += $input->readListEnd();" << '\n';
    }
  }
}

/**
 * Generates code to deserialize a map
 */
void t_php_generator::generate_deserialize_map_element(ostream& out, t_map* tmap, string prefix) {
  string key = tmp("key");
  string val = tmp("val");
  t_field fkey(tmap->get_key_type(), key);
  t_field fval(tmap->get_val_type(), val);

  indent(out) << declare_field(&fkey, true, true) << '\n';
  indent(out) << declare_field(&fval, true, true) << '\n';

  generate_deserialize_field(out, &fkey);
  generate_deserialize_field(out, &fval);

  indent(out) << "$" << prefix << "[$" << key << "] = $" << val << ";" << '\n';
}

void t_php_generator::generate_deserialize_set_element(ostream& out, t_set* tset, string prefix) {
  string elem = tmp("elem");
  t_field felem(tset->get_elem_type(), elem);

  indent(out) << "$" << elem << " = null;" << '\n';

  generate_deserialize_field(out, &felem);

  t_type* elem_type = tset->get_elem_type();
  if(php_is_scalar(elem_type)) {
    indent(out) << "$" << prefix << "[$" << elem << "] = true;" << '\n';
  } else {
    indent(out) << "$" << prefix << "[] = $" << elem << ";" << '\n';
  }
}

void t_php_generator::generate_deserialize_list_element(ostream& out,
                                                        t_list* tlist,
                                                        string prefix) {
  string elem = tmp("elem");
  t_field felem(tlist->get_elem_type(), elem);

  indent(out) << "$" << elem << " = null;" << '\n';

  generate_deserialize_field(out, &felem);

  indent(out) << "$" << prefix << "[] = $" << elem << ";" << '\n';
}

/**
 * Serializes a field of any type.
 *
 * @param tfield The field to serialize
 * @param prefix Name to prepend to field name
 */
void t_php_generator::generate_serialize_field(ostream& out, t_field* tfield, string prefix) {
  t_type* type = get_true_type(tfield->get_type());

  // Do nothing for void types
  if (type->is_void()) {
    throw "CANNOT GENERATE SERIALIZE CODE FOR void TYPE: " + prefix + tfield->get_name();
  }

  if (type->is_struct() || type->is_xception()) {
    generate_serialize_struct(out, (t_struct*)type, prefix + tfield->get_name());
  } else if (type->is_container()) {
    generate_serialize_container(out, type, prefix + tfield->get_name());
  } else if (type->is_base_type() || type->is_enum()) {

    string name = prefix + tfield->get_name();

    if (binary_inline_) {
      if (type->is_base_type()) {
        t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
        switch (tbase) {
        case t_base_type::TYPE_VOID:
          throw "compiler error: cannot serialize void field in a struct: " + name;
          break;
        case t_base_type::TYPE_STRING:
          out << indent() << "$output .= pack('N', strlen($" << name << "));" << '\n' << indent()
              << "$output .= $" << name << ";" << '\n';
          break;
        case t_base_type::TYPE_BOOL:
          out << indent() << "$output .= pack('c', $" << name << " ? 1 : 0);" << '\n';
          break;
        case t_base_type::TYPE_I8:
          out << indent() << "$output .= pack('c', $" << name << ");" << '\n';
          break;
        case t_base_type::TYPE_I16:
          out << indent() << "$output .= pack('n', $" << name << ");" << '\n';
          break;
        case t_base_type::TYPE_I32:
          out << indent() << "$output .= pack('N', $" << name << ");" << '\n';
          break;
        case t_base_type::TYPE_I64:
          out << indent() << "$output .= pack('N2', $" << name << " >> 32, $" << name
              << " & 0xFFFFFFFF);" << '\n';
          break;
        case t_base_type::TYPE_DOUBLE:
          out << indent() << "$output .= strrev(pack('d', $" << name << "));" << '\n';
          break;
        case t_base_type::TYPE_UUID:
          out << indent() << "$output .= hex2bin(str_replace('-', '', $" << name << "));" << '\n';
          break;
        default:
          throw "compiler error: no PHP name for base type " + t_base_type::t_base_name(tbase);
        }
      } else if (type->is_enum()) {
        out << indent() << "$output .= pack('N', $" << name << ");" << '\n';
      }
    } else {

      indent(out) << "$xfer += $output->";

      if (type->is_base_type()) {
        t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
        switch (tbase) {
        case t_base_type::TYPE_VOID:
          throw "compiler error: cannot serialize void field in a struct: " + name;
          break;
        case t_base_type::TYPE_STRING:
          out << "writeString($" << name << ");";
          break;
        case t_base_type::TYPE_BOOL:
          out << "writeBool($" << name << ");";
          break;
        case t_base_type::TYPE_I8:
          out << "writeByte($" << name << ");";
          break;
        case t_base_type::TYPE_I16:
          out << "writeI16($" << name << ");";
          break;
        case t_base_type::TYPE_I32:
          out << "writeI32($" << name << ");";
          break;
        case t_base_type::TYPE_I64:
          out << "writeI64($" << name << ");";
          break;
        case t_base_type::TYPE_DOUBLE:
          out << "writeDouble($" << name << ");";
          break;
        case t_base_type::TYPE_UUID:
          out << "writeUuid($" << name << ");";
          break;
        default:
          throw "compiler error: no PHP name for base type " + t_base_type::t_base_name(tbase);
        }
      } else if (type->is_enum()) {
        out << "writeI32($" << name << ");";
      }
      out << '\n';
    }
  } else {
    printf("DO NOT KNOW HOW TO SERIALIZE FIELD '%s%s' TYPE '%s'\n",
           prefix.c_str(),
           tfield->get_name().c_str(),
           type->get_name().c_str());
  }
}

/**
 * Serializes all the members of a struct.
 *
 * @param tstruct The struct to serialize
 * @param prefix  String prefix to attach to all fields
 */
void t_php_generator::generate_serialize_struct(ostream& out, t_struct* tstruct, string prefix) {
  (void)tstruct;
  indent(out) << "$xfer += $" << prefix << "->write($output);" << '\n';
}

/**
 * Writes out a container
 */
void t_php_generator::generate_serialize_container(ostream& out, t_type* ttype, string prefix) {
  if (ttype->is_map()) {
    if (binary_inline_) {
      out << indent() << "$output .= pack('c', " << type_to_enum(((t_map*)ttype)->get_key_type())
          << ");" << '\n' << indent() << "$output .= pack('c', "
          << type_to_enum(((t_map*)ttype)->get_val_type()) << ");" << '\n' << indent()
          << "$output .= strrev(pack('l', count($" << prefix << ")));" << '\n';
    } else {
      indent(out) << "$output->writeMapBegin(" << type_to_enum(((t_map*)ttype)->get_key_type())
                  << ", " << type_to_enum(((t_map*)ttype)->get_val_type()) << ", "
                  << "count($" << prefix << "));" << '\n';
    }
  } else if (ttype->is_set()) {
    if (binary_inline_) {
      out << indent() << "$output .= pack('c', " << type_to_enum(((t_set*)ttype)->get_elem_type())
          << ");" << '\n' << indent() << "$output .= strrev(pack('l', count($" << prefix << ")));"
          << '\n';

    } else {
      indent(out) << "$output->writeSetBegin(" << type_to_enum(((t_set*)ttype)->get_elem_type())
                  << ", "
                  << "count($" << prefix << "));" << '\n';
    }
  } else if (ttype->is_list()) {
    if (binary_inline_) {
      out << indent() << "$output .= pack('c', " << type_to_enum(((t_list*)ttype)->get_elem_type())
          << ");" << '\n' << indent() << "$output .= strrev(pack('l', count($" << prefix << ")));"
          << '\n';

    } else {
      indent(out) << "$output->writeListBegin(" << type_to_enum(((t_list*)ttype)->get_elem_type())
                  << ", "
                  << "count($" << prefix << "));" << '\n';
    }
  }

  if (ttype->is_map()) {
    string kiter = tmp("kiter");
    string viter = tmp("viter");
    indent(out) << "foreach ($" << prefix << " as "
                << "$" << kiter << " => $" << viter << ") {" << '\n';
    indent_up();
    generate_serialize_map_element(out, (t_map*)ttype, kiter, viter);
    scope_down(out);
  } else if (ttype->is_set()) {
    string iter = tmp("iter");
    string iter_val = tmp("iter");
    indent(out) << "foreach ($" << prefix << " as $" << iter << " => $" << iter_val << ") {" << '\n';
    indent_up();

    t_type* elem_type = ((t_set*)ttype)->get_elem_type();
    if(php_is_scalar(elem_type)) {
      generate_serialize_set_element(out, (t_set*)ttype, iter);
    } else {
      generate_serialize_set_element(out, (t_set*)ttype, iter_val);
    }
    scope_down(out);
  } else if (ttype->is_list()) {
    string iter = tmp("iter");
    indent(out) << "foreach ($" << prefix << " as $" << iter << ") {" << '\n';
    indent_up();
    generate_serialize_list_element(out, (t_list*)ttype, iter);
    scope_down(out);
  }

  if (!binary_inline_) {
    if (ttype->is_map()) {
      indent(out) << "$output->writeMapEnd();" << '\n';
    } else if (ttype->is_set()) {
      indent(out) << "$output->writeSetEnd();" << '\n';
    } else if (ttype->is_list()) {
      indent(out) << "$output->writeListEnd();" << '\n';
    }
  }
}

/**
 * PHP foreach yields keys with their stored array-key type — numeric strings
 * are normalised to int at insertion (`['123' => x]` becomes `[123 => x]`),
 * and bool keys collapse to int (`[true => x]` becomes `[1 => x]`). Under
 * `declare(strict_types=1)` the typed `writeXxx()` library calls then refuse
 * the coerced value. Emit a single-line cast back to the declared Thrift type
 * before the write so the runtime contract holds.
 *
 * Reuses `type_to_cast`, which already maps every Thrift base type and enum
 * to its PHP cast prefix; non-castable types (struct/container/void) yield
 * an empty string and are skipped.
 */
void t_php_generator::emit_array_key_recast(ostream& out, t_type* ttype, const std::string& var) {
  std::string cast = type_to_cast(get_true_type(ttype));
  if (cast.empty()) {
    return;
  }
  indent(out) << "$" << var << " = " << cast << "$" << var << ";" << '\n';
}

/**
 * Serializes the members of a map.
 *
 */
void t_php_generator::generate_serialize_map_element(ostream& out,
                                                     t_map* tmap,
                                                     string kiter,
                                                     string viter) {
  // PHP arrays silently coerce numeric-string keys to int (e.g. '123' => 123).
  // Cast back to the declared base type so the typed writeXxx() call sites in
  // strict-types generated files accept the value.
  emit_array_key_recast(out, tmap->get_key_type(), kiter);

  t_field kfield(tmap->get_key_type(), kiter);
  generate_serialize_field(out, &kfield, "");

  t_field vfield(tmap->get_val_type(), viter);
  generate_serialize_field(out, &vfield, "");
}

/**
 * Serializes the members of a set.
 */
void t_php_generator::generate_serialize_set_element(ostream& out, t_set* tset, string iter) {
  // Set element used as PHP array key — same coercion concern as map keys;
  // see comment on emit_array_key_recast. Helper no-ops for non-castable
  // element types.
  emit_array_key_recast(out, tset->get_elem_type(), iter);

  t_field efield(tset->get_elem_type(), iter);
  generate_serialize_field(out, &efield, "");
}

/**
 * Serializes the members of a list.
 */
void t_php_generator::generate_serialize_list_element(ostream& out, t_list* tlist, string iter) {
  t_field efield(tlist->get_elem_type(), iter);
  generate_serialize_field(out, &efield, "");
}

/**
 * Emits a PHPDoc comment for the given contents.
 *
 * Equivalent to the base `generate_docstring_comment` with prefix `" * "`,
 * except empty docstring lines are emitted as `" *"` (no trailing space) so
 * the result is clean under PSR-12 / Squiz `SuperfluousWhitespace` sniffs.
 */
void t_php_generator::generate_php_docstring_comment(ostream& out, string contents) {
  indent(out) << "/**" << '\n';
  std::stringstream docs(contents, std::ios_base::in);
  while (!(docs.eof() || docs.fail())) {
    char line[1024];
    docs.getline(line, 1024);
    if (strlen(line) > 0) {
      indent(out) << " * " << line << '\n';
    } else if (!docs.eof()) {
      indent(out) << " *" << '\n';
    }
  }
  indent(out) << " */" << '\n';
}

/**
 * Emits a PHPDoc comment if the provided object has a doc in Thrift
 */
void t_php_generator::generate_php_doc(ostream& out, t_doc* tdoc) {
  if (tdoc->has_doc()) {
    generate_php_docstring_comment(out, tdoc->get_doc());
  }
}

/**
 * Emits a PHPDoc comment for a field
 */
void t_php_generator::generate_php_doc(ostream& out, t_field* field) {
  t_type* type = field->get_type()->get_true_type();
  // Native PHP property types already carry the type info for everything
  // except containers (where `array` loses the element type). Only emit
  // a docblock when it adds value: a user-written `.thrift` doc string,
  // or an `@var` for a container with informative element type.
  bool has_user_doc = field->has_doc();
  bool var_adds_value = type->is_container();
  if (!has_user_doc && !var_adds_value) {
    return;
  }

  stringstream ss;
  if (has_user_doc) {
    ss << field->get_doc() << '\n';
  }
  if (var_adds_value) {
    ss << "@var " << type_to_phpdoc(type) << '\n';
  }
  generate_php_docstring_comment(out, ss.str());
}

/**
 * Emits a PHPDoc comment for a function
 */
void t_php_generator::generate_php_doc(ostream& out, t_function* function) {
  stringstream ss;
  if (function->has_doc()) {
    ss << function->get_doc() << '\n';
  }

  // generate parameter types doc
  const vector<t_field*>& args = function->get_arglist()->get_members();
  vector<t_field*>::const_iterator a_iter;
  for (a_iter = args.begin(); a_iter != args.end(); ++a_iter) {
    t_field* arg = *a_iter;
    ss << "@param " << type_to_phpdoc(arg->get_type()) << " $" << arg->get_name();
    if (arg->has_doc()) {
      ss << " " << arg->get_doc();
    }
    ss << '\n';
  }

  // generate return type doc
  t_type* ret_type = function->get_returntype();
  if (!ret_type->is_void() || ret_type->has_doc()) {
    ss << "@return " << type_to_phpdoc(ret_type);
    if (ret_type->has_doc()) {
      ss << " " << ret_type->get_doc();
    }
    ss << '\n';
  }

  // generate exceptions doc
  const vector<t_field*>& excs = function->get_xceptions()->get_members();
  vector<t_field*>::const_iterator e_iter;
  for (e_iter = excs.begin(); e_iter != excs.end(); ++e_iter) {
    t_field* exc = *e_iter;
    ss << "@throws " << type_to_phpdoc(exc->get_type());
    if (exc->has_doc()) {
      ss << " " << exc->get_doc();
    }
    ss << '\n';
  }

  generate_php_docstring_comment(out, ss.str());
}

/**
 * Declares a field, which may include initialization as necessary.
 *
 * @param ttype The type
 */
string t_php_generator::declare_field(t_field* tfield, bool init, bool obj) {
  string result = "$" + tfield->get_name();
  if (init) {
    t_type* type = get_true_type(tfield->get_type());
    if (type->is_base_type()) {
      t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
      switch (tbase) {
      case t_base_type::TYPE_VOID:
        break;
      case t_base_type::TYPE_STRING:
      case t_base_type::TYPE_UUID:
        result += " = ''";
        break;
      case t_base_type::TYPE_BOOL:
        result += " = false";
        break;
      case t_base_type::TYPE_I8:
      case t_base_type::TYPE_I16:
      case t_base_type::TYPE_I32:
      case t_base_type::TYPE_I64:
        result += " = 0";
        break;
      case t_base_type::TYPE_DOUBLE:
        result += " = 0.0";
        break;
      default:
        throw "compiler error: no PHP initializer for base type " + t_base_type::t_base_name(tbase);
      }
    } else if (type->is_enum()) {
      result += " = 0";
    } else if (type->is_container()) {
      result += " = []";
    } else if (type->is_struct() || type->is_xception()) {
      if (obj) {
        result += " = new " + php_namespace(type->get_program()) + type->get_name() + "()";
      } else {
        result += " = null";
      }
    }
  }
  return result + ";";
}

/**
 * Renders a function signature of the form 'type name(args)'
 *
 * @param tfunction Function definition
 * @return String of rendered function definition
 */
string t_php_generator::function_signature(t_function* tfunction, string prefix) {
  return prefix + tfunction->get_name()
         + "(" + argument_list(tfunction->get_arglist()) + ")"
         + type_to_return(tfunction->get_returntype());
}

/**
 * Renders a field list
 */
string t_php_generator::argument_list(t_struct* tstruct, bool addTypeHints) {
  string result = "";

  const vector<t_field*>& fields = tstruct->get_members();
  vector<t_field*>::const_iterator f_iter;
  bool first = true;
  for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
    if (first) {
      first = false;
    } else {
      result += ", ";
    }

    t_type* type = (*f_iter)->get_type();

    if (addTypeHints) {
      // Thrift fields admit null at construction (`?T`); same convention
      // for service-method parameters keeps PHP callers BC-compatible
      // while still narrowing accepted types under strict_types.
      result += "?" + type_to_native(type) + " ";
    }

    result += "$" + (*f_iter)->get_name();
  }
  return result;
}

/**
 * Renders a PHP return-type clause for the given Thrift type, e.g. ": void"
 * for `void` returns or ": ?T" for value returns (nullable to allow the
 * exception-result idiom). Used by function_signature.
 */
string t_php_generator::type_to_return(t_type* type) {
  if (type->is_void()) {
    return ": void";
  }
  return ": ?" + type_to_native(type);
}

/**
 * Gets a typecast string for a particular type.
 */
string t_php_generator::type_to_cast(t_type* type) {
  if (type->is_base_type()) {
    t_base_type* btype = (t_base_type*)type;
    switch (btype->get_base()) {
    case t_base_type::TYPE_BOOL:
      return "(bool)";
    case t_base_type::TYPE_I8:
    case t_base_type::TYPE_I16:
    case t_base_type::TYPE_I32:
    case t_base_type::TYPE_I64:
      return "(int)";
    case t_base_type::TYPE_DOUBLE:
      return "(float)";
    case t_base_type::TYPE_STRING:
      return "(string)";
    case t_base_type::TYPE_UUID:
      return "(string)";
    default:
      return "";
    }
  } else if (type->is_enum()) {
    return "(int)";
  }
  return "";
}

/**
 * Converts the parse type to a C++ enum string for the given type.
 */
string t_php_generator::type_to_enum(t_type* type) {
  type = get_true_type(type);

  if (type->is_base_type()) {
    t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
    switch (tbase) {
    case t_base_type::TYPE_VOID:
      throw "NO T_VOID CONSTRUCT";
    case t_base_type::TYPE_STRING:
      return "TType::STRING";
    case t_base_type::TYPE_BOOL:
      return "TType::BOOL";
    case t_base_type::TYPE_I8:
      return "TType::BYTE";
    case t_base_type::TYPE_I16:
      return "TType::I16";
    case t_base_type::TYPE_I32:
      return "TType::I32";
    case t_base_type::TYPE_I64:
      return "TType::I64";
    case t_base_type::TYPE_DOUBLE:
      return "TType::DOUBLE";
    case t_base_type::TYPE_UUID:
      return "TType::UUID";
    default:
      throw "compiler error: unhandled type";
    }
  } else if (type->is_enum()) {
    return "TType::I32";
  } else if (type->is_struct() || type->is_xception()) {
    return "TType::STRUCT";
  } else if (type->is_map()) {
    return "TType::MAP";
  } else if (type->is_set()) {
    return "TType::SET";
  } else if (type->is_list()) {
    return "TType::LST";
  }

  throw "INVALID TYPE IN type_to_enum: " + type->get_name();
}

/**
 * Converts the parse type to a PHPDoc string for the given type.
 */
string t_php_generator::type_to_phpdoc(t_type* type) {
  type = get_true_type(type);

  if (type->is_base_type()) {
    t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
    switch (tbase) {
    case t_base_type::TYPE_VOID:
      return "void";
    case t_base_type::TYPE_STRING:
      return "string";
    case t_base_type::TYPE_BOOL:
      return "bool";
    case t_base_type::TYPE_I8:
      return "int";
    case t_base_type::TYPE_I16:
      return "int";
    case t_base_type::TYPE_I32:
      return "int";
    case t_base_type::TYPE_I64:
      return "int";
    case t_base_type::TYPE_DOUBLE:
      return "double";
    case t_base_type::TYPE_UUID:
      return "string";
    default:
      throw "compiler error: unhandled type";
    }
  } else if (type->is_enum()) {
    return "int";
  } else if (type->is_struct() || type->is_xception()) {
    return php_namespace(type->get_program()) + type->get_name();
  } else if (type->is_map()) {
    return "array";
  } else if (type->is_set()) {
    t_set* tset = static_cast<t_set*>(type);
    t_type* t_elem = tset->get_elem_type();
    if (t_elem->is_container()) {
      return "(" + type_to_phpdoc(t_elem) + ")[]";
    } else {
      return type_to_phpdoc(t_elem) + "[]";
    }
  } else if (type->is_list()) {
    t_list* tlist = static_cast<t_list*>(type);
    t_type* t_elem = tlist->get_elem_type();
    if (t_elem->is_container()) {
      return "(" + type_to_phpdoc(t_elem) + ")[]";
    } else {
      return type_to_phpdoc(t_elem) + "[]";
    }
  }

  throw "INVALID TYPE IN type_to_enum: " + type->get_name();
}

/**
 * Renders a PHP native type declaration (without leading `?`) for the given
 * Thrift type. Used for property and parameter type hints; callers add the
 * nullable prefix since all Thrift fields default to null.
 */
string t_php_generator::type_to_native(t_type* type) {
  type = type->get_true_type();

  if (type->is_base_type()) {
    switch (((t_base_type*)type)->get_base()) {
    case t_base_type::TYPE_STRING:
    case t_base_type::TYPE_UUID:
      return "string";
    case t_base_type::TYPE_BOOL:
      return "bool";
    case t_base_type::TYPE_I8:
    case t_base_type::TYPE_I16:
    case t_base_type::TYPE_I32:
    case t_base_type::TYPE_I64:
      return "int";
    case t_base_type::TYPE_DOUBLE:
      return "float";
    default:
      throw "compiler error: unhandled base type in type_to_native";
    }
  } else if (type->is_enum()) {
    return "int";
  } else if (type->is_struct() || type->is_xception()) {
    // Same-namespace references resolve via the file-level `namespace …;`
    // declaration, so emit the short class name and let PHP resolve it.
    // Cross-namespace references fall back to a fully-qualified name.
    // php_namespace() already includes the leading backslash.
    if (type->get_program() == get_program()) {
      return type->get_name();
    }
    return php_namespace(type->get_program()) + type->get_name();
  } else if (type->is_container()) {
    return "array";
  }

  throw "INVALID TYPE IN type_to_native: " + type->get_name();
}

std::string t_php_generator::display_name() const {
  return "PHP";
}


THRIFT_REGISTER_GENERATOR(
    php,
    "PHP",
    "    inlined:         Generate PHP inlined files\n"
    "    server:          Generate PHP server stubs\n"
    "    oop:             Generate PHP with object oriented subclasses\n"
    "    classmap:        Generate old-style PHP files (use classmap autoloading)\n"
    "    rest:            Generate PHP REST processors\n"
    "    nsglobal=NAME:   Set global namespace\n"
    "    validate:        Generate PHP validator methods\n"
    "    json:            Generate JsonSerializable classes (requires PHP >= 5.4)\n"
    "    getters_setters: Generate Getters and Setters for struct variables\n")
