etsy-1.0.0-alpha3/src/Form/EtsyTestForm.php

src/Form/EtsyTestForm.php
<?php

namespace Drupal\etsy\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\etsy\EtsyService;
use Symfony\Component\DependencyInjection\ContainerInterface;

class EtsyTestForm extends FormBase {

  /**
   * @var \Drupal\etsy\EtsyService
   */
  protected $etsyService;

  public function __construct(EtsyService $service) {
    $this->etsyService = $service;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('etsy.api')
    );
  }

  /**
   * @inheritDoc
   */
  public function getFormId() {
    return 'etsy_test_form';
  }

  /**
   * @inheritDoc
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['testing_details'] = [
      '#type' => 'fieldset',
      '#tree' => FALSE,
      '#collapsible' => FALSE,
    ];

    $options = [
      'ping' => $this->t('Ping'),
      'me' => $this->t('Me'),
      'shop_info' => $this->t('Shop info'),
      'listings' => $this->t('Shop listings'),
      'listing' => $this->t('Listing'),
      'listing_properties' => $this->t('Listing properties'),
      'listing_transactions' => $this->t('Listing transactions'),
      'receipts' => $this->t('Receipts'),
      'seller_taxonomy' => $this->t('Seller taxonomy'),
      'buyer_taxonomy' => $this->t('Buyer taxonomy'),
      'sections' => $this->t('Shop sections'),
      'error' => $this->t('Simulated error')
    ];

    $form['testing_details']['api_call'] = [
      '#type' => 'select',
      '#title' => $this->t('Api call'),
      '#description' => $this->t('Select the Api call you wish to test.'),
      '#options' => $options,
      '#empty_option' => $this->t('Select one'),
      '#default_value' => '',
      '#required' => TRUE,
      '#attributes' => ['id' => 'api-call-method'],
    ];

    /*
     * We'll use form states to present additional fields based on the api call
     * being made.
     */
    // Listing by ID.
    $form['testing_details']['listing_id'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Listing ID'),
      '#description' => $this->t('Enter the listing ID to load.'),
      '#required' => FALSE,
      '#states' => [
        'visible' => [
          ':input[id="api-call-method"]' => [
            ['value' => 'listing'],
            ['value' => 'listing_properties'],
            ['value' => 'listing_transactions'],
          ]
        ],
      ],
    ];

    // Shop properties
    $form['testing_details']['shop_key'] = [
      '#type' => 'select',
      '#title' => $this->t('Store key'),
      '#options' => $this->storeKeyOptions(),
      '#empty_option' => $this->t('Select a shop property'),
      '#description' => $this->t('<em>OPTIONAL:</em> Select a specific shop property that you wish to view. If the shop property you select is empty or does not exist, the entire shop object is returned.'),
      '#states' => [
        'visible' => [
          ':input[id="api-call-method"]' => ['value' => 'shop_info'],
        ],
      ],
    ];

    // Taxonomy by ID.
    $form['testing_details']['taxonomy_id'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Taxonomy ID'),
      '#description' => $this->t('Enter the taxonomy ID to load. If empty, all taxonomies will be returned.'),
      '#required' => FALSE,
      '#states' => [
        'visible' => [
          ':input[id="api-call-method"]' => [
            ['value' => 'seller_taxonomy'],
            ['value' => 'buyer_taxonomy'],
          ]
        ],
      ],
    ];

    // Taxonomy by ID.
    $form['testing_details']['receipt_id'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Receipt ID'),
      '#description' => $this->t('Enter the receipt ID to load. If empty, all shop receipts will be returned.'),
      '#required' => FALSE,
      '#states' => [
        'visible' => [
          ':input[id="api-call-method"]' => [
            ['value' => 'receipts'],
          ]
        ],
      ],
    ];

    $form['testing_details']['actions'] = [
      '#type' => 'actions',
      '#tree' => FALSE,
    ];

    $form['testing_details']['actions']['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
      '#ajax' => [
        "callback" => "::ajaxSubmit",
        "method" => "replaceWith",
        "wrapper" => "api-response",
        "progress" => FALSE,
        "disable-refocus" => TRUE,
      ],
    ];

    $form['api_details'] = [
      '#type' => 'fieldset',
      '#tree' => FALSE,
      '#collapsible' => FALSE,
      '#attributes' => [
        'class' => ['code'],
      ],
    ];

    $form['api_details']['api_response'] = [
      '#type' => 'item',
      '#markup' => $this->t('Select an API call from the left.'),
      '#prefix' => '<div id="api-response">',
      '#suffix' => '</div>',
    ];

    $form['#attached']['library'] = [
      'etsy/etsy_test_form',
    ];

    return $form;

  }

  /**
   * @inheritDoc
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {

  }

  /**
   * @throws \Exception
   */
  public function ajaxSubmit($form, FormStateInterface $form_state) {
    $result = FALSE;

    switch ($form_state->getValue('api_call')) {
      case 'ping':
        $result = $this->etsyService->ping();
        break;
      case 'me':
        $result = $this->etsyService->getMe();
        break;
      case 'listings':
        $result = $this->etsyService->getListingsByShop(25, 0, [
          EtsyService::INCLUDES_IMAGES,
          EtsyService::INCLUDE_VIDEOS,
        ]);
        break;
      case 'listing':
        $result = $this->etsyService->getListingById(intval($form_state->getValue('listing_id')), [
          EtsyService::INCLUDES_IMAGES,
          EtsyService::INCLUDE_VIDEOS,
        ]);
        break;
      case 'listing_properties':
        $result = $this->etsyService->getListingProperties($form_state->getValue('listing_id'));
        break;
      case 'listing_transactions':
        $result = $this->etsyService->getListingTransactions($form_state->getValue('listing_id'));
        break;
      case 'seller_taxonomy':
        $taxonomy_id = intval($form_state->getValue('taxonomy_id'));
        $result = $this->etsyService->getTaxonomy('seller', $taxonomy_id);
        break;
      case 'buyer_taxonomy':
        $taxonomy_id = intval($form_state->getValue('taxonomy_id'));
        $result = $this->etsyService->getTaxonomy('buyer', $taxonomy_id);
        break;
      case 'receipts':
        $params = ['limit' => 10];
        $receipt_id = intval($form_state->getValue('receipt_id'));
        $result = $this->etsyService->getShopReceipts($receipt_id, $params);
        break;
      case 'shop_info':
        $key = trim($form_state->getValue('shop_key'));
        $result = $this->etsyService->shopInfo($key ?? NULL);
        break;
      case 'sections':
        $result = $this->etsyService->getShopSections();
        break;
      case 'error':
        $result = $this->etsyService->getListingById(0);
        break;
      default:
        // The field is a select box so we should never get here.
    }
    if (!isset($result->error)) {
      if (is_null($result)) {
        $result = 'NULL';
      }
      elseif (is_bool($result)) {
        $result = ($result === FALSE ? 'FALSE' : 'TRUE');
      }
      $form['api_details']['api_response']['#markup'] = '<pre>' . print_r($result, TRUE) . '</pre>';
    }
    else {
      $form['api_details']['api_response']['#markup'] = $result->error;
    }
    return $form['api_details']['api_response'];
  }

  private function storeKeyOptions() {
    $obj = <<<OBJ
{
"shop_id": 1,
"user_id": 1,
"shop_name": "string",
"create_date": 0,
"created_timestamp": 0,
"title": "string",
"announcement": "string",
"currency_code": "string",
"is_vacation": true,
"vacation_message": "string",
"sale_message": "string",
"digital_sale_message": "string",
"update_date": 0,
"updated_timestamp": 0,
"listing_active_count": 0,
"digital_listing_count": 0,
"login_name": "string",
"accepts_custom_requests": true,
"policy_welcome": "string",
"policy_payment": "string",
"policy_shipping": "string",
"policy_refunds": "string",
"policy_additional": "string",
"policy_seller_info": "string",
"policy_update_date": 0,
"policy_has_private_receipt_info": true,
"has_unstructured_policies": true,
"policy_privacy": "string",
"vacation_autoreply": "string",
"url": "string",
"image_url_760x100": "string",
"num_favorers": 0,
"languages": [
"string"
],
"icon_url_fullxfull": "string",
"is_using_structured_policies": true,
"has_onboarded_structured_policies": true,
"include_dispute_form_link": true,
"is_direct_checkout_onboarded": true,
"is_etsy_payments_onboarded": true,
"is_calculated_eligible": true,
"is_opted_in_to_buyer_promise": true,
"is_shop_us_based": true,
"transaction_sold_count": 0,
"shipping_from_country_iso": "string",
"shop_location_country_iso": "string",
"review_count": 0,
"review_average": 0
}
OBJ;
    $obj = json_decode($obj);
    $options = [];
    foreach ($obj as $key => $value) {
      $options[$key] = ucfirst(str_replace('_', ' ', $key));
    }
    return $options;
  }

}

Главная | Обратная связь

drupal hosting | друпал хостинг | it patrol .inc