php_Field.php

<?php

namespace FindStr;

class Field {

  public int $id;
  public string $name;
  public string $slug;
  public string $type;
  public string $source;
  public string $source_type;
  public string $source_name;
  public array $options;

  public function __construct( $args ) {
    $this->id          = $args['id'];
    $this->name        = $args['fieldName'];
    $this->slug        = $args['fieldSlug'];
    $this->options     = $this->get_options( $args );
    $this->type        = $this->get_type( $args );
    $this->source      = $this->get_source( $args );
    $this->source_name = $this->get_source_name( $args );
    $this->source_type = $this->get_source_type( $args );
  }

  private function get_source( $args ) {

    $source = false;

    if ( isset( $args['options']['sourceName'] ) ) {
      $source = $args['options']['sourceName'];
    }

    /**
     * Filter the field source
     *
     * @hook findstr_fields_source
     *
     * @param {string} $source original source
     * @param {string} $type field type
     * @param {array} $options field options
     * @param {array} $args field arguments
     *
     * @return {string} $source
     */
    return apply_filters( 'findstr_fields_source', $source, $this->type, $this->options, $args );
  }

  private function get_type( $args ) {
    if ( $args['fieldType'] ) {
      return $args['fieldType'];
    }
    return false;
  }

  private function get_source_type( $args ): string {

    if ( isset( $args['options']['sourceName'] ) ) {

      $backslash_pos = strpos( $args['options']['sourceName'], '/' );
      if ( false === $backslash_pos ) {
        return 'post';
      }

      $field_exploded_args = explode( '/', $args['options']['sourceName'] );
      return current( $field_exploded_args );
    }

    return '';
  }

  private function get_source_name( $args ): string {

    if ( isset( $args['options']['sourceName'] ) ) {
      $field_exploded_args = explode( '/', $args['options']['sourceName'] );
      return end( $field_exploded_args );
    }

    return '';
  }

  private function get_options( $args ) {
    if ( empty( $args['options'] ) ) {
      return array();
    }
    //todo: add filter ?
    return $args['options'];
  }

}