예제 #1
0
 /**
  * Replace transformer in form builder, keep sorting of transformers
  *
  * @param FormBuilderInterface     $builder
  * @param DataTransformerInterface $transformerToReplace
  * @param string                   $type               Model or View transformer type to replace in
  * @param callable                 $comparisonCallback Callable function that will be
  *                                                     used for old transformer detection
  */
 public static function replaceTransformer(FormBuilderInterface $builder, DataTransformerInterface $transformerToReplace, $type = 'model', callable $comparisonCallback = null)
 {
     $transformers = 'model' === $type ? $builder->getModelTransformers() : $builder->getViewTransformers();
     $newTransformers = [];
     $hasCallback = null !== $comparisonCallback;
     $class = get_class($transformerToReplace);
     foreach ($transformers as $key => $transformer) {
         if ($hasCallback && call_user_func($comparisonCallback, $transformer, $key) || !$hasCallback && is_a($transformer, $class)) {
             $newTransformers[] = $transformerToReplace;
         } else {
             $newTransformers[] = $transformer;
         }
     }
     if (!in_array($transformerToReplace, $newTransformers, true)) {
         $newTransformers[] = $transformerToReplace;
     }
     if ('model' === $type) {
         $builder->resetModelTransformers();
         array_walk($newTransformers, [$builder, 'addModelTransformer']);
     } else {
         $builder->resetViewTransformers();
         array_walk($newTransformers, [$builder, 'addViewTransformer']);
     }
 }