/** * @param MethodContainer $methods * @param StructAttributeModel $attribute * @return Struct */ protected function addStructMethodAddTo(MethodContainer $methods, StructAttributeModel $attribute) { if ($attribute->isArray()) { $method = new PhpMethod(sprintf('addTo%s', ucfirst($attribute->getCleanName())), array(new PhpFunctionParameter('item', PhpFunctionParameter::NO_VALUE, $this->getStructMethodParameterType($attribute, false)))); $this->addStructMethodAddToBody($method, $attribute); $methods->add($method); } return $this; }
/** * @param StructAttributeModel $attribute * @param string $returnArrayType * @return bool */ protected function useBrackets(StructAttributeModel $attribute, $returnArrayType = true) { return $returnArrayType && $attribute->isArray(); }
/** * @param PhpMethod $method * @param StructAttributeModel $attribute * @return Struct */ protected function addStructMethodSetBodyForArray(PhpMethod $method, StructAttributeModel $attribute) { if ($attribute->isArray()) { $model = $this->getRestrictionFromStructAttribute($attribute); $parameterName = lcfirst($attribute->getCleanName()); if ($model instanceof StructModel) { $method->addChild('$invalidValues = array();')->addChild(sprintf('foreach($%s as $item) {', $parameterName))->addChild($method->getIndentedString(sprintf('if (!%s::%s($item)) {', $model->getPackagedName(true), StructEnum::METHOD_VALUE_IS_VALID), 1))->addChild($method->getIndentedString('$invalidValues[] = var_export($item);', 2))->addChild($method->getIndentedString('}', 1))->addChild('}')->addChild('if (!empty($invalidValues)) {')->addChild($method->getIndentedString(sprintf('throw new \\InvalidArgumentException(sprintf(\'Value(s) "%%s" is/are invalid, please use one of: %%s\', implode(\', \', $invalidValues), implode(\', \', %s::%s())), __LINE__);', $model->getPackagedName(true), StructEnum::METHOD_GET_VALID_VALUES), 1))->addChild('}'); } else { $method->addChild(sprintf('foreach($%s as $item) {', $parameterName))->addChild($method->getIndentedString(sprintf('if (!%s) {', $this->getStructMethodSetBodyForArrayItemSanityCheck($attribute)), 1))->addChild($method->getIndentedString(sprintf('throw new \\InvalidArgumentException(sprintf(\'The %s property can only contain items of %s, "%%s" given\', is_object($item) ? get_class($item) : gettype($item)), __LINE__);', $attribute->getCleanName(), $this->getStructAttributeType($attribute, true)), 2))->addChild($method->getIndentedString('}', 1))->addChild('}'); } } return $this; }