Factory.php 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\Message;
  7. use Magento\Framework\ObjectManagerInterface;
  8. /**
  9. * Message model factory
  10. */
  11. class Factory
  12. {
  13. /**
  14. * Allowed message types
  15. *
  16. * @var string[]
  17. */
  18. protected $types = [
  19. MessageInterface::TYPE_ERROR,
  20. MessageInterface::TYPE_WARNING,
  21. MessageInterface::TYPE_NOTICE,
  22. MessageInterface::TYPE_SUCCESS,
  23. ];
  24. /**
  25. * Object Manager instance
  26. *
  27. * @var ObjectManagerInterface
  28. */
  29. protected $objectManager;
  30. /**
  31. * Factory constructor
  32. *
  33. * @param ObjectManagerInterface $objectManager
  34. */
  35. public function __construct(ObjectManagerInterface $objectManager)
  36. {
  37. $this->objectManager = $objectManager;
  38. }
  39. /**
  40. * Create a message instance of a given type with given text.
  41. *
  42. * @param string|null $type The message type to create, must correspond to a message type under the
  43. * namespace Magento\Framework\Message\
  44. * @param string $text The text to inject into the message
  45. * @throws \InvalidArgumentException Exception gets thrown if type does not correspond to a valid Magento message
  46. * @return MessageInterface
  47. */
  48. public function create($type, $text = null)
  49. {
  50. if (!in_array($type, $this->types)) {
  51. throw new \InvalidArgumentException('Wrong message type');
  52. }
  53. $className = 'Magento\\Framework\\Message\\' . ucfirst($type);
  54. $message = $this->objectManager->create($className, $text === null ? [] : ['text' => $text]);
  55. if (!$message instanceof MessageInterface) {
  56. throw new \InvalidArgumentException(
  57. $className . ' doesn\'t implement \Magento\Framework\Message\MessageInterface'
  58. );
  59. }
  60. return $message;
  61. }
  62. }