1

我有以下代码;

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
    ->add(
        $builder->create(
            'href', 
            'url', 
            $this->getOptionsForUrlWidget('Website URL')
            )->addEventSubscriber(new GetResolvedUrlListener())
        )
...

我的方法GetResolvedUrlListener执行 curl 请求以发现正确的协议和最终地址(在重定向之后)以确定正确的 url。

如果 curl 请求没有收到成功的 HTTP 响应,我希望它导致验证失败。因此,如果提供的 url 不可访问,则不应保存。

这可以在实现 EventSubscriberInterface 的类中完成吗?我是否应该添加一个新的约束并验证提供的 url 两次?

4

1 回答 1

0

您应该添加一个约束,但不一定要验证它两次,您可以创建一个中央服务来解析这些 url,但也可以将它们保留在两个$validUrls$invalidUrls属性中,然后您可以在两个事件侦听器中使用此服务在您的验证约束中,服务看起来像这样:

class UrlValidator{

    protected $validUrls = array();
    protected $invalidUrls = array();

    public function resolve($url){
        // we have validated this url before, and it wasn't valid
        if(isset($this->invalidUrls[$url])
            return false;
        // we have validated this url before, so we can return true or the resolved value
        if(isset($this->validUrls[$url])
            return $this->validUrls[$url];

        else{
        // do the curl request, and set $this->validUrls[$urls] or $this->invalidUrls[$url] accordingly
        }
    }
}
于 2015-09-04T05:51:58.377 回答