Skip to content

Commit

Permalink
Use a stricter get+has pattern for associations on tables.
Browse files Browse the repository at this point in the history
  • Loading branch information
dereuromark committed Jan 16, 2018
1 parent c20de0f commit f7b3e0b
Showing 1 changed file with 49 additions and 5 deletions.
54 changes: 49 additions & 5 deletions src/ORM/Table.php
Expand Up @@ -934,17 +934,17 @@ public function hasBehavior($name)
}

/**
* Returns an association object configured for the specified alias if any
* Returns an association object configured for the specified alias if any.
*
* @deprecated 3.6.0 Use getAssociation() instead.
* @param string $name the alias used for the association.
* @return \Cake\ORM\Association|null Either the association or null.
*/
public function association($name)
{
deprecationWarning('Use Table::getAssociation() instead.');
deprecationWarning('Use Table::getAssociation() and Table::hasAssocation() instead.');

return $this->getAssociation($name);
return $this->findAssociation($name);
}

/**
Expand All @@ -956,10 +956,54 @@ public function association($name)
* $users = $this->getAssociation('Articles.Comments.Users');
* ```
*
* @param string $name the alias used for the association.
* @return \Cake\ORM\Association|null Either the association or null.
* Note that this method requires the association to be present or otherwise
* throws an exception.
* If you are not sure, use hasAssociation() before calling this method.
*
* @param string $name The alias used for the association.
* @return \Cake\ORM\Association The association.
* @throws \InvalidArgumentException
*/
public function getAssociation($name)
{
$association = $this->findAssociation($name);
if (!$association) {
throw new InvalidArgumentException('Association does not exist: ' . $name);
}

return $association;
}

/**
* Checks whether a specific association exists on this Table instance.
*
* The name argument also supports dot syntax to access deeper associations.
*
* ```
* $hasUsers = $this->hasAssociation('Articles.Comments.Users');
* ```
*
* @param string $name The alias used for the association.
* @return bool
*/
public function hasAssociation($name)
{
return $this->findAssociation($name) !== null;
}

/**
* Returns an association object configured for the specified alias if any.
*
* The name argument also supports dot syntax to access deeper associations.
*
* ```
* $users = $this->getAssociation('Articles.Comments.Users');
* ```
*
* @param string $name The alias used for the association.
* @return \Cake\ORM\Association|null Either the association or null.
*/
protected function findAssociation($name)
{
if (strpos($name, '.') === false) {
return $this->_associations->get($name);
Expand Down

0 comments on commit f7b3e0b

Please sign in to comment.