How do I limit a normalizer to a given class or interface? I'm creating a custom normalizer for node entities.

I want to restrict the normalizer to normalize Node entities only. It seems like there are two ways this can be done:


protected $supportedInterfaceOrClass = NodeInterface::class;
public function supportsNormalization($data, $format = NULL) {
  return (bool) $data instanceof NodeInterface;
}



Is there a difference between the two? Do I need both, or only one of them?

It seems like I don't need the $supportedInterfaceOrClass, but what is it used for? Can I just remove it and only use supportsNormalization()?

UPDATE: My class extends the NormalizerBase class.
You didn't explicitly state that your class is extending NormalizerBase, but I assume that's the case. My reply is based on that assumption.

If you look in the code for NormalizerBase, there are two spots where $supportedInterfaceOrClass is accessed, in supportsNormalization() and supportsDenormalization(). If you override supportsNormalization() as option #2 from the original post suggests, your normalizer will be restricted to nodes. However, it overrides the base method, bypassing a check to see if the given normalization format is even supported, which is not good. If someone were to try to normalize an unsupported format, the overridden method would incorrectly return TRUE. Therefore, it is better to set supportedInterfaceOrClass according option #1 from the original post, as that will also cover the denormalization option, as well as allow the base API to do its work.

Verdict: Do NOT use method #2. Do use method #1. I would implement __construct() and set the node class upon instantiation:

public function __construct() {
  this-&gt;supportedInterfaceOrClass = NodeInterface::class;
}