如何使用browserkit客户端进行multypart /数据请求?

时间:2018-08-28 13:51:33

标签: symfony

$data = [
            'name' => 'Merry Christamas',
            'description' => 'Merry Christamas',
            'starts_at' => '2018-9-15 12:45:56',
            'ends_at' => '2050-9-15 12:45:56',
            'priority' => -1,
            'coupon_based' => false,
            'action' => [
                'type' => 'order_fixed_discount',
                'configuration' => [
                        'amount' => 100
                ]
            ],
            'rules' => [
                [
                    'type'=> 'item_total',
                    'configuration' => [
                        'amount' => 2500,
                        'base_amount' => 100,
                    ]
                ]
            ]
        ];

 $multipartStream = new MultipartStream($this->flatten($data)); //use GuzzleHttp\Psr7\MultipartStream;

我使用以下方法将关联数组转换为MultipartStream的需求。

protected function flatten(array $array, string $prefix = '', string $suffix = ''): array
    {
        $result = [];

        foreach ($array as $key => $value) {
            if (is_array($value)) {
                $result = array_merge($result, $this->flatten($value, $prefix . $key . $suffix . '[', ']'));
            } else {
                if ($value instanceof UploadedFile) {
                    $result[] = [
                        'name' => $prefix . $key . $suffix,
                        'filename' => $value->getClientOriginalName(),
                        'Mime-Type' => $value->getClientMimeType(),
                        'contents' => file_get_contents($value->getPathname()),
                    ];
                } else {
                    $result[] = [
                        'name' => $prefix . $key . $suffix,
                        'contents' => $value,
                    ];
                }
            }
        }

        return $result;
    }

然后通过browserkit客户端发出请求

$this->client->request(
            'POST',
            '/api/admin/promotions',
            [],
            [],
            [
                'CONTENT_TYPE' => 'multipart/form-data; boundary=--'.$multipartStream->getBoundary() ,
                'HTTP_Authorization'=> "blabla"
            ],
            $multipartStream->getContents()
        );

但是request->request->all()为空,用symfony browserkit客户端发出multipart/data请求的正确方法是什么?我进行了很多搜索,但没有找到合适的例子的机会。

0 个答案:

没有答案