SubSelect.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\DB;
  7. use Magento\Framework\App\ResourceConnection;
  8. use Magento\Framework\DB\Adapter\AdapterInterface;
  9. /**
  10. * Class Concat
  11. */
  12. class SubSelect extends \Zend_Db_Expr
  13. {
  14. /**
  15. * @var string
  16. */
  17. protected $table;
  18. /**
  19. * @var string[]
  20. */
  21. protected $columns;
  22. /**
  23. * @var string
  24. */
  25. protected $originColumn;
  26. /**
  27. * @var string
  28. */
  29. protected $targetColumn;
  30. /**
  31. * @var \Magento\Framework\App\ResourceConnection
  32. */
  33. protected $resource;
  34. /**
  35. * @var string
  36. */
  37. protected $connectionName;
  38. /**
  39. * @var AdapterInterface
  40. */
  41. protected $connection;
  42. /**
  43. * @param ResourceConnection $resource
  44. * @param string $connectionName
  45. * @param string $table
  46. * @param string[] $columns
  47. * @param string $originColumn
  48. * @param string $targetColumn
  49. */
  50. public function __construct(
  51. ResourceConnection $resource,
  52. $table,
  53. array $columns,
  54. $originColumn,
  55. $targetColumn,
  56. $connectionName = ResourceConnection::DEFAULT_CONNECTION
  57. ) {
  58. $this->resource = $resource;
  59. $this->connectionName = $connectionName;
  60. $this->table = $table;
  61. $this->columns = $columns;
  62. $this->originColumn = $originColumn;
  63. $this->targetColumn = $targetColumn;
  64. }
  65. /**
  66. * @return string
  67. */
  68. public function __toString()
  69. {
  70. $select = $this->getConnection()->select()->from(
  71. $this->resource->getTableName($this->table),
  72. array_values($this->columns)
  73. )->where(
  74. sprintf(
  75. '%s = %s',
  76. $this->getConnection()->quoteIdentifier($this->originColumn),
  77. $this->getConnection()->quoteIdentifier($this->targetColumn)
  78. )
  79. )->limit(1);
  80. return sprintf('(%s)', $select);
  81. }
  82. /**
  83. * Returns connection
  84. *
  85. * @return AdapterInterface
  86. */
  87. protected function getConnection()
  88. {
  89. if (!$this->connection) {
  90. $this->connection = $this->resource->getConnection($this->connectionName);
  91. }
  92. return $this->connection;
  93. }
  94. }