【问题标题】:PhpStorm hint ArrayShape?PhpStorm 提示 ArrayShape?
【发布时间】:2021-12-22 16:07:00
【问题描述】:

我正在定义一个类如下,使用来自https://blog.jetbrains.com/phpstorm/2020/10/phpstorm-2020-3-eap-4/#arrayshape 的建议将数组形状定义为常量,以便可以在项目中使用它:

<?php

namespace my\namespace\Api;

use JetBrains\PhpStorm\ArrayShape;

class CheckoutSessionLineItemMetadata implements MetadataInterface {

  /**
   * The ArrayShape of toArray().
   */
  public const ARRAY_SHAPE = [
    'order_item_id' => "string",
    'order_id' => "string",
    'product_variation_id' => "string",
  ];

  /**
   * Constructs a new object.
   *
   * @param string $order_item_id
   * @param string $order_id
   * @param string $product_variation_id
   */
  public function __construct(
    private string $order_item_id,
    private string $order_id,
    private string $product_variation_id) {
  }

  /**
   * {@inheritDoc}
   */
  #[ArrayShape(self::ARRAY_SHAPE)] public function toArray(): array {
    return [
      'order_item_id' => $this->order_item_id,
      'order_id' => $this->order_id,
      'product_variation_id' => $this->product_variation_id,
    ];
  }

}

这用于帮助我在创建事务时将一些数据传递给 Stripe API。

我在其他地方循环访问由单独的 Stripe API 响应提供的数据,该响应包括具有该结构的元数据元素。我想暗示数据采用这种数组形状,但我不确定如何(或是否)可以做到。

foreach ($data->display_items as $line_item) {
  /** @var $metadata CheckoutSessionLineItemMetadata::ARRAY_SHAPE */
  $metadata = $line_item->metadata;
  // Ideally I'd get hinting that the associated keys are on this element.
}

这可能吗?我应该注意我正在使用这个插件:https://github.com/klesun/deep-assoc-completion/issues/63,所以我可以用它来复制结构,但是因为它已经在其他地方定义了,所以很遗憾。

【问题讨论】:

    标签: php phpstorm php-8


    【解决方案1】:

    好的,在使用 deep-assoc-completion 链接发布编辑后,我想出了如何做到这一点。这就是我想要的。

       foreach ($data->display_items as $line_item) {
          /** @var $metadata = CheckoutSessionLineItemMetadata::ARRAY_SHAPE */
          $metadata = $line_item->metadata;
        }
    

    【讨论】:

      猜你喜欢
      • 2021-12-26
      • 2021-09-21
      • 2013-07-14
      • 1970-01-01
      • 2019-03-08
      • 2012-09-22
      • 1970-01-01
      • 2021-01-02
      • 2015-06-08
      相关资源
      最近更新 更多