Changing parameter values of Guzzle commands at runtime, through plugins?

自古美人都是妖i 提交于 2019-12-08 07:33:01

问题


This is (part of) the definition of BaseOperation, with one mandatory parameter (foo):

'BaseOperation' => array(
    'class' => 'My\Command\MyCustomCommand',
    'httpMethod' => 'POST',
    'parameters' => array(
        'foo' => array(
            'required' => true,
            'location' => 'query'
        )
    )
)

Inside ChangeMethodPlugin plugin I need to modify the value of foo at runtime:

class ChangeMethodPlugin implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array('command.before_send' => 'onBeforeCommandSend');
    }

    public function onBeforeCommandSend(Event $event)
    {
        /** @var \Guzzle\Service\Command\CommandInterface $command */
        $command = $event['command'];

        // Only if test configuration is true
        if ($command->getClient()->getConfig(ClientOptions::TEST)) {
            // Only if command is MyCustomCommand
            if ($command instanceof MyCustomCommand) {
                // Here I need to change the value of 'foo' parameter
            }
        }
    }
}

I can't find any method inside Parameter or AbstractCommand.

EDIT: param name changed to "foo" from "method" to avoid confusion with HTTP verbs.


回答1:


You can use the setHttpMethod() method of the Operation owned by the command, but you'll need to use the command.before_prepare event instead.

<?php

class ChangeMethodPlugin implements EventSubscriberInterface
{
    public static function getSubscribedEvents()
    {
        return array('command.before_prepare' => 'onBeforeCommandPrepare');
    }

    public function onBeforeCommandPrepare(Event $event)
    {
        /** @var \Guzzle\Service\Command\CommandInterface $command */
        $command = $event['command'];

        // Only if test configuration is true
        if ($command->getClient()->getConfig(ClientOptions::TEST)) {
            // Only if command is MyCustomCommand
            if ($command instanceof MyCustomCommand) {
                // Here I need to change the value of 'method' parameter
                $command->getOperation()->setHttpMethod('METHOD_NAME');
            }
        }
    }
}



回答2:


You could do something like the following:

$command->getRequest()->getQuery()->set('foo', 'bar');

So long as you have injected the new 'foo' value into the plugin, you should be able to accomplish what you are looking to do.



来源:https://stackoverflow.com/questions/17705907/changing-parameter-values-of-guzzle-commands-at-runtime-through-plugins

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!