Query.php 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  11. * @link https://cakephp.org CakePHP(tm) Project
  12. * @since 3.0.0
  13. * @license https://opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\ORM;
  16. use ArrayObject;
  17. use Cake\Database\ExpressionInterface;
  18. use Cake\Database\Query as DatabaseQuery;
  19. use Cake\Database\TypedResultInterface;
  20. use Cake\Database\TypeMap;
  21. use Cake\Database\ValueBinder;
  22. use Cake\Datasource\QueryInterface;
  23. use Cake\Datasource\QueryTrait;
  24. use JsonSerializable;
  25. use RuntimeException;
  26. /**
  27. * Extends the base Query class to provide new methods related to association
  28. * loading, automatic fields selection, automatic type casting and to wrap results
  29. * into a specific iterator that will be responsible for hydrating results if
  30. * required.
  31. *
  32. * @see \Cake\Collection\CollectionInterface For a full description of the collection methods supported by this class
  33. * @method \Cake\Collection\CollectionInterface each(callable $c) Passes each of the query results to the callable
  34. * @method \Cake\Collection\CollectionInterface filter(callable $c = null) Keeps the results using passing the callable test
  35. * @method \Cake\Collection\CollectionInterface reject(callable $c) Removes the results passing the callable test
  36. * @method bool every(callable $c) Returns true if all the results pass the callable test
  37. * @method bool some(callable $c) Returns true if at least one of the results pass the callable test
  38. * @method \Cake\Collection\CollectionInterface map(callable $c) Modifies each of the results using the callable
  39. * @method mixed reduce(callable $c, $zero = null) Folds all the results into a single value using the callable.
  40. * @method \Cake\Collection\CollectionInterface extract($field) Extracts a single column from each row
  41. * @method mixed max($field, $type = SORT_NUMERIC) Returns the maximum value for a single column in all the results.
  42. * @method mixed min($field, $type = SORT_NUMERIC) Returns the minimum value for a single column in all the results.
  43. * @method \Cake\Collection\CollectionInterface groupBy(string|callable $field) In-memory group all results by the value of a column.
  44. * @method \Cake\Collection\CollectionInterface indexBy(string|callable $field) Returns the results indexed by the value of a column.
  45. * @method int countBy(string|callable $field) Returns the number of unique values for a column
  46. * @method float sumOf(string|callable $field) Returns the sum of all values for a single column
  47. * @method \Cake\Collection\CollectionInterface shuffle() In-memory randomize the order the results are returned
  48. * @method \Cake\Collection\CollectionInterface sample($size = 10) In-memory shuffle the results and return a subset of them.
  49. * @method \Cake\Collection\CollectionInterface take($size = 1, $from = 0) In-memory limit and offset for the query results.
  50. * @method \Cake\Collection\CollectionInterface skip(int $howMany) Skips some rows from the start of the query result.
  51. * @method mixed last() Return the last row of the query result
  52. * @method \Cake\Collection\CollectionInterface append(array|\Traversable $items) Appends more rows to the result of the query.
  53. * @method \Cake\Collection\CollectionInterface combine($k, $v, $g = null) Returns the values of the column $v index by column $k,
  54. * and grouped by $g.
  55. * @method \Cake\Collection\CollectionInterface nest($k, $p, $n = 'children') Creates a tree structure by nesting the values of column $p into that
  56. * with the same value for $k using $n as the nesting key.
  57. * @method array toArray() Returns a key-value array with the results of this query.
  58. * @method array toList() Returns a numerically indexed array with the results of this query.
  59. * @method \Cake\Collection\CollectionInterface stopWhen(callable $c) Returns each row until the callable returns true.
  60. * @method \Cake\Collection\CollectionInterface zip(array|\Traversable $c) Returns the first result of both the query and $c in an array,
  61. * then the second results and so on.
  62. * @method \Cake\Collection\CollectionInterface zipWith($collections, callable $callable) Returns each of the results out of calling $c
  63. * with the first rows of the query and each of the items, then the second rows and so on.
  64. * @method \Cake\Collection\CollectionInterface chunk($size) Groups the results in arrays of $size rows each.
  65. * @method bool isEmpty() Returns true if this query found no results.
  66. * @mixin \Cake\Datasource\QueryTrait
  67. */
  68. class Query extends DatabaseQuery implements JsonSerializable, QueryInterface
  69. {
  70. use QueryTrait {
  71. cache as private _cache;
  72. all as private _all;
  73. _decorateResults as private _applyDecorators;
  74. __call as private _call;
  75. }
  76. /**
  77. * Indicates that the operation should append to the list
  78. *
  79. * @var int
  80. */
  81. const APPEND = 0;
  82. /**
  83. * Indicates that the operation should prepend to the list
  84. *
  85. * @var int
  86. */
  87. const PREPEND = 1;
  88. /**
  89. * Indicates that the operation should overwrite the list
  90. *
  91. * @var bool
  92. */
  93. const OVERWRITE = true;
  94. /**
  95. * Whether the user select any fields before being executed, this is used
  96. * to determined if any fields should be automatically be selected.
  97. *
  98. * @var bool
  99. */
  100. protected $_hasFields;
  101. /**
  102. * Tracks whether or not the original query should include
  103. * fields from the top level table.
  104. *
  105. * @var bool
  106. */
  107. protected $_autoFields;
  108. /**
  109. * Whether to hydrate results into entity objects
  110. *
  111. * @var bool
  112. */
  113. protected $_hydrate = true;
  114. /**
  115. * A callable function that can be used to calculate the total amount of
  116. * records this query will match when not using `limit`
  117. *
  118. * @var callable
  119. */
  120. protected $_counter;
  121. /**
  122. * Instance of a class responsible for storing association containments and
  123. * for eager loading them when this query is executed
  124. *
  125. * @var \Cake\ORM\EagerLoader
  126. */
  127. protected $_eagerLoader;
  128. /**
  129. * True if the beforeFind event has already been triggered for this query
  130. *
  131. * @var bool
  132. */
  133. protected $_beforeFindFired = false;
  134. /**
  135. * The COUNT(*) for the query.
  136. *
  137. * When set, count query execution will be bypassed.
  138. *
  139. * @var int|null
  140. */
  141. protected $_resultsCount;
  142. /**
  143. * Constructor
  144. *
  145. * @param \Cake\Database\Connection $connection The connection object
  146. * @param \Cake\ORM\Table $table The table this query is starting on
  147. */
  148. public function __construct($connection, $table)
  149. {
  150. parent::__construct($connection);
  151. $this->repository($table);
  152. if ($this->_repository) {
  153. $this->addDefaultTypes($this->_repository);
  154. }
  155. }
  156. /**
  157. * Adds new fields to be returned by a `SELECT` statement when this query is
  158. * executed. Fields can be passed as an array of strings, array of expression
  159. * objects, a single expression or a single string.
  160. *
  161. * If an array is passed, keys will be used to alias fields using the value as the
  162. * real field to be aliased. It is possible to alias strings, Expression objects or
  163. * even other Query objects.
  164. *
  165. * If a callable function is passed, the returning array of the function will
  166. * be used as the list of fields.
  167. *
  168. * By default this function will append any passed argument to the list of fields
  169. * to be selected, unless the second argument is set to true.
  170. *
  171. * ### Examples:
  172. *
  173. * ```
  174. * $query->select(['id', 'title']); // Produces SELECT id, title
  175. * $query->select(['author' => 'author_id']); // Appends author: SELECT id, title, author_id as author
  176. * $query->select('id', true); // Resets the list: SELECT id
  177. * $query->select(['total' => $countQuery]); // SELECT id, (SELECT ...) AS total
  178. * $query->select(function ($query) {
  179. * return ['article_id', 'total' => $query->count('*')];
  180. * })
  181. * ```
  182. *
  183. * By default no fields are selected, if you have an instance of `Cake\ORM\Query` and try to append
  184. * fields you should also call `Cake\ORM\Query::enableAutoFields()` to select the default fields
  185. * from the table.
  186. *
  187. * If you pass an instance of a `Cake\ORM\Table` or `Cake\ORM\Association` class,
  188. * all the fields in the schema of the table or the association will be added to
  189. * the select clause.
  190. *
  191. * @param array|\Cake\Database\ExpressionInterface|string|\Cake\ORM\Table|\Cake\ORM\Association $fields fields
  192. * to be added to the list.
  193. * @param bool $overwrite whether to reset fields with passed list or not
  194. * @return $this
  195. */
  196. public function select($fields = [], $overwrite = false)
  197. {
  198. if ($fields instanceof Association) {
  199. $fields = $fields->getTarget();
  200. }
  201. if ($fields instanceof Table) {
  202. $fields = $this->aliasFields($fields->getSchema()->columns(), $fields->getAlias());
  203. }
  204. return parent::select($fields, $overwrite);
  205. }
  206. /**
  207. * All the fields associated with the passed table except the excluded
  208. * fields will be added to the select clause of the query. Passed excluded fields should not be aliased.
  209. * After the first call to this method, a second call cannot be used to remove fields that have already
  210. * been added to the query by the first. If you need to change the list after the first call,
  211. * pass overwrite boolean true which will reset the select clause removing all previous additions.
  212. *
  213. *
  214. *
  215. * @param \Cake\ORM\Table|\Cake\ORM\Association $table The table to use to get an array of columns
  216. * @param array $excludedFields The un-aliased column names you do not want selected from $table
  217. * @param bool $overwrite Whether to reset/remove previous selected fields
  218. * @return Query
  219. * @throws \InvalidArgumentException If Association|Table is not passed in first argument
  220. */
  221. public function selectAllExcept($table, array $excludedFields, $overwrite = false)
  222. {
  223. if ($table instanceof Association) {
  224. $table = $table->getTarget();
  225. }
  226. if (!($table instanceof Table)) {
  227. throw new \InvalidArgumentException('You must provide either an Association or a Table object');
  228. }
  229. $fields = array_diff($table->getSchema()->columns(), $excludedFields);
  230. $aliasedFields = $this->aliasFields($fields);
  231. return $this->select($aliasedFields, $overwrite);
  232. }
  233. /**
  234. * Hints this object to associate the correct types when casting conditions
  235. * for the database. This is done by extracting the field types from the schema
  236. * associated to the passed table object. This prevents the user from repeating
  237. * themselves when specifying conditions.
  238. *
  239. * This method returns the same query object for chaining.
  240. *
  241. * @param \Cake\ORM\Table $table The table to pull types from
  242. * @return $this
  243. */
  244. public function addDefaultTypes(Table $table)
  245. {
  246. $alias = $table->getAlias();
  247. $map = $table->getSchema()->typeMap();
  248. $fields = [];
  249. foreach ($map as $f => $type) {
  250. $fields[$f] = $fields[$alias . '.' . $f] = $fields[$alias . '__' . $f] = $type;
  251. }
  252. $this->getTypeMap()->addDefaults($fields);
  253. return $this;
  254. }
  255. /**
  256. * Sets the instance of the eager loader class to use for loading associations
  257. * and storing containments.
  258. *
  259. * @param \Cake\ORM\EagerLoader $instance The eager loader to use.
  260. * @return $this
  261. */
  262. public function setEagerLoader(EagerLoader $instance)
  263. {
  264. $this->_eagerLoader = $instance;
  265. return $this;
  266. }
  267. /**
  268. * Returns the currently configured instance.
  269. *
  270. * @return \Cake\ORM\EagerLoader
  271. */
  272. public function getEagerLoader()
  273. {
  274. if ($this->_eagerLoader === null) {
  275. $this->_eagerLoader = new EagerLoader();
  276. }
  277. return $this->_eagerLoader;
  278. }
  279. /**
  280. * Sets the instance of the eager loader class to use for loading associations
  281. * and storing containments. If called with no arguments, it will return the
  282. * currently configured instance.
  283. *
  284. * @deprecated 3.4.0 Use setEagerLoader()/getEagerLoader() instead.
  285. * @param \Cake\ORM\EagerLoader|null $instance The eager loader to use. Pass null
  286. * to get the current eagerloader.
  287. * @return \Cake\ORM\EagerLoader|$this
  288. */
  289. public function eagerLoader(EagerLoader $instance = null)
  290. {
  291. deprecationWarning(
  292. 'Query::eagerLoader() is deprecated. ' .
  293. 'Use setEagerLoader()/getEagerLoader() instead.'
  294. );
  295. if ($instance !== null) {
  296. return $this->setEagerLoader($instance);
  297. }
  298. return $this->getEagerLoader();
  299. }
  300. /**
  301. * Sets the list of associations that should be eagerly loaded along with this
  302. * query. The list of associated tables passed must have been previously set as
  303. * associations using the Table API.
  304. *
  305. * ### Example:
  306. *
  307. * ```
  308. * // Bring articles' author information
  309. * $query->contain('Author');
  310. *
  311. * // Also bring the category and tags associated to each article
  312. * $query->contain(['Category', 'Tag']);
  313. * ```
  314. *
  315. * Associations can be arbitrarily nested using dot notation or nested arrays,
  316. * this allows this object to calculate joins or any additional queries that
  317. * must be executed to bring the required associated data.
  318. *
  319. * ### Example:
  320. *
  321. * ```
  322. * // Eager load the product info, and for each product load other 2 associations
  323. * $query->contain(['Product' => ['Manufacturer', 'Distributor']);
  324. *
  325. * // Which is equivalent to calling
  326. * $query->contain(['Products.Manufactures', 'Products.Distributors']);
  327. *
  328. * // For an author query, load his region, state and country
  329. * $query->contain('Regions.States.Countries');
  330. * ```
  331. *
  332. * It is possible to control the conditions and fields selected for each of the
  333. * contained associations:
  334. *
  335. * ### Example:
  336. *
  337. * ```
  338. * $query->contain(['Tags' => function ($q) {
  339. * return $q->where(['Tags.is_popular' => true]);
  340. * }]);
  341. *
  342. * $query->contain(['Products.Manufactures' => function ($q) {
  343. * return $q->select(['name'])->where(['Manufactures.active' => true]);
  344. * }]);
  345. * ```
  346. *
  347. * Each association might define special options when eager loaded, the allowed
  348. * options that can be set per association are:
  349. *
  350. * - `foreignKey`: Used to set a different field to match both tables, if set to false
  351. * no join conditions will be generated automatically. `false` can only be used on
  352. * joinable associations and cannot be used with hasMany or belongsToMany associations.
  353. * - `fields`: An array with the fields that should be fetched from the association.
  354. * - `finder`: The finder to use when loading associated records. Either the name of the
  355. * finder as a string, or an array to define options to pass to the finder.
  356. * - `queryBuilder`: Equivalent to passing a callable instead of an options array.
  357. *
  358. * ### Example:
  359. *
  360. * ```
  361. * // Set options for the hasMany articles that will be eagerly loaded for an author
  362. * $query->contain([
  363. * 'Articles' => [
  364. * 'fields' => ['title', 'author_id']
  365. * ]
  366. * ]);
  367. * ```
  368. *
  369. * Finders can be configured to use options.
  370. *
  371. * ```
  372. * // Retrieve translations for the articles, but only those for the `en` and `es` locales
  373. * $query->contain([
  374. * 'Articles' => [
  375. * 'finder' => [
  376. * 'translations' => [
  377. * 'locales' => ['en', 'es']
  378. * ]
  379. * ]
  380. * ]
  381. * ]);
  382. * ```
  383. *
  384. * When containing associations, it is important to include foreign key columns.
  385. * Failing to do so will trigger exceptions.
  386. *
  387. * ```
  388. * // Use a query builder to add conditions to the containment
  389. * $query->contain('Authors', function ($q) {
  390. * return $q->where(...); // add conditions
  391. * });
  392. * // Use special join conditions for multiple containments in the same method call
  393. * $query->contain([
  394. * 'Authors' => [
  395. * 'foreignKey' => false,
  396. * 'queryBuilder' => function ($q) {
  397. * return $q->where(...); // Add full filtering conditions
  398. * }
  399. * ],
  400. * 'Tags' => function ($q) {
  401. * return $q->where(...); // add conditions
  402. * }
  403. * ]);
  404. * ```
  405. *
  406. * If called with no arguments, this function will return an array with
  407. * with the list of previously configured associations to be contained in the
  408. * result. This getter part is deprecated as of 3.6.0. Use getContain() instead.
  409. *
  410. * If called with an empty first argument and `$override` is set to true, the
  411. * previous list will be emptied.
  412. *
  413. * @param array|string|null $associations List of table aliases to be queried.
  414. * @param callable|bool $override The query builder for the association, or
  415. * if associations is an array, a bool on whether to override previous list
  416. * with the one passed
  417. * defaults to merging previous list with the new one.
  418. * @return array|$this
  419. */
  420. public function contain($associations = null, $override = false)
  421. {
  422. $loader = $this->getEagerLoader();
  423. if ($override === true) {
  424. $this->clearContain();
  425. }
  426. if ($associations === null) {
  427. deprecationWarning(
  428. 'Using Query::contain() as getter is deprecated. ' .
  429. 'Use getContain() instead.'
  430. );
  431. return $loader->getContain();
  432. }
  433. $queryBuilder = null;
  434. if (is_callable($override)) {
  435. $queryBuilder = $override;
  436. }
  437. if ($associations) {
  438. $loader->contain($associations, $queryBuilder);
  439. }
  440. $this->_addAssociationsToTypeMap(
  441. $this->getRepository(),
  442. $this->getTypeMap(),
  443. $loader->getContain()
  444. );
  445. return $this;
  446. }
  447. /**
  448. * @return array
  449. */
  450. public function getContain()
  451. {
  452. return $this->getEagerLoader()->getContain();
  453. }
  454. /**
  455. * Clears the contained associations from the current query.
  456. *
  457. * @return $this
  458. */
  459. public function clearContain()
  460. {
  461. $this->getEagerLoader()->clearContain();
  462. $this->_dirty();
  463. return $this;
  464. }
  465. /**
  466. * Used to recursively add contained association column types to
  467. * the query.
  468. *
  469. * @param \Cake\ORM\Table $table The table instance to pluck associations from.
  470. * @param \Cake\Database\TypeMap $typeMap The typemap to check for columns in.
  471. * This typemap is indirectly mutated via Cake\ORM\Query::addDefaultTypes()
  472. * @param array $associations The nested tree of associations to walk.
  473. * @return void
  474. */
  475. protected function _addAssociationsToTypeMap($table, $typeMap, $associations)
  476. {
  477. foreach ($associations as $name => $nested) {
  478. if (!$table->hasAssociation($name)) {
  479. continue;
  480. }
  481. $association = $table->getAssociation($name);
  482. $target = $association->getTarget();
  483. $primary = (array)$target->getPrimaryKey();
  484. if (empty($primary) || $typeMap->type($target->aliasField($primary[0])) === null) {
  485. $this->addDefaultTypes($target);
  486. }
  487. if (!empty($nested)) {
  488. $this->_addAssociationsToTypeMap($target, $typeMap, $nested);
  489. }
  490. }
  491. }
  492. /**
  493. * Adds filtering conditions to this query to only bring rows that have a relation
  494. * to another from an associated table, based on conditions in the associated table.
  495. *
  496. * This function will add entries in the `contain` graph.
  497. *
  498. * ### Example:
  499. *
  500. * ```
  501. * // Bring only articles that were tagged with 'cake'
  502. * $query->matching('Tags', function ($q) {
  503. * return $q->where(['name' => 'cake']);
  504. * );
  505. * ```
  506. *
  507. * It is possible to filter by deep associations by using dot notation:
  508. *
  509. * ### Example:
  510. *
  511. * ```
  512. * // Bring only articles that were commented by 'markstory'
  513. * $query->matching('Comments.Users', function ($q) {
  514. * return $q->where(['username' => 'markstory']);
  515. * );
  516. * ```
  517. *
  518. * As this function will create `INNER JOIN`, you might want to consider
  519. * calling `distinct` on this query as you might get duplicate rows if
  520. * your conditions don't filter them already. This might be the case, for example,
  521. * of the same user commenting more than once in the same article.
  522. *
  523. * ### Example:
  524. *
  525. * ```
  526. * // Bring unique articles that were commented by 'markstory'
  527. * $query->distinct(['Articles.id'])
  528. * ->matching('Comments.Users', function ($q) {
  529. * return $q->where(['username' => 'markstory']);
  530. * );
  531. * ```
  532. *
  533. * Please note that the query passed to the closure will only accept calling
  534. * `select`, `where`, `andWhere` and `orWhere` on it. If you wish to
  535. * add more complex clauses you can do it directly in the main query.
  536. *
  537. * @param string $assoc The association to filter by
  538. * @param callable|null $builder a function that will receive a pre-made query object
  539. * that can be used to add custom conditions or selecting some fields
  540. * @return $this
  541. */
  542. public function matching($assoc, callable $builder = null)
  543. {
  544. $result = $this->getEagerLoader()->setMatching($assoc, $builder)->getMatching();
  545. $this->_addAssociationsToTypeMap($this->getRepository(), $this->getTypeMap(), $result);
  546. $this->_dirty();
  547. return $this;
  548. }
  549. /**
  550. * Creates a LEFT JOIN with the passed association table while preserving
  551. * the foreign key matching and the custom conditions that were originally set
  552. * for it.
  553. *
  554. * This function will add entries in the `contain` graph.
  555. *
  556. * ### Example:
  557. *
  558. * ```
  559. * // Get the count of articles per user
  560. * $usersQuery
  561. * ->select(['total_articles' => $query->func()->count('Articles.id')])
  562. * ->leftJoinWith('Articles')
  563. * ->group(['Users.id'])
  564. * ->enableAutoFields(true);
  565. * ```
  566. *
  567. * You can also customize the conditions passed to the LEFT JOIN:
  568. *
  569. * ```
  570. * // Get the count of articles per user with at least 5 votes
  571. * $usersQuery
  572. * ->select(['total_articles' => $query->func()->count('Articles.id')])
  573. * ->leftJoinWith('Articles', function ($q) {
  574. * return $q->where(['Articles.votes >=' => 5]);
  575. * })
  576. * ->group(['Users.id'])
  577. * ->enableAutoFields(true);
  578. * ```
  579. *
  580. * This will create the following SQL:
  581. *
  582. * ```
  583. * SELECT COUNT(Articles.id) AS total_articles, Users.*
  584. * FROM users Users
  585. * LEFT JOIN articles Articles ON Articles.user_id = Users.id AND Articles.votes >= 5
  586. * GROUP BY USers.id
  587. * ```
  588. *
  589. * It is possible to left join deep associations by using dot notation
  590. *
  591. * ### Example:
  592. *
  593. * ```
  594. * // Total comments in articles by 'markstory'
  595. * $query
  596. * ->select(['total_comments' => $query->func()->count('Comments.id')])
  597. * ->leftJoinWith('Comments.Users', function ($q) {
  598. * return $q->where(['username' => 'markstory']);
  599. * )
  600. * ->group(['Users.id']);
  601. * ```
  602. *
  603. * Please note that the query passed to the closure will only accept calling
  604. * `select`, `where`, `andWhere` and `orWhere` on it. If you wish to
  605. * add more complex clauses you can do it directly in the main query.
  606. *
  607. * @param string $assoc The association to join with
  608. * @param callable|null $builder a function that will receive a pre-made query object
  609. * that can be used to add custom conditions or selecting some fields
  610. * @return $this
  611. */
  612. public function leftJoinWith($assoc, callable $builder = null)
  613. {
  614. $result = $this->getEagerLoader()
  615. ->setMatching($assoc, $builder, [
  616. 'joinType' => QueryInterface::JOIN_TYPE_LEFT,
  617. 'fields' => false
  618. ])
  619. ->getMatching();
  620. $this->_addAssociationsToTypeMap($this->getRepository(), $this->getTypeMap(), $result);
  621. $this->_dirty();
  622. return $this;
  623. }
  624. /**
  625. * Creates an INNER JOIN with the passed association table while preserving
  626. * the foreign key matching and the custom conditions that were originally set
  627. * for it.
  628. *
  629. * This function will add entries in the `contain` graph.
  630. *
  631. * ### Example:
  632. *
  633. * ```
  634. * // Bring only articles that were tagged with 'cake'
  635. * $query->innerJoinWith('Tags', function ($q) {
  636. * return $q->where(['name' => 'cake']);
  637. * );
  638. * ```
  639. *
  640. * This will create the following SQL:
  641. *
  642. * ```
  643. * SELECT Articles.*
  644. * FROM articles Articles
  645. * INNER JOIN tags Tags ON Tags.name = 'cake'
  646. * INNER JOIN articles_tags ArticlesTags ON ArticlesTags.tag_id = Tags.id
  647. * AND ArticlesTags.articles_id = Articles.id
  648. * ```
  649. *
  650. * This function works the same as `matching()` with the difference that it
  651. * will select no fields from the association.
  652. *
  653. * @param string $assoc The association to join with
  654. * @param callable|null $builder a function that will receive a pre-made query object
  655. * that can be used to add custom conditions or selecting some fields
  656. * @return $this
  657. * @see \Cake\ORM\Query::matching()
  658. */
  659. public function innerJoinWith($assoc, callable $builder = null)
  660. {
  661. $result = $this->getEagerLoader()
  662. ->setMatching($assoc, $builder, [
  663. 'joinType' => QueryInterface::JOIN_TYPE_INNER,
  664. 'fields' => false
  665. ])
  666. ->getMatching();
  667. $this->_addAssociationsToTypeMap($this->getRepository(), $this->getTypeMap(), $result);
  668. $this->_dirty();
  669. return $this;
  670. }
  671. /**
  672. * Adds filtering conditions to this query to only bring rows that have no match
  673. * to another from an associated table, based on conditions in the associated table.
  674. *
  675. * This function will add entries in the `contain` graph.
  676. *
  677. * ### Example:
  678. *
  679. * ```
  680. * // Bring only articles that were not tagged with 'cake'
  681. * $query->notMatching('Tags', function ($q) {
  682. * return $q->where(['name' => 'cake']);
  683. * );
  684. * ```
  685. *
  686. * It is possible to filter by deep associations by using dot notation:
  687. *
  688. * ### Example:
  689. *
  690. * ```
  691. * // Bring only articles that weren't commented by 'markstory'
  692. * $query->notMatching('Comments.Users', function ($q) {
  693. * return $q->where(['username' => 'markstory']);
  694. * );
  695. * ```
  696. *
  697. * As this function will create a `LEFT JOIN`, you might want to consider
  698. * calling `distinct` on this query as you might get duplicate rows if
  699. * your conditions don't filter them already. This might be the case, for example,
  700. * of the same article having multiple comments.
  701. *
  702. * ### Example:
  703. *
  704. * ```
  705. * // Bring unique articles that were commented by 'markstory'
  706. * $query->distinct(['Articles.id'])
  707. * ->notMatching('Comments.Users', function ($q) {
  708. * return $q->where(['username' => 'markstory']);
  709. * );
  710. * ```
  711. *
  712. * Please note that the query passed to the closure will only accept calling
  713. * `select`, `where`, `andWhere` and `orWhere` on it. If you wish to
  714. * add more complex clauses you can do it directly in the main query.
  715. *
  716. * @param string $assoc The association to filter by
  717. * @param callable|null $builder a function that will receive a pre-made query object
  718. * that can be used to add custom conditions or selecting some fields
  719. * @return $this
  720. */
  721. public function notMatching($assoc, callable $builder = null)
  722. {
  723. $result = $this->getEagerLoader()
  724. ->setMatching($assoc, $builder, [
  725. 'joinType' => QueryInterface::JOIN_TYPE_LEFT,
  726. 'fields' => false,
  727. 'negateMatch' => true
  728. ])
  729. ->getMatching();
  730. $this->_addAssociationsToTypeMap($this->getRepository(), $this->getTypeMap(), $result);
  731. $this->_dirty();
  732. return $this;
  733. }
  734. /**
  735. * {@inheritDoc}
  736. *
  737. * Populates or adds parts to current query clauses using an array.
  738. * This is handy for passing all query clauses at once. The option array accepts:
  739. *
  740. * - fields: Maps to the select method
  741. * - conditions: Maps to the where method
  742. * - limit: Maps to the limit method
  743. * - order: Maps to the order method
  744. * - offset: Maps to the offset method
  745. * - group: Maps to the group method
  746. * - having: Maps to the having method
  747. * - contain: Maps to the contain options for eager loading
  748. * - join: Maps to the join method
  749. * - page: Maps to the page method
  750. *
  751. * ### Example:
  752. *
  753. * ```
  754. * $query->applyOptions([
  755. * 'fields' => ['id', 'name'],
  756. * 'conditions' => [
  757. * 'created >=' => '2013-01-01'
  758. * ],
  759. * 'limit' => 10
  760. * ]);
  761. * ```
  762. *
  763. * Is equivalent to:
  764. *
  765. * ```
  766. * $query
  767. * ->select(['id', 'name'])
  768. * ->where(['created >=' => '2013-01-01'])
  769. * ->limit(10)
  770. * ```
  771. */
  772. public function applyOptions(array $options)
  773. {
  774. $valid = [
  775. 'fields' => 'select',
  776. 'conditions' => 'where',
  777. 'join' => 'join',
  778. 'order' => 'order',
  779. 'limit' => 'limit',
  780. 'offset' => 'offset',
  781. 'group' => 'group',
  782. 'having' => 'having',
  783. 'contain' => 'contain',
  784. 'page' => 'page',
  785. ];
  786. ksort($options);
  787. foreach ($options as $option => $values) {
  788. if (isset($valid[$option], $values)) {
  789. $this->{$valid[$option]}($values);
  790. } else {
  791. $this->_options[$option] = $values;
  792. }
  793. }
  794. return $this;
  795. }
  796. /**
  797. * Creates a copy of this current query, triggers beforeFind and resets some state.
  798. *
  799. * The following state will be cleared:
  800. *
  801. * - autoFields
  802. * - limit
  803. * - offset
  804. * - map/reduce functions
  805. * - result formatters
  806. * - order
  807. * - containments
  808. *
  809. * This method creates query clones that are useful when working with subqueries.
  810. *
  811. * @return \Cake\ORM\Query
  812. */
  813. public function cleanCopy()
  814. {
  815. $clone = clone $this;
  816. $clone->setEagerLoader(clone $this->getEagerLoader());
  817. $clone->triggerBeforeFind();
  818. $clone->enableAutoFields(false);
  819. $clone->limit(null);
  820. $clone->order([], true);
  821. $clone->offset(null);
  822. $clone->mapReduce(null, null, true);
  823. $clone->formatResults(null, true);
  824. $clone->setSelectTypeMap(new TypeMap());
  825. $clone->decorateResults(null, true);
  826. return $clone;
  827. }
  828. /**
  829. * Object clone hook.
  830. *
  831. * Destroys the clones inner iterator and clones the value binder, and eagerloader instances.
  832. *
  833. * @return void
  834. */
  835. public function __clone()
  836. {
  837. parent::__clone();
  838. if ($this->_eagerLoader) {
  839. $this->_eagerLoader = clone $this->_eagerLoader;
  840. }
  841. }
  842. /**
  843. * {@inheritDoc}
  844. *
  845. * Returns the COUNT(*) for the query. If the query has not been
  846. * modified, and the count has already been performed the cached
  847. * value is returned
  848. */
  849. public function count()
  850. {
  851. if ($this->_resultsCount === null) {
  852. $this->_resultsCount = $this->_performCount();
  853. }
  854. return $this->_resultsCount;
  855. }
  856. /**
  857. * Performs and returns the COUNT(*) for the query.
  858. *
  859. * @return int
  860. */
  861. protected function _performCount()
  862. {
  863. $query = $this->cleanCopy();
  864. $counter = $this->_counter;
  865. if ($counter) {
  866. $query->counter(null);
  867. return (int)$counter($query);
  868. }
  869. $complex = (
  870. $query->clause('distinct') ||
  871. count($query->clause('group')) ||
  872. count($query->clause('union')) ||
  873. $query->clause('having')
  874. );
  875. if (!$complex) {
  876. // Expression fields could have bound parameters.
  877. foreach ($query->clause('select') as $field) {
  878. if ($field instanceof ExpressionInterface) {
  879. $complex = true;
  880. break;
  881. }
  882. }
  883. }
  884. if (!$complex && $this->_valueBinder !== null) {
  885. $order = $this->clause('order');
  886. $complex = $order === null ? false : $order->hasNestedExpression();
  887. }
  888. $count = ['count' => $query->func()->count('*')];
  889. if (!$complex) {
  890. $query->getEagerLoader()->enableAutoFields(false);
  891. $statement = $query
  892. ->select($count, true)
  893. ->enableAutoFields(false)
  894. ->execute();
  895. } else {
  896. $statement = $this->getConnection()->newQuery()
  897. ->select($count)
  898. ->from(['count_source' => $query])
  899. ->execute();
  900. }
  901. $result = $statement->fetch('assoc')['count'];
  902. $statement->closeCursor();
  903. return (int)$result;
  904. }
  905. /**
  906. * Registers a callable function that will be executed when the `count` method in
  907. * this query is called. The return value for the function will be set as the
  908. * return value of the `count` method.
  909. *
  910. * This is particularly useful when you need to optimize a query for returning the
  911. * count, for example removing unnecessary joins, removing group by or just return
  912. * an estimated number of rows.
  913. *
  914. * The callback will receive as first argument a clone of this query and not this
  915. * query itself.
  916. *
  917. * If the first param is a null value, the built-in counter function will be called
  918. * instead
  919. *
  920. * @param callable|null $counter The counter value
  921. * @return $this
  922. */
  923. public function counter($counter)
  924. {
  925. $this->_counter = $counter;
  926. return $this;
  927. }
  928. /**
  929. * Toggle hydrating entities.
  930. *
  931. * If set to false array results will be returned for the query.
  932. *
  933. * @param bool $enable Use a boolean to set the hydration mode.
  934. * @return $this
  935. */
  936. public function enableHydration($enable = true)
  937. {
  938. $this->_dirty();
  939. $this->_hydrate = (bool)$enable;
  940. return $this;
  941. }
  942. /**
  943. * Returns the current hydration mode.
  944. *
  945. * @return bool
  946. */
  947. public function isHydrationEnabled()
  948. {
  949. return $this->_hydrate;
  950. }
  951. /**
  952. * Toggle hydrating entities.
  953. *
  954. * If set to false array results will be returned.
  955. *
  956. * @deprecated 3.4.0 Use enableHydration()/isHydrationEnabled() instead.
  957. * @param bool|null $enable Use a boolean to set the hydration mode.
  958. * Null will fetch the current hydration mode.
  959. * @return bool|$this A boolean when reading, and $this when setting the mode.
  960. */
  961. public function hydrate($enable = null)
  962. {
  963. deprecationWarning(
  964. 'Query::hydrate() is deprecated. ' .
  965. 'Use enableHydration()/isHydrationEnabled() instead.'
  966. );
  967. if ($enable === null) {
  968. return $this->isHydrationEnabled();
  969. }
  970. return $this->enableHydration($enable);
  971. }
  972. /**
  973. * {@inheritDoc}
  974. *
  975. * @return $this
  976. * @throws \RuntimeException When you attempt to cache a non-select query.
  977. */
  978. public function cache($key, $config = 'default')
  979. {
  980. if ($this->_type !== 'select' && $this->_type !== null) {
  981. throw new RuntimeException('You cannot cache the results of non-select queries.');
  982. }
  983. return $this->_cache($key, $config);
  984. }
  985. /**
  986. * {@inheritDoc}
  987. *
  988. * @throws \RuntimeException if this method is called on a non-select Query.
  989. */
  990. public function all()
  991. {
  992. if ($this->_type !== 'select' && $this->_type !== null) {
  993. throw new RuntimeException(
  994. 'You cannot call all() on a non-select query. Use execute() instead.'
  995. );
  996. }
  997. return $this->_all();
  998. }
  999. /**
  1000. * Trigger the beforeFind event on the query's repository object.
  1001. *
  1002. * Will not trigger more than once, and only for select queries.
  1003. *
  1004. * @return void
  1005. */
  1006. public function triggerBeforeFind()
  1007. {
  1008. if (!$this->_beforeFindFired && $this->_type === 'select') {
  1009. $table = $this->getRepository();
  1010. $this->_beforeFindFired = true;
  1011. /* @var \Cake\Event\EventDispatcherInterface $table */
  1012. $table->dispatchEvent('Model.beforeFind', [
  1013. $this,
  1014. new ArrayObject($this->_options),
  1015. !$this->isEagerLoaded()
  1016. ]);
  1017. }
  1018. }
  1019. /**
  1020. * {@inheritDoc}
  1021. */
  1022. public function sql(ValueBinder $binder = null)
  1023. {
  1024. $this->triggerBeforeFind();
  1025. $this->_transformQuery();
  1026. return parent::sql($binder);
  1027. }
  1028. /**
  1029. * Executes this query and returns a ResultSet object containing the results.
  1030. * This will also setup the correct statement class in order to eager load deep
  1031. * associations.
  1032. *
  1033. * @return \Cake\ORM\ResultSet
  1034. */
  1035. protected function _execute()
  1036. {
  1037. $this->triggerBeforeFind();
  1038. if ($this->_results) {
  1039. $decorator = $this->_decoratorClass();
  1040. return new $decorator($this->_results);
  1041. }
  1042. $statement = $this->getEagerLoader()->loadExternal($this, $this->execute());
  1043. return new ResultSet($this, $statement);
  1044. }
  1045. /**
  1046. * Applies some defaults to the query object before it is executed.
  1047. *
  1048. * Specifically add the FROM clause, adds default table fields if none are
  1049. * specified and applies the joins required to eager load associations defined
  1050. * using `contain`
  1051. *
  1052. * It also sets the default types for the columns in the select clause
  1053. *
  1054. * @see \Cake\Database\Query::execute()
  1055. * @return void
  1056. */
  1057. protected function _transformQuery()
  1058. {
  1059. if (!$this->_dirty || $this->_type !== 'select') {
  1060. return;
  1061. }
  1062. if (empty($this->_parts['from'])) {
  1063. $this->from([$this->_repository->getAlias() => $this->_repository->getTable()]);
  1064. }
  1065. $this->_addDefaultFields();
  1066. $this->getEagerLoader()->attachAssociations($this, $this->_repository, !$this->_hasFields);
  1067. $this->_addDefaultSelectTypes();
  1068. }
  1069. /**
  1070. * Inspects if there are any set fields for selecting, otherwise adds all
  1071. * the fields for the default table.
  1072. *
  1073. * @return void
  1074. */
  1075. protected function _addDefaultFields()
  1076. {
  1077. $select = $this->clause('select');
  1078. $this->_hasFields = true;
  1079. if (!count($select) || $this->_autoFields === true) {
  1080. $this->_hasFields = false;
  1081. $this->select($this->getRepository()->getSchema()->columns());
  1082. $select = $this->clause('select');
  1083. }
  1084. $aliased = $this->aliasFields($select, $this->getRepository()->getAlias());
  1085. $this->select($aliased, true);
  1086. }
  1087. /**
  1088. * Sets the default types for converting the fields in the select clause
  1089. *
  1090. * @return void
  1091. */
  1092. protected function _addDefaultSelectTypes()
  1093. {
  1094. $typeMap = $this->getTypeMap()->getDefaults();
  1095. $select = $this->clause('select');
  1096. $types = [];
  1097. foreach ($select as $alias => $value) {
  1098. if (isset($typeMap[$alias])) {
  1099. $types[$alias] = $typeMap[$alias];
  1100. continue;
  1101. }
  1102. if (is_string($value) && isset($typeMap[$value])) {
  1103. $types[$alias] = $typeMap[$value];
  1104. }
  1105. if ($value instanceof TypedResultInterface) {
  1106. $types[$alias] = $value->getReturnType();
  1107. }
  1108. }
  1109. $this->getSelectTypeMap()->addDefaults($types);
  1110. }
  1111. /**
  1112. * {@inheritDoc}
  1113. *
  1114. * @see \Cake\ORM\Table::find()
  1115. */
  1116. public function find($finder, array $options = [])
  1117. {
  1118. return $this->getRepository()->callFinder($finder, $this, $options);
  1119. }
  1120. /**
  1121. * Marks a query as dirty, removing any preprocessed information
  1122. * from in memory caching such as previous results
  1123. *
  1124. * @return void
  1125. */
  1126. protected function _dirty()
  1127. {
  1128. $this->_results = null;
  1129. $this->_resultsCount = null;
  1130. parent::_dirty();
  1131. }
  1132. /**
  1133. * Create an update query.
  1134. *
  1135. * This changes the query type to be 'update'.
  1136. * Can be combined with set() and where() methods to create update queries.
  1137. *
  1138. * @param string|null $table Unused parameter.
  1139. * @return $this
  1140. */
  1141. public function update($table = null)
  1142. {
  1143. $table = $table ?: $this->getRepository()->getTable();
  1144. return parent::update($table);
  1145. }
  1146. /**
  1147. * Create a delete query.
  1148. *
  1149. * This changes the query type to be 'delete'.
  1150. * Can be combined with the where() method to create delete queries.
  1151. *
  1152. * @param string|null $table Unused parameter.
  1153. * @return $this
  1154. */
  1155. public function delete($table = null)
  1156. {
  1157. $repo = $this->getRepository();
  1158. $this->from([$repo->getAlias() => $repo->getTable()]);
  1159. return parent::delete();
  1160. }
  1161. /**
  1162. * Create an insert query.
  1163. *
  1164. * This changes the query type to be 'insert'.
  1165. * Note calling this method will reset any data previously set
  1166. * with Query::values()
  1167. *
  1168. * Can be combined with the where() method to create delete queries.
  1169. *
  1170. * @param array $columns The columns to insert into.
  1171. * @param array $types A map between columns & their datatypes.
  1172. * @return $this
  1173. */
  1174. public function insert(array $columns, array $types = [])
  1175. {
  1176. $table = $this->getRepository()->getTable();
  1177. $this->into($table);
  1178. return parent::insert($columns, $types);
  1179. }
  1180. /**
  1181. * {@inheritDoc}
  1182. *
  1183. * @throws \BadMethodCallException if the method is called for a non-select query
  1184. */
  1185. public function __call($method, $arguments)
  1186. {
  1187. if ($this->type() === 'select') {
  1188. return $this->_call($method, $arguments);
  1189. }
  1190. throw new \BadMethodCallException(
  1191. sprintf('Cannot call method "%s" on a "%s" query', $method, $this->type())
  1192. );
  1193. }
  1194. /**
  1195. * {@inheritDoc}
  1196. */
  1197. public function __debugInfo()
  1198. {
  1199. $eagerLoader = $this->getEagerLoader();
  1200. return parent::__debugInfo() + [
  1201. 'hydrate' => $this->_hydrate,
  1202. 'buffered' => $this->_useBufferedResults,
  1203. 'formatters' => count($this->_formatters),
  1204. 'mapReducers' => count($this->_mapReduce),
  1205. 'contain' => $eagerLoader ? $eagerLoader->getContain() : [],
  1206. 'matching' => $eagerLoader ? $eagerLoader->getMatching() : [],
  1207. 'extraOptions' => $this->_options,
  1208. 'repository' => $this->_repository
  1209. ];
  1210. }
  1211. /**
  1212. * Executes the query and converts the result set into JSON.
  1213. *
  1214. * Part of JsonSerializable interface.
  1215. *
  1216. * @return \Cake\Datasource\ResultSetInterface The data to convert to JSON.
  1217. */
  1218. public function jsonSerialize()
  1219. {
  1220. return $this->all();
  1221. }
  1222. /**
  1223. * Sets whether or not the ORM should automatically append fields.
  1224. *
  1225. * By default calling select() will disable auto-fields. You can re-enable
  1226. * auto-fields with this method.
  1227. *
  1228. * @param bool $value Set true to enable, false to disable.
  1229. * @return $this
  1230. */
  1231. public function enableAutoFields($value = true)
  1232. {
  1233. $this->_autoFields = (bool)$value;
  1234. return $this;
  1235. }
  1236. /**
  1237. * Gets whether or not the ORM should automatically append fields.
  1238. *
  1239. * By default calling select() will disable auto-fields. You can re-enable
  1240. * auto-fields with enableAutoFields().
  1241. *
  1242. * @return bool The current value.
  1243. */
  1244. public function isAutoFieldsEnabled()
  1245. {
  1246. return $this->_autoFields;
  1247. }
  1248. /**
  1249. * Get/Set whether or not the ORM should automatically append fields.
  1250. *
  1251. * By default calling select() will disable auto-fields. You can re-enable
  1252. * auto-fields with this method.
  1253. *
  1254. * @deprecated 3.4.0 Use enableAutoFields()/isAutoFieldsEnabled() instead.
  1255. * @param bool|null $value The value to set or null to read the current value.
  1256. * @return bool|$this Either the current value or the query object.
  1257. */
  1258. public function autoFields($value = null)
  1259. {
  1260. deprecationWarning(
  1261. 'Query::autoFields() is deprecated. ' .
  1262. 'Use enableAutoFields()/isAutoFieldsEnabled() instead.'
  1263. );
  1264. if ($value === null) {
  1265. return $this->isAutoFieldsEnabled();
  1266. }
  1267. return $this->enableAutoFields($value);
  1268. }
  1269. /**
  1270. * Decorates the results iterator with MapReduce routines and formatters
  1271. *
  1272. * @param \Traversable $result Original results
  1273. * @return \Cake\Datasource\ResultSetInterface
  1274. */
  1275. protected function _decorateResults($result)
  1276. {
  1277. $result = $this->_applyDecorators($result);
  1278. if (!($result instanceof ResultSet) && $this->isBufferedResultsEnabled()) {
  1279. $class = $this->_decoratorClass();
  1280. $result = new $class($result->buffered());
  1281. }
  1282. return $result;
  1283. }
  1284. }