Development

/branches/1.1/lib/generator/sfCrudGenerator.class.php

You must first sign up to be able to contribute.

root/branches/1.1/lib/generator/sfCrudGenerator.class.php

Revision 9123, 12.5 kB (checked in by Carl.Vondrick, 6 years ago)

1.1: fixed @param in phpdoc to fit specs in generator (refs #2991)

  • Property svn:mime-type set to text/x-php
  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
Line 
1 <?php
2
3 /*
4  * This file is part of the symfony package.
5  * (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
6  *
7  * For the full copyright and license information, please view the LICENSE
8  * file that was distributed with this source code.
9  */
10
11 /**
12  * CRUD generator.
13  *
14  * This class generates a basic CRUD module.
15  *
16  * @package    symfony
17  * @subpackage generator
18  * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
19  * @version    SVN: $Id$
20  */
21 abstract class sfCrudGenerator extends sfGenerator
22 {
23   protected
24     $singularName  = '',
25     $pluralName    = '',
26     $peerClassName = '',
27     $map           = null,
28     $tableMap      = null,
29     $primaryKey    = array(),
30     $className     = '',
31     $params        = array();
32
33   /**
34    * Generates classes and templates in cache.
35    *
36    * @param array $params The parameters
37    *
38    * @return string The data to put in configuration cache
39    */
40   public function generate($params = array())
41   {
42     $this->params = $params;
43
44     $required_parameters = array('model_class', 'moduleName');
45     foreach ($required_parameters as $entry)
46     {
47       if (!isset($this->params[$entry]))
48       {
49         throw new sfParseException(sprintf('You must specify a "%s".', $entry));
50       }
51     }
52
53     $modelClass = $this->params['model_class'];
54
55     if (!class_exists($modelClass))
56     {
57       throw new sfInitializationException(sprintf('Unable to scaffold nonexistent model "%s".', $modelClass));
58     }
59
60     $this->setScaffoldingClassName($modelClass);
61
62     // generated module name
63     $this->setGeneratedModuleName('auto'.ucfirst($this->params['moduleName']));
64     $this->setModuleName($this->params['moduleName']);
65
66     // get some model metadata
67     $this->loadMapBuilderClasses();
68
69     // load all primary keys
70     $this->loadPrimaryKeys();
71
72     // theme exists?
73     $theme = isset($this->params['theme']) ? $this->params['theme'] : 'default';
74     $themeDir = $this->generatorManager->getConfiguration()->getGeneratorTemplate($this->getGeneratorClass(), $theme, '');
75     if (!is_dir($themeDir))
76     {
77       throw new sfConfigurationException(sprintf('The theme "%s" does not exist.', $theme));
78     }
79
80     $this->setTheme($theme);
81     $files = sfFinder::type('file')->relative()->in($themeDir);
82
83     $this->generatePhpFiles($this->generatedModuleName, $files);
84
85     // require generated action class
86     $data = "require_once(sfConfig::get('sf_module_cache_dir').'/".$this->generatedModuleName."/actions/actions.class.php');\n";
87
88     return $data;
89   }
90
91   /**
92    * Returns PHP code for primary keys parameters.
93    *
94    * @param integer $indent The indentation value
95    * @param string  $callee The function to call
96    *
97    * @return string The PHP code
98    */
99   public function getRetrieveByPkParamsForAction($indent, $callee = '$this->getRequestParameter')
100   {
101     $params = array();
102     foreach ($this->getPrimaryKey() as $pk)
103     {
104       $params[] = "$callee('".sfInflector::underscore($pk->getPhpName())."')";
105     }
106
107     return implode(",\n".str_repeat(' ', max(0, $indent - strlen($this->singularName.$this->className))), $params);
108   }
109
110   /**
111    * Returns PHP code for primary keys parameters.
112    *
113    * @param integer $indent The indentation value
114    * @param string  $prefix No effect at this time
115    *
116    * @return string The PHP code
117    */
118   public function getRetrieveByPkParamsForEdit($indent, $prefix)
119   {
120     $params = array();
121     foreach ($this->getPrimaryKey() as $pk)
122     {
123       $name = sfInflector::underscore($pk->getPhpName());
124 //      $params[] = sprintf("\$request->getParameter('%s', \$request->getParameter('%s'))", sprintf('%s[%s]', $prefix, $name), $name);
125       $params[] = sprintf("\$request->getParameter('%s')", $name);
126     }
127
128     return implode(",\n".str_repeat(' ', max(0, $indent - strlen($this->singularName.$this->className))), $params);
129   }
130
131   /**
132    * Returns PHP code for getOrCreate() parameters.
133    *
134    * @return string The PHP code
135    */
136   public function getMethodParamsForGetOrCreate()
137   {
138     $method_params = array();
139     foreach ($this->getPrimaryKey() as $pk)
140     {
141       $fieldName       = sfInflector::underscore($pk->getPhpName());
142       $method_params[] = "\$$fieldName = '$fieldName'";
143     }
144
145     return implode(', ', $method_params);
146   }
147
148   /**
149    * Returns PHP code for getOrCreate() promary keys condition.
150    *
151    * @param boolean $fieldNameAsArgument true if we pass the field name as an argument, false otherwise
152    *
153    * @return string The PHP code
154    */
155   public function getTestPksForGetOrCreate($fieldNameAsArgument = true)
156   {
157     $test_pks = array();
158     foreach ($this->getPrimaryKey() as $pk)
159     {
160       $fieldName  = sfInflector::underscore($pk->getPhpName());
161       // 2 checks needed here, as '0' is a vaild PK.
162       $test_pks[] = sprintf("\$this->getRequestParameter(%s) === ''", $fieldNameAsArgument ? "\$$fieldName" : "'".$fieldName."'");
163       $test_pks[] = sprintf("\$this->getRequestParameter(%s) === null", $fieldNameAsArgument ? "\$$fieldName" : "'".$fieldName."'");
164     }
165
166     return implode("\n     || ", $test_pks);
167   }
168
169   /**
170    * Returns PHP code for primary keys parameters used in getOrCreate() method.
171    *
172    * @return string The PHP code
173    */
174   public function getRetrieveByPkParamsForGetOrCreate()
175   {
176     $retrieve_params = array();
177     foreach ($this->getPrimaryKey() as $pk)
178     {
179       $fieldName         = sfInflector::underscore($pk->getPhpName());
180       $retrieve_params[] = "\$this->getRequestParameter(\$$fieldName)";
181     }
182
183     return implode(",\n".str_repeat(' ', max(0, 45 - strlen($this->singularName.$this->className))), $retrieve_params);
184   }
185
186   /**
187    * Gets the table map for the current model class.
188    *
189    * @return TableMap A TableMap instance
190    */
191   public function getTableMap()
192   {
193     return $this->tableMap;
194   }
195
196   /**
197    * Sets the class name to use for scaffolding
198    *
199    * @param string $className class name
200    */
201   protected function setScaffoldingClassName($className)
202   {
203     $this->singularName  = sfInflector::underscore($className);
204     $this->pluralName    = $this->singularName.'s';
205     $this->className     = $className;
206     $this->peerClassName = $className.'Peer';
207   }
208
209   /**
210    * Gets the singular name for current scaffolding class.
211    *
212    * @return string
213    */
214   public function getSingularName()
215   {
216     return $this->singularName;
217   }
218
219   /**
220    * Gets the plural name for current scaffolding class.
221    *
222    * @return string
223    */
224   public function getPluralName()
225   {
226     return $this->pluralName;
227   }
228
229   /**
230    * Gets the class name for current scaffolding class.
231    *
232    * @return string
233    */
234   public function getClassName()
235   {
236     return $this->className;
237   }
238
239   /**
240    * Gets the Peer class name.
241    *
242    * @return string
243    */
244   public function getPeerClassName()
245   {
246     return $this->peerClassName;
247   }
248
249   /**
250    * Gets the primary key name.
251    *
252    * @return string
253    */
254   public function getPrimaryKey()
255   {
256     return $this->primaryKey;
257   }
258
259   /**
260    * Gets the Map object.
261    *
262    * @return object
263    */
264   public function getMap()
265   {
266     return $this->map;
267   }
268
269   /**
270    * Returns PHP code to add to a URL for primary keys.
271    *
272    * @param string $prefix The prefix value
273    *
274    * @return string PHP code
275    */
276   public function getPrimaryKeyUrlParams($prefix = '')
277   {
278     $params = array();
279     foreach ($this->getPrimaryKey() as $pk)
280     {
281       $phpName   = $pk->getPhpName();
282       $fieldName = sfInflector::underscore($phpName);
283       $params[]  = "$fieldName='.".$this->getColumnGetter($pk, true, $prefix);
284     }
285
286     return implode(".'&", $params);
287   }
288
289   /**
290    * Gets PHP code for primary key condition.
291    *
292    * @param string $prefix The prefix value
293    *
294    * @return string PHP code
295    */
296   public function getPrimaryKeyIsSet($prefix = '')
297   {
298     $params = array();
299     foreach ($this->getPrimaryKey() as $pk)
300     {
301       $params[] = $this->getColumnGetter($pk, true, $prefix);
302     }
303
304     return implode(' && ', $params);
305   }
306
307   /**
308    * Gets object tag parameters.
309    *
310    * @param array $params         An array of parameters
311    * @param array $default_params An array of default parameters
312    *
313    * @return string PHP code
314    */
315   protected function getObjectTagParams($params, $default_params = array())
316   {
317     return var_export(array_merge($default_params, $params), true);
318   }
319
320   /**
321    * Returns HTML code for a column in list mode.
322    *
323    * @param string  $column   The column name
324    * @param array   $params   The parameters
325    *
326    * @return string HTML code
327    */
328   public function getColumnListTag($column, $params = array())
329   {
330     $type = $column->getCreoleType();
331     
332     $columnGetter = $this->getColumnGetter($column, true);
333
334     if ($type == CreoleTypes::TIMESTAMP)
335     {
336       return "format_date($columnGetter, 'f')";
337     }
338     elseif ($type == CreoleTypes::DATE)
339     {
340       return "format_date($columnGetter, 'D')";
341     }
342     else
343     {
344       return "$columnGetter";
345     }
346   }
347
348   /**
349    * Returns HTML code for a column in edit mode.
350    *
351    * @param string  $column   The column name
352    * @param array   $params   The parameters
353    *
354    * @return string HTML code
355    */
356   public function getCrudColumnEditTag($column, $params = array())
357   {
358     $type = $column->getCreoleType();
359
360     if ($column->isForeignKey())
361     {
362       if (!$column->isNotNull() && !isset($params['include_blank']))
363       {
364         $params['include_blank'] = true;
365       }
366
367       return $this->getPHPObjectHelper('select_tag', $column, $params, array('related_class' => $this->getRelatedClassName($column)));
368     }
369     else if ($type == CreoleTypes::DATE)
370     {
371       // rich=false not yet implemented
372       return $this->getPHPObjectHelper('input_date_tag', $column, $params, array('rich' => true));
373     }
374     else if ($type == CreoleTypes::TIMESTAMP)
375     {
376       // rich=false not yet implemented
377       return $this->getPHPObjectHelper('input_date_tag', $column, $params, array('rich' => true, 'withtime' => true));
378     }
379     else if ($type == CreoleTypes::BOOLEAN)
380     {
381       return $this->getPHPObjectHelper('checkbox_tag', $column, $params);
382     }
383     else if ($type == CreoleTypes::CHAR || $type == CreoleTypes::VARCHAR)
384     {
385       $size = ($column->getSize() > 20 ? ($column->getSize() < 80 ? $column->getSize() : 80) : 20);
386       return $this->getPHPObjectHelper('input_tag', $column, $params, array('size' => $size));
387     }
388     else if ($type == CreoleTypes::INTEGER || $type == CreoleTypes::TINYINT || $type == CreoleTypes::SMALLINT || $type == CreoleTypes::BIGINT)
389     {
390       return $this->getPHPObjectHelper('input_tag', $column, $params, array('size' => 7));
391     }
392     else if ($type == CreoleTypes::FLOAT || $type == CreoleTypes::DOUBLE || $type == CreoleTypes::DECIMAL || $type == CreoleTypes::NUMERIC || $type == CreoleTypes::REAL)
393     {
394       return $this->getPHPObjectHelper('input_tag', $column, $params, array('size' => 7));
395     }
396     else if ($type == CreoleTypes::TEXT || $type == CreoleTypes::LONGVARCHAR)
397     {
398       return $this->getPHPObjectHelper('textarea_tag', $column, $params, array('size' => '30x3'));
399     }
400     else
401     {
402       return $this->getPHPObjectHelper('input_tag', $column, $params, array('disabled' => true));
403     }
404   }
405
406   /**
407    * Loads primary keys.
408    *
409    * This method is ORM dependant.
410    *
411    * @throws sfException
412    */
413   abstract protected function loadPrimaryKeys();
414
415   /**
416    * Loads map builder classes.
417    *
418    * This method is ORM dependant.
419    *
420    * @throws sfException
421    */
422   abstract protected function loadMapBuilderClasses();
423
424   /**
425    * Generates a PHP call to an object helper.
426    *
427    * This method is ORM dependant.
428    *
429    * @param string $helperName    The helper name
430    * @param string $column        The column name
431    * @param array  $params        An array of parameters
432    * @param array  $localParams   An array of local parameters
433    *
434    * @return string PHP code
435    */
436   abstract function getPHPObjectHelper($helperName, $column, $params, $localParams = array());
437
438   /**
439    * Returns the getter either non-developped: 'getFoo' or developped: '$class->getFoo()'.
440    *
441    * This method is ORM dependant.
442    *
443    * @param string  $column     The column name
444    * @param boolean $developed  true if you want developped method names, false otherwise
445    * @param string  $prefix     The prefix value
446    *
447    * @return string PHP code
448    */
449   abstract function getColumnGetter($column, $developed = false , $prefix = '');
450
451   /*
452    * Gets the PHP name of the related class name.
453    *
454    * Used for foreign keys only; this method should be removed when we use sfAdminColumn instead.
455    *
456    * This method is ORM dependant.
457    *
458    * @param string $column The column name
459    *
460    * @return string The PHP name of the related class name
461    */
462   abstract function getRelatedClassName($column);
463 }
464
Note: See TracBrowser for help on using the browser.