GiixCrudCode.php 14.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371
<?php

/**
 * GiixCrudCode class file.
 *
 * @author Rodrigo Coelho <rodrigo@giix.org>
 * @link http://giix.org/
 * @copyright Copyright &copy; 2010-2011 Rodrigo Coelho
 * @license http://giix.org/license/ New BSD License
 */
Yii::import('system.gii.generators.crud.CrudCode');
Yii::import('ext.giix-core.helpers.*');

/**
 * GiixCrudCode is the model for giix crud generator.
 *
 * @author Rodrigo Coelho <rodrigo@giix.org>
 */
class GiixCrudCode extends CrudCode {

	/**
	 * @var string The type of authentication.
	 */
	public $authtype = 'auth_none';
	/**
	 * @var int Specifies if ajax validation is enabled. 0 represents false, 1 represents true.
	 */
	public $enable_ajax_validation = 0;
	/**
	 * @var string The controller base class name.
	 */
	public $baseControllerClass = 'GxController';

	/**
	 * Adds the new model attributes (class properties) to the rules.
	 * #MethodTracker
	 * This method overrides {@link CrudCode::rules}, from version 1.1.7 (r3135). Changes:
	 * <ul>
	 * <li>Adds the rules for the new attributes in the code generation form: authtype; enable_ajax_validation.</li>
	 * </ul>
	 */
	public function rules() {
		return array_merge(parent::rules(), array(
			array('authtype, enable_ajax_validation', 'required'),
		));
	}

	/**
	 * Sets the labels for the new model attributes (class properties).
	 * #MethodTracker
	 * This method overrides {@link CrudCode::attributeLabels}, from version 1.1.7 (r3135). Changes:
	 * <ul>
	 * <li>Adds the labels for the new attributes in the code generation form: authtype; enable_ajax_validation.</li>
	 * </ul>
	 */
	public function attributeLabels() {
		return array_merge(parent::attributeLabels(), array(
			'authtype' => 'Authentication type',
			'enable_ajax_validation' => 'Enable ajax validation',
		));
	}

	/**
	 * Generates and returns the view source code line
	 * to create the appropriate active input field based on
	 * the model attribute field type on the database.
	 * #MethodTracker
	 * This method is based on {@link CrudCode::generateActiveField}, from version 1.1.7 (r3135). Changes:
	 * <ul>
	 * <li>All styling is removed.</li>
	 * </ul>
	 * @param string $modelClass The model class name.
	 * @param CDbColumnSchema $column The column.
	 * @return string The source code line for the active field.
	 */
	public function generateActiveField($modelClass, $column) {
		if ($column->isForeignKey) {
			$relation = $this->findRelation($modelClass, $column);
			$relatedModelClass = $relation[3];
			return "echo \$form->dropDownList(\$model, '{$column->name}', GxHtml::listDataEx({$relatedModelClass}::model()->findAllAttributes(null, true)))";
		}

		if (strtoupper($column->dbType) == 'TINYINT(1)'
				|| strtoupper($column->dbType) == 'BIT'
				|| strtoupper($column->dbType) == 'BOOL'
				|| strtoupper($column->dbType) == 'BOOLEAN') {
			return "echo \$form->checkBox(\$model, '{$column->name}')";
		} else if (strtoupper($column->dbType) == 'DATE') {
			return "\$form->widget('zii.widgets.jui.CJuiDatePicker', array(
			'model' => \$model,
			'attribute' => '{$column->name}',
			'value' => \$model->{$column->name},
			'options' => array(
				'showButtonPanel' => true,
				'changeYear' => true,
				'dateFormat' => 'yy-mm-dd',
				),
			));\n";
		} else if (stripos($column->dbType, 'text') !== false) { // Start of CrudCode::generateActiveField code.
			return "echo \$form->textArea(\$model, '{$column->name}')";
		} else {
			$passwordI18n = Yii::t('app', 'password');
			$passwordI18n = (isset($passwordI18n) && $passwordI18n !== '') ? '|' . $passwordI18n : '';
			$pattern = '/^(password|pass|passwd|passcode' . $passwordI18n . ')$/i';
			if (preg_match($pattern, $column->name))
				$inputField = 'passwordField';
			else
				$inputField='textField';

			if ($column->type !== 'string' || $column->size === null)
				return "echo \$form->{$inputField}(\$model, '{$column->name}')";
			else
				return "echo \$form->{$inputField}(\$model, '{$column->name}', array('maxlength' => {$column->size}))";
		} // End of CrudCode::generateActiveField code.
	}

	/**
	 * Generates and returns the view source code line
	 * to create the appropriate active input field based on
	 * the model relation.
	 * @param string $modelClass The model class name.
	 * @param array $relation The relation details in the same format
	 * used by {@link getRelations}.
	 * @return string The source code line for the relation field.
	 * @throws InvalidArgumentException If the relation type is not HAS_ONE, HAS_MANY or MANY_MANY.
	 */
	public function generateActiveRelationField($modelClass, $relation) {
		$relationName = $relation[0];
		$relationType = $relation[1];
		$relationField = $relation[2]; // The FK.
		$relationModel = $relation[3];
		// The relation type must be HAS_ONE, HAS_MANY or MANY_MANY.
		// Other types (BELONGS_TO) should be generated by generateActiveField.
		if ($relationType != GxActiveRecord::HAS_ONE && $relationType != GxActiveRecord::HAS_MANY && $relationType != GxActiveRecord::MANY_MANY)
			throw new InvalidArgumentException(Yii::t('giix', 'The argument "relationName" must have a relation type of HAS_ONE, HAS_MANY or MANY_MANY.'));

		// Generate the field according to the relation type.
		switch ($relationType) {
			case GxActiveRecord::HAS_ONE:
				return "echo \$form->dropDownList(\$model, '{$relationName}', GxHtml::listDataEx({$relationModel}::model()->findAllAttributes(null, true)))";
				break;
			case GxActiveRecord::HAS_MANY:
			case GxActiveRecord::MANY_MANY:
				return "echo \$form->checkBoxList(\$model, '{$relationName}', GxHtml::encodeEx(GxHtml::listDataEx({$relationModel}::model()->findAllAttributes(null, true)), false, true))";
				break;
		}
	}

	public function generateInputField($modelClass, $column) {
		return 'echo ' . parent::generateInputField($modelClass, $column);
	}

	/**
	 * Generates and returns the view source code line
	 * to create the appropriate attribute configuration for a CDetailView.
	 * @param string $modelClass The model class name.
	 * @param CDbColumnSchema $column The column.
	 * @return string The source code line for the attribute.
	 */
	public function generateDetailViewAttribute($modelClass, $column) {
		if (!$column->isForeignKey) {
			if (strtoupper($column->dbType) == 'TINYINT(1)'
					|| strtoupper($column->dbType) == 'BIT'
					|| strtoupper($column->dbType) == 'BOOL'
					|| strtoupper($column->dbType) == 'BOOLEAN') {
				return "'{$column->name}:boolean'";
			} else
				return "'{$column->name}'";
		} else {
			// Find the relation name for this column.
			$relation = $this->findRelation($modelClass, $column);
			$relationName = $relation[0];
			$relatedModelClass = $relation[3];
			$relatedControllerName = strtolower($relatedModelClass[0]) . substr($relatedModelClass, 1);

			return "array(
			'name' => '{$relationName}',
			'type' => 'raw',
			'value' => \$model->{$relationName} !== null ? GxHtml::link(GxHtml::encode(GxHtml::valueEx(\$model->{$relationName})), array('{$relatedControllerName}/view', 'id' => GxActiveRecord::extractPkValue(\$model->{$relationName}, true))) : null,
			)";
		}
	}

	/**
	 * Generates and returns the view source code line
	 * to create the CGridView column definition.
	 * @param string $modelClass The model class name.
	 * @param CDbColumnSchema $column The column.
	 * @return string The source code line for the column definition.
	 */
	public function generateGridViewColumn($modelClass, $column) {
		if (!$column->isForeignKey) {
			// Boolean or bit.
			if (strtoupper($column->dbType) == 'TINYINT(1)'
					|| strtoupper($column->dbType) == 'BIT'
					|| strtoupper($column->dbType) == 'BOOL'
					|| strtoupper($column->dbType) == 'BOOLEAN') {
				return "array(
					'name' => '{$column->name}',
					'value' => '(\$data->{$column->name} === 0) ? Yii::t(\\'app\\', \\'No\\') : Yii::t(\\'app\\', \\'Yes\\')',
					'filter' => array('0' => Yii::t('app', 'No'), '1' => Yii::t('app', 'Yes')),
					)";
			} else // Common column.
				return "'{$column->name}'";
		} else { // FK.
			// Find the related model for this column.
			$relation = $this->findRelation($modelClass, $column);
			$relationName = $relation[0];
			$relatedModelClass = $relation[3];
			return "array(
				'name'=>'{$column->name}',
				'value'=>'GxHtml::valueEx(\$data->{$relationName})',
				'filter'=>GxHtml::listDataEx({$relatedModelClass}::model()->findAllAttributes(null, true)),
				)";
		}
	}

	/**
	 * Generates and returns the view source code line
	 * to create the advanced search.
	 * @param string $modelClass The model class name.
	 * @param CDbColumnSchema $column The column.
	 * @return string The source code line for the column definition.
	 */
	public function generateSearchField($modelClass, $column) {
		if (!$column->isForeignKey) {
			// Boolean or bit.
			if (strtoupper($column->dbType) == 'TINYINT(1)'
					|| strtoupper($column->dbType) == 'BIT'
					|| strtoupper($column->dbType) == 'BOOL'
					|| strtoupper($column->dbType) == 'BOOLEAN')
				return "echo \$form->dropDownList(\$model, '{$column->name}', array('0' => Yii::t('app', 'No'), '1' => Yii::t('app', 'Yes')), array('prompt' => Yii::t('app', 'All')))";
			else // Common column. generateActiveField method will add 'echo' when necessary.
				return $this->generateActiveField($this->modelClass, $column);
		} else { // FK.
			// Find the related model for this column.
			$relation = $this->findRelation($modelClass, $column);
			$relatedModelClass = $relation[3];
			return "echo \$form->dropDownList(\$model, '{$column->name}', GxHtml::listDataEx({$relatedModelClass}::model()->findAllAttributes(null, true)), array('prompt' => Yii::t('app', 'All')))";
		}
	}

	/**
	 * Generates and returns the array (as a PHP source code string)
	 * to collect the MANY_MANY related data from the POST.
	 * @param string $modelClass The model class name.
	 * @return string The source code to collect the MANY_MANY related
	 * data from the POST.
	 */
	public function generateGetPostRelatedData($modelClass, $indent = 1) {
		$result = array();
		$relations = $this->getRelations($modelClass);
		foreach ($relations as $relationData) {
			$relationName = $relationData[0];
			$relationType = $relationData[1];
			if ($relationType == GxActiveRecord::MANY_MANY)
				$result[$relationData[0]] = "php:\$_POST['{$modelClass}']['{$relationName}'] === '' ? null : \$_POST['{$modelClass}']['{$relationName}']";
		}
		return GxCoreHelper::ArrayToPhpSource($result, $indent);
	}

	/**
	 * Checks whether this AR has a MANY_MANY relation.
	 * @param string $modelClass The model class name.
	 * @return boolean Whether this AR has a MANY_MANY relation.
	 */
	public function hasManyManyRelation($modelClass) {
		$relations = $this->getRelations($modelClass);
		foreach ($relations as $relationData) {
			if ($relationData[1] == GxActiveRecord::MANY_MANY) {
				return true;
			}
		}
		return false;
	}

	/**
	 * Finds the relation of the specified column.
	 * Note: There's a similar method in the class GxActiveRecord.
	 * @param string $modelClass The model class name.
	 * @param CDbColumnSchema $column The column.
	 * @return array The relation. The array will have 3 values:
	 * 0: the relation name,
	 * 1: the relation type (will always be GxActiveRecord::BELONGS_TO),
	 * 2: the foreign key (will always be the specified column),
	 * 3: the related active record class name.
	 * Or null if no matching relation was found.
	 */
	public function findRelation($modelClass, $column) {
		if (!$column->isForeignKey)
			return null;
		$relations = GxActiveRecord::model($modelClass)->relations();
		// Find the relation for this attribute.
		foreach ($relations as $relationName => $relation) {
			// For attributes on this model, relation must be BELONGS_TO.
			if ($relation[0] == GxActiveRecord::BELONGS_TO && $relation[2] == $column->name) {
				return array(
					$relationName, // the relation name
					$relation[0], // the relation type
					$relation[2], // the foreign key
					$relation[1] // the related active record class name
				);
			}
		}
		// None found.
		return null;
	}

	/**
	 * Returns all the relations of the specified model.
	 * @param string $modelClass The model class name.
	 * @return array The relations. Each array item is
	 * a relation as an array, having 3 items:
	 * 0: the relation name,
	 * 1: the relation type,
	 * 2: the foreign key,
	 * 3: the related active record class name.
	 * Or an empty array if no relations were found.
	 */
	public function getRelations($modelClass) {
		$relations = GxActiveRecord::model($modelClass)->relations();
		$result = array();
		foreach ($relations as $relationName => $relation) {
			$result[] = array(
				$relationName, // the relation name
				$relation[0], // the relation type
				$relation[2], // the foreign key
				$relation[1] // the related active record class name
			);
		}
		return $result;
	}

	/**
	 * Returns the message to be displayed when the newly generated code is saved successfully.
	 * #MethodTracker
	 * This method overrides {@link CrudCode::successMessage}, from version 1.1.7 (r3135). Changes:
	 * <ul>
	 * <li>Custom giix success message.</li>
	 * </ul>
	 * @return string The message to be displayed when the newly generated code is saved successfully.
	 */
	public function successMessage() {
		return <<<EOM
<p><strong>Sweet!</strong></p>
<ul style="list-style-type: none; padding-left: 0;">
	<li><img src="http://giix.org/icons/love.png"> Show how you love giix on <a href="http://www.yiiframework.com/forum/index.php?/topic/13154-giix-%E2%80%94-gii-extended/">the forum</a> and on its <a href="http://www.yiiframework.com/extension/giix">extension page</a></li>
	<li><img src="http://giix.org/icons/vote.png"> Upvote <a href="http://www.yiiframework.com/extension/giix">giix</a></li>
	<li><img src="http://giix.org/icons/powered.png"> Show everybody that you are using giix in <a href="http://www.yiiframework.com/forum/index.php?/topic/19226-powered-by-giix/">Powered by giix</a></li>
	<li><img src="http://giix.org/icons/donate.png"> <a href="http://giix.org/">Donate</a></li>
</ul>
<p style="margin: 2px 0; position: relative; text-align: right; top: -15px; color: #668866;">icons by <a href="http://www.famfamfam.com/lab/icons/silk/" style="color: #668866;">famfamfam.com</a></p>
EOM;
	}
	
	/**
	 * #MethodTracker
	 * This method overrides {@link CCodeModel::confirmed}, from version 1.1.13. Changes:
	 * <ul>
	 * <li>Support for {@link http://www.yiiframework.com/extension/giic/ giic} out-of-the-box.</li>
	 * </ul>
	 */
	public function confirmed($file) {
		if (defined('GIIC_ALL_CONFIRMED') && (GIIC_ALL_CONFIRMED === true)) {
			return true;
		} else {
			return parent::confirmed($file);
		}
	}

}