Skip to content

Instantly share code, notes, and snippets.

@Glideh
Last active July 7, 2016 09:45
Show Gist options
  • Save Glideh/0d4f09bede787190de88c67d3e370323 to your computer and use it in GitHub Desktop.
Save Glideh/0d4f09bede787190de88c67d3e370323 to your computer and use it in GitHub Desktop.
Generates an array of key => alias pairs joins from dotted path ready for a Doctrine QueryBuilder
<?php
/**
* @param string|array $dottedParts
* @param string $parent
* @return array
*/
public function getJoinsFromDottedPath($dottedParts, $parent = 'entity')
{
if (!is_array($dottedParts)) {
// Assuming the $dottedParts is a string
if (!strstr($dottedParts, '.')) {
// Exiting if this string does not contain any dot
return array();
}
// Converting into array
$dottedParts = explode('.', $dottedParts);
}
$joins = array();
// Adding the current join
$joins[$parent.'.'.$dottedParts[0]] = $dottedParts[0];
if (count($dottedParts) > 2) {
// There are children
$parent = array_shift($dottedParts);
$children = $this->getJoinsFromDottedPath($dottedParts, $parent);
// They are part of the family
$joins = array_merge($joins, $children);
}
return $joins;
}
<?php
function testGetJoinsFromDottedPath()
{
$joins = $this->admin->getJoinsFromDottedPath('site.customer');
$this->assertCount(1, $joins);
$this->assertEquals('entity.site', array_keys($joins)[0]);
$this->assertEquals('site', array_values($joins)[0]);
$joins = $this->admin->getJoinsFromDottedPath('site.customer.address.city');
$this->assertCount(3, $joins);
$this->assertEquals('entity.site', array_keys($joins)[0]);
$this->assertEquals('site', array_values($joins)[0]);
$this->assertEquals('site.customer', array_keys($joins)[1]);
$this->assertEquals('customer', array_values($joins)[1]);
$this->assertEquals('customer.address', array_keys($joins)[2]);
$this->assertEquals('address', array_values($joins)[2]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment