ObjectToPopulateTrait.php 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Serializer\Normalizer;
  11. trait ObjectToPopulateTrait
  12. {
  13. /**
  14. * Extract the `object_to_populate` field from the context if it exists
  15. * and is an instance of the provided $class.
  16. *
  17. * @param string $class The class the object should be
  18. * @param string|null $key They in which to look for the object to populate.
  19. * Keeps backwards compatibility with `AbstractNormalizer`.
  20. *
  21. * @return object|null an object if things check out, null otherwise
  22. */
  23. protected function extractObjectToPopulate(string $class, array $context, string $key = null): ?object
  24. {
  25. $key = $key ?? AbstractNormalizer::OBJECT_TO_POPULATE;
  26. if (isset($context[$key]) && \is_object($context[$key]) && $context[$key] instanceof $class) {
  27. return $context[$key];
  28. }
  29. return null;
  30. }
  31. }