No Description

IOFactory.php 2.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. /**
  3. * PHPWord
  4. *
  5. * @link https://github.com/PHPOffice/PHPWord
  6. * @copyright 2014 PHPWord
  7. * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL
  8. */
  9. namespace PhpOffice\PhpWord;
  10. use PhpOffice\PhpWord\Exception\Exception;
  11. use PhpOffice\PhpWord\Reader\ReaderInterface;
  12. use PhpOffice\PhpWord\Writer\WriterInterface;
  13. abstract class IOFactory
  14. {
  15. /**
  16. * Create new writer
  17. *
  18. * @param PhpWord $phpWord
  19. * @param string $name
  20. * @return WriterInterface
  21. * @throws \PhpOffice\PhpWord\Exception\Exception
  22. */
  23. public static function createWriter(PhpWord $phpWord, $name = 'Word2007')
  24. {
  25. if ($name !== 'WriterInterface' && !in_array($name, array('ODText', 'RTF', 'Word2007', 'HTML', 'PDF'), true)) {
  26. throw new Exception("\"{$name}\" is not a valid writer.");
  27. }
  28. $fqName = "PhpOffice\\PhpWord\\Writer\\{$name}";
  29. return new $fqName($phpWord);
  30. }
  31. /**
  32. * Create new reader
  33. *
  34. * @param string $name
  35. * @return ReaderInterface
  36. * @throws Exception
  37. */
  38. public static function createReader($name = 'Word2007')
  39. {
  40. return self::createObject('Reader', $name);
  41. }
  42. /**
  43. * Create new object
  44. *
  45. * @param string $type
  46. * @param string $name
  47. * @param \PhpOffice\PhpWord\PhpWord $phpWord
  48. * @return \PhpOffice\PhpWord\Writer\WriterInterface|\PhpOffice\PhpWord\Reader\ReaderInterface
  49. * @throws \PhpOffice\PhpWord\Exception\Exception
  50. */
  51. private static function createObject($type, $name, $phpWord = null)
  52. {
  53. $class = "PhpOffice\\PhpWord\\{$type}\\{$name}";
  54. if (class_exists($class) && self::isConcreteClass($class)) {
  55. return new $class($phpWord);
  56. } else {
  57. throw new Exception("\"{$name}\" is not a valid {$type}.");
  58. }
  59. }
  60. /**
  61. * Loads PhpWord from file
  62. *
  63. * @param string $filename The name of the file
  64. * @param string $readerName
  65. * @return \PhpOffice\PhpWord\PhpWord $phpWord
  66. */
  67. public static function load($filename, $readerName = 'Word2007')
  68. {
  69. /** @var \PhpOffice\PhpWord\Reader\ReaderInterface $reader */
  70. $reader = self::createReader($readerName);
  71. return $reader->load($filename);
  72. }
  73. /**
  74. * Check if it's a concrete class (not abstract nor interface)
  75. *
  76. * @param string $class
  77. * @return bool
  78. */
  79. private static function isConcreteClass($class)
  80. {
  81. $reflection = new \ReflectionClass($class);
  82. return !$reflection->isAbstract() && !$reflection->isInterface();
  83. }
  84. }