public function testParseName() { $info = new phNameInfo('ids[1]'); $this->assertTrue($info->isValid(), 'ids[1] is valid'); $this->assertTrue($info->isArray(), 'ids[1] has been identified as an array'); $this->assertEquals($info->getArrayKeyString(), '[1]', 'Array parts is [1]'); $this->assertEquals($info->getName(), 'ids', 'Name is ids'); $info = new phNameInfo('ids[]'); $this->assertTrue($info->isValid(), 'ids[] is valid'); $this->assertTrue($info->isArray(), 'ids[] has been identified as an array'); $this->assertEquals($info->getArrayKeyString(), '[]', 'Array parts is []'); $this->assertEquals($info->getName(), 'ids', 'Name is ids'); $info = new phNameInfo('ids[1][moo]'); $this->assertTrue($info->isValid(), 'ids[1][moo] is valid'); $this->assertTrue($info->isArray(), 'ids[1][moo] has been identified as an array'); $this->assertEquals($info->getArrayKeyString(), '[1][moo]', 'Array parts is [1][moo]'); $this->assertEquals($info->getName(), 'ids', 'Name is ids'); }
/** * Gets a rewritten name that will be unique and relate to the form * that the element belongs to * * @param string $name */ public function name($name) { /* * valid names can only start with alpha characters * following the first letter can be alpha, numeric or underscores (but need'nt be present, a valid name can be 1 character) * the second parahenthises check, if an array is present that it is valid */ $nameInfo = new phNameInfo($name); if (!$nameInfo->isValid()) { throw new phFormException("'{$name}' is not valid, names must be a-z0-9 or '_' only and contain no spaces and must not start with an '_' (underscore) or number"); } $nameOnly = $nameInfo->getName(); /* * check if someone is trying to specify 2 names where one is an array and the other isn't * e.g. name="address" and name="address[zip]" */ if (array_key_exists($nameOnly, $this->_types) && $nameInfo->isArray() != $this->_types[$nameOnly]) { throw new phFormException("Invalid name {$name}, trying to mix array's and normal types"); } $key = array_search($name, $this->_names); if ($key !== false) { return $key; } else { $this->_types[$nameOnly] = $nameInfo->isArray(); $newName = sprintf($this->_form->getNameFormat(), $nameOnly); if ($nameInfo->isArray()) { $newName .= $nameInfo->getArrayKeyString(); } $this->_names[$newName] = $name; return $newName; } }