2015-09-03 27 views
1

我有以下代码;对于Symfony验证器组件是否有可能强制验证失败的类实现EventSubscriberInterface

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

我的方法GetResolvedUrlListener确实卷曲请求以发现正确的协议和最终地址(以下重定向),以确定正确的URL。

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

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

回答

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 
     } 
    } 
}