cphalcon icon indicating copy to clipboard operation
cphalcon copied to clipboard

Dangerous collection clone

Open tacxou opened this issue 7 years ago • 1 comments

Phalcon 3.x

If the user tries to create a new behavior to duplicate records, the collection class can create unexpected errors,

Example of a dangerous collection:

class Robot extends Collection
{
	public $name;

	// This method will be triggered at each iteration on the records
	public function __clone()
	{
		$this->_id = new MongoId;
	}

	...
}

The clone method is triggered at each record:

# Part of https://github.com/phalcon/cphalcon/blob/3.4.x/phalcon/mvc/collection.zep

protected static function _getResultset(var params, <CollectionInterface> collection, connection, boolean unique)
{
        ...
	if unique === true {

	       /**
		* Requesting a single result
		*/
		documentsCursor->rewind();

		let document = documentsCursor->current();

		if typeof document != "array" {
			return false;
		}

	       /**
		* Assign the values to the base object
		*/
		return static::cloneResult(base, document);
	}

       /**
	* Requesting a complete resultset
	*/
	let collections = [];
	for document in iterator_to_array(documentsCursor, false) {

	       /**
		* Assign the values to the base object
		*/
		let collections[] = static::cloneResult(base, document);
	}

	return collections;
}

The method that clones the result:

# Part of https://github.com/phalcon/cphalcon/blob/3.4.x/phalcon/mvc/collection.zep

public static function cloneResult(<CollectionInterface> collection, array! document) -> <CollectionInterface>
{
	var clonedCollection, key, value;

	let clonedCollection = clone collection;
	for key, value in document {
		clonedCollection->writeAttribute(key, value);
	}

	if method_exists(clonedCollection, "afterFetch") {
		clonedCollection->{"afterFetch"}();
	}

	return clonedCollection;
}

Some solutions:

  • Prevent from changing the clone's behavior
abstract class Collection implements EntityInterface, CollectionInterface, InjectionAwareInterface, \Serializable
{
	...

	// Override
	public final function __clone()
	{
	}
}
  • Do not use cloneResult in find/findFirst
  • Put an information message in the documentation

tacxou avatar Jul 01 '19 10:07 tacxou

Sadly this is a very old and unattended issue. We don't even support mongo in cphalcon - there is an incubator package there.

Apologies but this will not be addressed.

niden avatar Jun 08 '26 23:06 niden