10000 [Form] Moved logic of addXxx()/removeXxx() methods to the PropertyPath class by webmozart · Pull Request #3819 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Form] Moved logic of addXxx()/removeXxx() methods to the PropertyPath class #3819

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 10, 2012
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CHANGELOG-2.1.md
Original file line number Diff line number Diff line change
Expand Up @@ -251,8 +251,8 @@ To get the diff between two versions, go to https://github.com/symfony/symfony/c
* the radio type is now a child of the checkbox type
* the collection, choice (with multiple selection) and entity (with multiple
selection) types now make use of addXxx() and removeXxx() methods in your
model
* added options "add_method" and "remove_method" to collection and choice type
model. For a custom, non-recognized singular form, set the "property_path"
option like this: "plural|singular"
* forms now don't create an empty object anymore if they are completely
empty and not required. The empty value for such forms is null.
* added constant Guess::VERY_HIGH_CONFIDENCE
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,16 @@ public function mapDataToForms($data, array $forms)
public function mapDataToForm($data, FormInterface $form)
{
if (!empty($data)) {
if (null !== $form->getAttribute('property_path')) {
$form->setData($form->getAttribute('property_path')->getValue($data));
$propertyPath = $form->getAttribute('property_path');

if (null !== $propertyPath) {
$propertyData = $propertyPath->getValue($data);

if (is_object($propertyData) && !$form->getAttribute('by_reference')) {
$propertyData = clone $propertyData;
}

$form->setData($propertyData);
}
}
}
Expand All @@ -77,9 +85,9 @@ public function mapFormsToData(array $forms, &$data)

public function mapFormToData(FormInterface $form, &$data)
{
if (null !== $form->getAttribute('property_path') && $form->isSynchronized()) {
$propertyPath = $form->getAttribute('property_path');
$propertyPath = $form->getAttribute('property_path');

if (null !== $propertyPath && $form->isSynchronized()) {
// If the data is identical to the value in $data, we are
// dealing with a reference
$isReference = $form->getData() === $propertyPath->getValue($data);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,21 +25,6 @@
*/
class MergeCollectionListener implements EventSubscriberInterface
{
/**
* Strategy for merging the new collection into the old collection
*
* @var integer
*/
const MERGE_NORMAL = 1;

/**
* Strategy for calling add/remove methods on the parent data for all
* new/removed elements in the new collection
*
* @var integer
*/
const MERGE_INTO_PARENT = 2;

/**
* Whether elements may be added to the collection
* @var Boolean
Expand All @@ -52,131 +37,33 @@ class MergeCollectionListener implements EventSubscriberInterface
*/
private $allowDelete;

/**
* Whether to search for and use adder and remover methods
* @var Boolean
*/
private $mergeStrategy;

/**
* The name of the adder method to look for
* @var string
*/
private $addMethod;

/**
* The name of the remover method to look for
* @var string
*/
private $removeMethod;

/**
* A copy of the data before starting binding for this form
* @var mixed
*/
private $dataSnapshot;

/**
* Creates a new listener.
*
* @param Boolean $allowAdd Whether values might be added to the
* 10000 collection.
* @param Boolean $allowDelete Whether values might be removed from the
* collection.
* @param integer $mergeStrategy Which strategy to use for merging the
* bound collection with the original
* collection. Might be any combination of
* MERGE_NORMAL and MERGE_INTO_PARENT.
* MERGE_INTO_PARENT has precedence over
* MERGE_NORMAL if an adder/remover method
* is found. The default strategy is to use
* both strategies.
* @param string $addMethod The name of the adder method to use. If
* not given, the listener tries to discover
* the method automatically.
* @param string $removeMethod The name of the remover method to use. If
* not given, the listener tries to discover
* the method automatically.
*
* @throws FormException If the given strategy is invalid.
*/
public function __construct($allowAdd = false, $allowDelete = false, $mergeStrategy = null, $addMethod = null, $removeMethod = null)
public function __construct($allowAdd = false, $allowDelete = false)
{
if ($mergeStrategy && !($mergeStrategy & (self::MERGE_NORMAL | self::MERGE_INTO_PARENT))) {
throw new FormException('The merge strategy needs to be at least MERGE_NORMAL or MERGE_INTO_PARENT');
}

$this->allowAdd = $allowAdd;
$this->allowDelete = $allowDelete;
$this->mergeStrategy = $mergeStrategy ?: self::MERGE_NORMAL | self::MERGE_INTO_PARENT;
$this->addMethod = $addMethod;
$this->removeMethod = $removeMethod;
}

static public function getSubscribedEvents()
{
return array(
FormEvents::PRE_BIND => 'preBind',
FormEvents::BIND_NORM_DATA => 'onBindNormData',
);
}

public function preBind(DataEvent $event)
{
// Get a snapshot of the current state of the normalized data
// to compare against later
$this->dataSnapshot = $event->getForm()->getNormData();

if (is_object($this->dataSnapshot)) {
// Make sure the snapshot remains stable and doesn't change
$this->dataSnapshot = clone $this->dataSnapshot;
}

if (null !== $this->dataSnapshot && !is_array($this->dataSnapshot) && !($this->dataSnapshot instanceof \Traversable && $this->dataSnapshot instanceof \ArrayAccess)) {
throw new UnexpectedTypeException($this->dataSnapshot, 'array or (\Traversable and \ArrayAccess)');
}
}

public function onBindNormData(FilterDataEvent $event)
{
$originalData = $event->getForm()->getNormData();

// If we are not allowed to change anything, return immediately
if (!$this->allowAdd && !$this->allowDelete) {
// Don't set to the snapshot as then we are switching from the
// original object to its copy, which might break things
$event->setData($originalData);

return;
}
$dataToMergeInto = $event->getForm()->getNormData();

$form = $event->getForm();
$data = $event->getData();
$childPropertyPath = null;
$parentData = null;
$addMethod = null;
$removeMethod = null;
$propertyPath = null;
$plural = null;

if ($form->hasParent() && $form->getAttribute('property_path')) {
$propertyPath = new PropertyPath($form->getAttribute('property_path'));
$childPropertyPath = $propertyPath;
$parentData = $form->getParent()->getClientData();
$lastElement = $propertyPath->getElement($propertyPath->getLength() - 1);

// If the property path contains more than one element, the parent
// data is the object at the parent property path
if ($propertyPath->getLength() > 1) {
$parentData = $propertyPath->getParent()->getValue($parentData);

// Property path relative to $parentData
$childPropertyPath = new PropertyPath($lastElement);
}

// The plural form is the last element of the property path
$plural = ucfirst($lastElement);
}

if (null === $data) {
$data = array();
Expand All @@ -186,157 +73,60 @@ public function onBindNormData(FilterDataEvent $event)
throw new UnexpectedTypeException($data, 'array or (\Traversable and \ArrayAccess)');
}

if (null !== $originalData && !is_array($originalData) && !($originalData instanceof \Traversable && $originalData 97AE instanceof \ArrayAccess)) {
throw new UnexpectedTypeException($originalData, 'array or (\Traversable and \ArrayAccess)');
if (null !== $dataToMergeInto && !is_array($dataToMergeInto) && !($dataToMergeInto instanceof \Traversable && $dataToMergeInto instanceof \ArrayAccess)) {
throw new UnexpectedTypeException($dataToMergeInto, 'array or (\Traversable and \ArrayAccess)');
}

// Check if the parent has matching methods to add/remove items
if (($this->mergeStrategy & self::MERGE_INTO_PARENT) && is_object($parentData)) {
$reflClass = new \ReflectionClass($parentData);
$addMethodNeeded = $this->allowAdd && !$this->addMethod;
$removeMethodNeeded = $this->allowDelete && !$this->removeMethod;

// Any of the two methods is required, but not yet known
if ($addMethodNeeded || $removeMethodNeeded) {
$singulars = (array) FormUtil::singularify($plural);

foreach ($singulars as $singular) {
// Try to find adder, but don't override preconfigured one
if ($addMethodNeeded) {
$addMethod = 'add' . $singular;

// False alert
if (!$this->isAccessible($reflClass, $addMethod, 1)) {
$addMethod = null;
}
}

// Try to find remover, but don't override preconfigured one
if ($removeMethodNeeded) {
$removeMethod = 'remove' . $singular;

// False alert
if (!$this->isAccessible($reflClass, $removeMethod, 1)) {
$removeMethod = null;
}
}

// Found all that we need. Abort search.
if ((!$addMethodNeeded || $addMethod) && (!$removeMethodNeeded || $removeMethod)) {
break;
}

// False alert
$addMethod = null;
$removeMethod = null;
}
}

// Set preconfigured adder
if ($this->allowAdd && $this->addMethod) {
$addMethod = $this->addMethod;

if (!$this->isAccessible($reflClass, $addMethod, 1)) {
throw new FormException(sprintf(
'The public method "%s" could not be found on class %s',
$addMethod,
$reflClass->getName()
));
}
}

// Set preconfigured remover
if ($this->allowDelete && $this->removeMethod) {
$removeMethod = $this->removeMethod;
// If we are not allowed to change anything, return immediately
if ((!$this->allowAdd && !$this->allowDelete) || $data === $dataToMergeInto) {
$event->setData($dataToMergeInto);

if (!$this->isAccessible($reflClass, $removeMethod, 1)) {
throw new FormException(sprintf(
'The public method "%s" could not be found on class %s',
$removeMethod,
$reflClass->getName()
));
}
}
return;
}

// Calculate delta between $data and the snapshot created in PRE_BIND
$itemsToDelete = array();
$itemsToAdd = is_object($data) ? clone $data : $data;

if ($this->dataSnapshot) {
foreach ($this->dataSnapshot as $originalItem) {
foreach ($data as $key => $item) {
if ($item === $originalItem) {
if (!$dataToMergeInto) {
// No original data was set. Set it if allowed
if ($this->allowAdd) {
$dataToMergeInto = $data;
}
} else {
// Calculate delta
$itemsToAdd = is_object($data) ? clone $data : $data;
$itemsToDelete = array();

foreach ($dataToMergeInto as $beforeKey => $beforeItem) {
foreach ($data as $afterKey => $afterItem) {
if ($afterItem === $beforeItem) {
// Item found, next original item
unset($itemsToAdd[$key]);
unset($itemsToAdd[$afterKey]);
continue 2;
}
}

// Item not found, remember for deletion
foreach ($originalData as $key => $item) {
if ($item === $originalItem) {
$itemsToDelete[$key] = $item;
continue 2;
}
}
}
}

if ($addMethod || $removeMethod) {
// If methods to add and to remove exist, call them now, if allowed
if ($removeMethod) {
foreach ($itemsToDelete as $item) {
$parentData->$removeMethod($item);
}
$itemsToDelete[] = $beforeKey;
}

if ($addMethod) {
foreach ($itemsToAdd as $item) {
$parentData->$addMethod($item);
// Remove deleted items before adding to free keys that are to be
// replaced
if ($this->allowDelete) {
foreach ($itemsToDelete as $key) {
unset($dataToMergeInto[$key]);
}
}

$event->setData($childPropertyPath->getValue($parentData));
} elseif ($this->mergeStrategy & self::MERGE_NORMAL) {
if (!$originalData) {
// No original data was set. Set it if allowed
if ($this->allowAdd) {
$originalData = $data;
}
} else {
// Original data is an array-like structure
// Add and remove items in the original variable
if ($this->allowDelete) {
foreach ($itemsToDelete as $key => $item) {
unset($originalData[$key]);
// Add remaining items
if ($this->allowAdd) {
foreach ($itemsToAdd as $key => $item) {
if (!isset($dataToMergeInto[$key])) {
$dataToMergeInto[$key] = $item;
} else {
$dataToMergeInto[] = $item;
}
}

if ($this->allowAdd) {
foreach ($itemsToAdd as $key => $item) {
if (!isset($originalData[$key])) {
$originalData[$key] = $item;
} else {
$originalData[] = $item;
}
}
}
}

$event->setData($originalData);
}
}

private function isAccessible(\ReflectionClass $reflClass, $methodName, $numberOfRequiredParameters) {
if ($reflClass->hasMethod($methodName)) {
$method = $reflClass->getMethod($methodName);

if ($method->isPublic() && $method->getNumberOfRequiredParameters() === $numberOfRequiredParameters) {
return true;
}
}

return false;
$event->setData($dataToMergeInto);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,8 @@ public function onBindNormData(FilterDataEvent $event)
throw new UnexpectedTypeException($data, 'array or (\Traversable and \ArrayAccess)');
}

// The data mapper only adds, but does not remove items, so do this
// here
if ($this->allowDelete) {
foreach ($data as $name => $child) {
if (!$form->has($name)) {
Expand Down
Loading
0