Files
grzanieplus.pl/plugins/stAdminGeneratorPlugin/lib/generator/stAdminGenerator.class.php
2025-03-12 17:06:23 +01:00

2232 lines
77 KiB
PHP

<?php
/**
* SOTESHOP/stAdminGeneratorPlugin
*
* Ten plik należy do aplikacji stAdminGeneratorPlugin opartej na licencji (Open License SOTE) Otwarta Licencja SOTE.
* Nie zmieniaj tego pliku, jeśli chcesz korzystać z automatycznych aktualizacji oprogramowania.
* Jeśli chcesz wprowadzać swoje modyfikacje do programu, zapoznaj się z dokumentacją, jak zmieniać
* oprogramowanie bez zmiany kodu bazowego http://www.sote.pl/modifications
*
* @package stAdminGeneratorPlugin
* @subpackage libs
* @copyright SOTE (www.sote.pl)
* @license http://www.sote.pl/license/open (Open License SOTE) Otwarta Licencja SOTE
* @version $Id: stAdminGenerator.class.php 17572 2012-03-29 11:29:08Z marcin $
* @author Marcin Butlak <marcin.butlak@sote.pl>
*/
/**
* Sote Admin generator.
* This class extends sfPropelAdminGenerator.
*
* @package stAdminGeneratorPlugin
* @subpackage generator
* @author Marcin Butlak <marcin.butlak@sote.pl>
*/
class stAdminGenerator extends sfPropelAdminGenerator
{
/**
* Instancja obiektu event dispatcher
* @var sfEventDispatcher
*/
protected $dispatcher = null;
/**
* Nazwa własnej akcji
* @var string
*/
protected $customAction = '';
/**
* Nazwa typu
* @var string
*/
protected $customType = '';
protected $ignoreEscapeTagParams = array();
protected $forwardParameters = array();
protected $appTitle = null;
public static function getModuleNamespace($module, $action, $scope)
{
return 'soteshop/stAdminGenerator/' . $module . '/' . $action . '/' . $scope;
}
public function getValueForParameter($param, $default = null)
{
return $this->getValueFromKey($param, $default);
}
public function setValueForParameter($param, $value = null)
{
$ref = &$this->params;
$parts = explode('.', $param);
foreach ($parts as $part)
{
if (!isset($ref[$part]))
{
$ref[$part] = array();
}
$ref = &$ref[$part];
}
$ref = $value;
}
public function getPrimaryKeyField($glue = '_', $prefix = '')
{
$params = array();
foreach ($this->getPrimaryKey() as $pk)
{
$params[] = $this->getColumnGetter($pk, true, $prefix);
}
return implode(".'$glue'.", $params);
}
public function getMethodParamsForPrimaryKey()
{
$method_params = array();
foreach ($this->getPrimaryKey() as $pk)
{
$fieldName = sfInflector::underscore($pk->getPhpName());
$method_params[] = "\$$fieldName";
}
return implode(', ', $method_params);
}
public function getRetrieveByPkParamsForAction($indent, $glue = ",\n")
{
$params = array();
foreach ($this->getPrimaryKey() as $pk)
{
$params[] = "\$this->getRequestParameter('" . sfInflector::underscore($pk->getPhpName()) . "')";
}
return implode($glue, $params);
}
public function insertParameterBefore($key, $param)
{
return $this->insertParameterHelper($key, $param, 'before');
}
public function insertParameterAfter($key, $param)
{
return $this->insertParameterHelper($key, $param, 'after');
}
public function insertParameterHelper($key, $param, $type = 'after')
{
$parts = explode('.', $key);
$last = array_pop($parts);
$matches = array();
$tmp = array();
if (preg_match('/([^\[]+)\[([^\]]*)\]/', $last, $matches))
{
$last_param = $matches[1];
$last_value = $matches[2];
$parts[] = $last_param;
$key = implode('.', $parts);
$values = $this->getValueForParameter($key);
foreach ($values as $v)
{
if ($type == 'after')
{
$tmp[] = $v;
}
if ($last_value == $v)
{
foreach ((array) $param as $p)
{
$tmp[] = $p;
}
}
if ($type == 'before')
{
$tmp[] = $v;
}
}
}
else
{
$key = implode('.', $parts);
$values = $this->getValueForParameter($key);
foreach ($values as $k1 => $v)
{
if ($type == 'after')
{
$tmp[$k1] = $v;
}
if ($k1 == $last)
{
foreach ((array) $param as $k2 => $p)
{
if (isset($values[$k2]))
{
throw new sfConfigurationException(sprintf('Cannot insert a duplicated parameter "%s" in "%s"', $k2, $param));
}
$tmp[$k2] = $p;
}
}
if ($type == 'before')
{
$tmp[$k1] = $v;
}
}
}
$this->setValueForParameter($key, $tmp);
}
/**
* Gets a parameter value.
*
* @param string The key name
* @param mixed The default value
* @return mixed The parameter value
*/
public function getParameterValue($key, $default = null, $add_prefix = true)
{
return parent::getParameterValue(($add_prefix ? $this->getCustomActionName('', '_') : '') . $key, $default);
}
public function getRecordListColSpan()
{
$object_actions = $this->getParameterValue('list.object_actions');
return count($this->getColumns('list.display')) + isset($object_actions['_edit']) + 3;
return $object_actions ? (count($this->getColumns('list.display')) + 2 + isset($object_actions['_edit']) + (bool) $this->getParameterValue('list.build_options.through_class')) : count($this->getColumns('list.display')) + 2 + (bool) $this->getParameterValue('list.build_options.through_class');
}
public function isObjectActionVisible()
{
return !empty($this->getParameterValue('list.object_actions'));
}
/**
* Ustawia globalny prefix dla metody getParameterValue
*
* @param string $prefix Nazwa akcji bez typu (format underscored)
*/
protected function setParameterValuePrefix($prefix)
{
$this->customAction = $prefix;
$this->changeModelClass(isset($this->params[$prefix . '_model_class']) ? $this->params[$prefix . '_model_class'] : $this->params['model_class']);
}
/**
* Zwraca nazwę akcji w formacie underscored
*
* @param string $prefix wartość doklejona przed nazwą akcji (tylko jeśli akcja istnieje)
* @param string $postfix wartość doklejona za nazwą akcji (tylko jeśli akcja istnieje)
* @param string $default wartość domyślna w przypadku braku akcji
* @return string
*/
protected function getCustomActionName($prefix = '', $postfix = '', $default = '')
{
return $this->customAction ? $prefix . $this->customAction . $postfix : $default;
}
/**
* Zwraca nazwę akcji w formacie php (zamienia format wartosc1_wartosc2... na Wartosc1Wartosc2...)
*
* @param string $prefix wartość doklejona przed nazwą akcji (tylko jeśli akcja istnieje)
* @param string $postfix wartość doklejona za nazwą akcji (tylko jeśli akcja istnieje)
* @param string $default wartość domyślna w przypadku braku akcji
* @return string
*/
protected function getCustomActionPhpName($prefix = '', $postfix = '', $default = '')
{
$tmp = $this->getCustomActionName($prefix, $postfix, $default);
if ($tmp != $default)
{
$tmp = sfInflector::camelize($tmp);
}
return $tmp;
}
/**
* Zwraca nazwę akcji w formacie camelized (zamienia format wartosc1_wartosc2... na wartosc1Wartosc2...)
*
* @param string $prefix wartość doklejona przed nazwą akcji (tylko jeśli akcja istnieje)
* @param string $postfix wartość doklejona za nazwą akcji (tylko jeśli akcja istnieje)
* @param string $default wartość domyślna w przypadku braku akcji
* @return string
*/
protected function getCustomActionNameCamelized($prefix = '', $postfix = '', $default = '')
{
$tmp = $this->getCustomActionPhpName($prefix, $postfix, $default);
if ($tmp != $default)
{
$tmp[0] = strtolower($tmp[0]);
}
return $tmp;
}
/**
* Kończy konfigurację dla indywidualnej akcji
*/
protected function resetParameterValuePrefix()
{
$this->customAction = '';
$this->restoreModelClass();
}
/**
* Zwraca listę akcji danego typu
*
* @param string $type Typ akcji
* @return array Lista akcji
*/
protected function getAllActionsByType($type)
{
if (!$this->getClassName() && $type != 'config')
{
return array();
}
$actions = array('');
if (is_array($type))
{
foreach ($type as $t)
{
if ($tmp = $this->getParameterValue('custom_actions.' . $t, array(), false))
{
$actions = array_merge($actions, $tmp);
}
}
$actions = array_unique($actions);
}
else
{
$actions = array_merge($actions, $this->getParameterValue('custom_actions.' . $type, array(), false));
}
return $actions;
}
/**
* Zwraca parametry w postaci wartosci tablicy ('parametr' => 'wartosc')
*
* @param string $key Klucz zawierajacy parametry
* @return string
*/
public function getComponentParameters($key)
{
$params = sfToolkit::stringToArray($this->getParameterValue($key), array());
$array_string = '';
foreach ($params as $name => $value)
{
if (strpos($value, 'forward_parameters.') !== false)
{
$array_string .= "'" . $name . "' => $" . str_replace('.', "['", $value) . "'], ";
}
else
{
$array_string .= "'" . $name . "' => '" . $value . "', ";
}
}
return $array_string;
}
public function getForwardParameterBy($related_id_key, $prefix = '$', $use_quotes = true)
{
if ($forward_parameter = $this->getParameterValue($related_id_key))
{
if ($use_quotes)
{
return $prefix . str_replace('.', '[\'', $forward_parameter) . '\']';
}
else
{
return $prefix . str_replace('.', '[', $forward_parameter) . ']';
}
}
else
{
return 'null';
}
}
/**
* Returns PHP code to add to a URL for primary keys.
*
* @param string The prefix value
*
* @return string PHP code
*/
public function getPrimaryKeyUrlParams($prefix = '')
{
$params = array();
foreach ($this->getPrimaryKey() as $pk)
{
$fieldName = sfInflector::underscore($pk->getPhpName());
if ($pk->getCreoleType() == CreoleTypes::INTEGER)
{
$params[] = "$fieldName='.intval(" . $this->getColumnGetter($pk, true, $prefix) . ')';
}
else
{
$params[] = "$fieldName='." . $this->getColumnGetter($pk, true, $prefix);
}
}
return implode(".'&", $params);
}
public function compilePrimaryKeyArray($prefix = '')
{
$params = array();
foreach ($this->getPrimaryKey() as $pk)
{
$fieldName = sfInflector::underscore($pk->getPhpName());
if ($pk->getCreoleType() == CreoleTypes::INTEGER)
{
$params[] = "'$fieldName' => intval({$this->getColumnGetter($pk, true, $prefix)})";
}
else
{
$params[] = "'$fieldName' => {$this->getColumnGetter($pk, true, $prefix)}";
}
}
return 'array(' . implode(', ', $params) . ')';
}
public function getMenuComponentBy($key)
{
$menu = $this->getParameterValue($key);
if ($menu == 'none')
{
return 'none';
}
if ($this->getParameterValue($menu . '.display', null, false))
{
$tmp = explode('.', $menu);
return lcfirst(sfInflector::camelize($tmp[0])) . ucfirst($tmp[1]);
}
else
{
return null;
}
}
/**
* Inicjuj gereator
*
* @param unknown_type $generatorManager
*/
public function initialize($generatorManager)
{
$this->dispatcher = sfContext::getInstance()->getController()->getDispatcher();
parent::initialize($generatorManager);
}
/**
* Returns HTML code for a column in filter mode.
*
* @param string The column name
* @param array The parameters
* @return string HTML code
*/
public function getColumnFilterTag($column, $params = array())
{
if (isset($params['alternative_name']))
{
$control_name = $params['alternative_name'];
unset($params['alternative_name']);
}
else
{
$control_name = $column->getName();
}
$user_params = $this->getParameterValue('list.filters.' . $control_name . '.params');
$user_params = is_array($user_params) ? $user_params : sfToolkit::stringToArray($user_params);
$params = $user_params ? array_merge($params, $user_params) : $params;
$type = $column->getCreoleType();
$default_value = "isset(\$filters['" . $control_name . "']) ? \$filters['" . $control_name . "'] : null";
$default_value_from = "isset(\$filters['" . $control_name . "']['from']) ? \$filters['" . $control_name . "']['from'] : null";
$default_value_to = "isset(\$filters['" . $control_name . "']['to']) ? \$filters['" . $control_name . "']['to'] : null";
$unquotedName = 'filters[' . $control_name . ']';
$name = "'$unquotedName'";
$i18n_catalogue = $this->getParameterValue('list.fields.' . $control_name . '.i18n', $this->getModuleName());
if ($column->isForeignKey())
{
$params = $this->getObjectTagParams($params, array('include_custom' => '---', 'related_class' => $this->getRelatedClassName($column), 'text_method' => '__toString', 'control_name' => $unquotedName));
return "object_select_tag($default_value, null, $params)";
}
else if ($type == CreoleTypes::TIMESTAMP || $type == CreoleTypes::DATE)
{
$params = $this->getObjectTagParams($params, array('rich' => true, 'withtime' => $type == CreoleTypes::TIMESTAMP, 'calendar_button_img' => sfConfig::get('sf_admin_web_dir') . '/images/date.png', 'size' => 15, 'class' => 'range-filter'));
$datetime = "input_date_tag('{$unquotedName}[from]', $default_value_from, _parse_attributes($params)) . ' - ' . ";
$datetime .= "input_date_tag('{$unquotedName}[to]', $default_value_to, _parse_attributes($params))";
return $datetime;
}
else if ($type == CreoleTypes::BOOLEAN)
{
$defaultIncludeCustom = '---';
$option_params = $this->getObjectTagParams($params, array('include_custom' => $defaultIncludeCustom));
$params = $this->getObjectTagParams($params);
$options = "options_for_select(array(1 => __('tak', array(), 'stAdminGeneratorPlugin'), 0 => __('nie', array(), 'stAdminGeneratorPlugin')), $default_value, $option_params)";
return "select_tag($name, $options, $params)";
}
else if ($type == CreoleTypes::CHAR || $type == CreoleTypes::VARCHAR || $type == CreoleTypes::TEXT || $type == CreoleTypes::LONGVARCHAR || $type == CreoleTypes::MEDIUMTEXT)
{
if (!isset($params['size'])) {
$params['size'] = 10;
}
$params = $this->getObjectTagParams($params);
return "input_tag($name, $default_value, $params)";
}
else if (
$type == CreoleTypes::INTEGER || $type == CreoleTypes::TINYINT || $type == CreoleTypes::SMALLINT || $type == CreoleTypes::BIGINT ||
$type == CreoleTypes::FLOAT || $type == CreoleTypes::DOUBLE || $type == CreoleTypes::DECIMAL || $type == CreoleTypes::NUMERIC || $type == CreoleTypes::REAL
)
{
$is_float = $type == CreoleTypes::FLOAT || $type == CreoleTypes::DOUBLE || $type == CreoleTypes::DECIMAL || $type == CreoleTypes::NUMERIC || $type == CreoleTypes::REAL;
$params = $this->getObjectTagParams($params, array('size' => 4, 'class' => $is_float ? 'float range-filter' : 'integer range-filter'));
$number_field = "input_tag('{$unquotedName}[from]', $default_value_from, $params) . ' - ' . ";
$number_field .= "input_tag('{$unquotedName}[to]', $default_value_to, $params)";
return $number_field;
}
else
{
if (!isset($params['size'])) {
$params['size'] = 10;
}
$params = $this->getObjectTagParams($params, array('disabled' => true));
return "input_tag($name, $default_value, $params)";
}
}
public function getAdvancedFilterTag($column, $params = array())
{
if (isset($params['alternative_name']))
{
$control_name = $params['alternative_name'];
unset($params['alternative_name']);
}
else
{
$control_name = $column->getName();
}
$user_params = $this->getParameterValue('list.filters.' . $control_name . '.params');
$user_params = is_array($user_params) ? $user_params : sfToolkit::stringToArray($user_params);
$params = $user_params ? array_merge($params, $user_params) : $params;
$type = $column->getCreoleType();
$default_value = "isset(\$filters['" . $control_name . "']) ? \$filters['" . $control_name . "'] : null";
$default_value_from = "isset(\$filters['" . $control_name . "']['from']) ? \$filters['" . $control_name . "']['from'] : null";
$default_value_to = "isset(\$filters['" . $control_name . "']['to']) ? \$filters['" . $control_name . "']['to'] : null";
$default_value_is_empty = "isset(\$filters['" . $control_name . "_is_empty']) ? \$filters['" . $control_name . "_is_empty'] : null";
$unquotedName = 'filters[' . $control_name . ']';
$name = "'$unquotedName'";
$is_empty = $this->getParameterValue('list.filters.' . $control_name . '.empty');
if (!$column->isNotNull() && ($is_empty === null || $is_empty))
{
$is_empty_field = ".' '.content_tag('div', st_admin_checkbox_tag('filters[{$control_name}_is_empty]', true, $default_value_is_empty, array('label' => __('niewypełnione', null, 'stAdminGeneratorPlugin'))), array('class' => 'is_empty_field'))";
}
else
{
$is_empty_field = '';
}
if ($column->isForeignKey())
{
$params = $this->getObjectTagParams($params, array('include_custom' => '---', 'related_class' => $this->getRelatedClassName($column), 'text_method' => '__toString', 'control_name' => $unquotedName));
return "object_select_tag($default_value, null, $params)";
}
else if ($type == CreoleTypes::TIMESTAMP || $type == CreoleTypes::DATE)
{
$params = $this->getObjectTagParams($params, array('rich' => true, 'withtime' => $type == CreoleTypes::TIMESTAMP, 'calendar_button_img' => sfConfig::get('sf_admin_web_dir') . '/images/date.png', 'size' => 15));
$from = "input_date_tag('{$unquotedName}[from]', $default_value_from, $params)";
$to = "input_date_tag('{$unquotedName}[to]', $default_value_to, $params)";
return $from . ".' - '." . $to . $is_empty_field;
}
else if ($type == CreoleTypes::BOOLEAN)
{
$defaultIncludeCustom = '---';
$option_params = $this->getObjectTagParams($params, array('include_custom' => $defaultIncludeCustom));
$params = $this->getObjectTagParams($params);
// little hack
$option_params = preg_replace("/'" . preg_quote($defaultIncludeCustom) . "'/", $defaultIncludeCustom, $option_params);
$options = "options_for_select(array(1 => __('tak', array(), 'stAdminGeneratorPlugin'), 0 => __('nie', array(), 'stAdminGeneratorPlugin')), $default_value, $option_params)";
return "select_tag($name, $options, $params)";
}
else if ($type == CreoleTypes::CHAR || $type == CreoleTypes::VARCHAR || $type == CreoleTypes::TEXT || $type == CreoleTypes::LONGVARCHAR || $type == CreoleTypes::MEDIUMTEXT)
{
$params = $this->getObjectTagParams($params, array('size' => 15));
$input = "input_tag($name, $default_value, $params)";
return $input . $is_empty_field;
}
else if (
$type == CreoleTypes::INTEGER || $type == CreoleTypes::TINYINT || $type == CreoleTypes::SMALLINT || $type == CreoleTypes::BIGINT ||
$type == CreoleTypes::FLOAT || $type == CreoleTypes::DOUBLE || $type == CreoleTypes::DECIMAL || $type == CreoleTypes::NUMERIC || $type == CreoleTypes::REAL
)
{
$is_float = $type == CreoleTypes::FLOAT || $type == CreoleTypes::DOUBLE || $type == CreoleTypes::DECIMAL || $type == CreoleTypes::NUMERIC || $type == CreoleTypes::REAL;
$params = $this->getObjectTagParams($params, array('size' => 8, 'class' => $is_float ? 'float' : 'integer'));
$from = "input_tag('{$unquotedName}[from]', $default_value_from, $params)";
$to = "input_tag('{$unquotedName}[to]', $default_value_to, $params)";
return $from . ".' - '." . $to . $is_empty_field;
}
else
{
$params = $this->getObjectTagParams($params, array('disabled' => true, 'size' => 15));
return "input_tag($name, $default_value, $params)" . $is_empty_field;
}
}
protected function addIgnoreEscapeTagParams($name)
{
$this->ignoreEscapeTagParams[$name] = $name;
}
protected function getObjectTagParams($params, $default_params = array())
{
$params = array_merge($default_params, $params);
if (isset($params['include_custom']))
{
$params['include_custom'] = '__("'.$params['include_custom'].'", null, "stAdminGeneratorPlugin")';
$this->addIgnoreEscapeTagParams('include_custom');
}
$result = var_export($params, true);
if ($this->ignoreEscapeTagParams)
{
foreach ($this->ignoreEscapeTagParams as $name)
{
$result = preg_replace_callback("/'({$name})' \=\> '(.+)'/", function($matches) {
return "'{$matches[1]}' => " . stripslashes($matches[2]);
}, $result);
}
}
$this->ignoreEscapeTagParams = array();
return $result;
}
/**
* Returns HTML code for a column in edit mode.
*
* @param sfAdminColumn $column
* @param array $parameters
* @return string HTML code
*/
public function getColumnEditTag($column, $params = array())
{
$userParams = $this->getParameterValue('edit.fields.' . $column->getName() . '.params');
$userParams = is_array($userParams) ? $userParams : sfToolkit::stringToArray($userParams);
if ($callback = $this->getParameterValue('edit.fields.' . $column->getName() . '.callback'))
{
$params = $userParams ? array_merge($params, $userParams) : $params;
$obj_params = var_export($params, true);
$obj_params = substr_replace($obj_params, count($params) > 0 ? ", 'mode' => \$mode\n" : "'mode' => \$mode\n", -1, 0);
return sprintf('%s(\'%s[%s]\', %s, %s)', $callback, $this->getSingularName(), $column->getName(), method_exists($this->getClassName(), 'get'.$column->getPhpName()) ? $this->getColumnGetter($column, true) : '$'.$this->getSingularName(), $obj_params);
}
elseif ($column->isComponent())
{
$module = $this->getParameterValue('edit.fields.' . $column->getName() . '.module', $this->getModuleName());
$component = $this->getParameterValue('edit.fields.' . $column->getName() . '.component', lcfirst($column->getPhpName()));
$options = var_export($userParams, true);
return "st_get_component('{$module}', '{$component}', array('type' => 'edit', '{$this->getSingularName()}' => \${$this->getSingularName()}, 'name' => '{$this->getSingularName()}[{$column->getName()}]', 'value' => \${$this->getSingularName()}, 'method' => '{$this->getColumnGetter($column)}', 'options' => $options, 'forward_parameters' => \$forward_parameters, 'related_object' => \$related_object, 'mode' => \$mode))";
}
else if ($column->isPartial())
{
$module = $this->getParameterValue('edit.fields.' . $column->getName() . '.module', $this->getModuleName());
$partial = $this->getParameterValue('edit.fields.' . $column->getName() . '.partial', $column->getName());
$options = var_export($userParams, true);
return "st_get_partial('{$module}/{$partial}', array('type' => 'edit', '{$this->getSingularName()}' => \${$this->getSingularName()}, 'name' => '{$this->getSingularName()}[{$column->getName()}]', 'value' => \${$this->getSingularName()}, 'method' => '{$this->getColumnGetter($column)}', 'options' => $options, 'forward_parameters' => \$forward_parameters, 'related_object' => \$related_object, 'mode' => \$mode))";
}
$format = $this->getParameterValue('edit.fields.' . $column->getName() . '.format');
if ($this->getParameterValue('edit.fields.' . $column->getName() . '.support'))
{
$params['class'] = "support";
}
if (isset($params['width']))
{
if (intval($params['width']) === $params['width'])
{
$width = $params['width'] . 'px';
}
else
{
$width = $params['width'];
}
$userParams['style'] = 'width: ' . ($width == 'auto' ? '100%' : $width);
$this->params[$this->getCustomActionName('', '_').'edit']['fields'][$column->getName()]['params'] = $userParams;
}
if ($format)
{
$params['data-format'] = is_array($format) ? json_encode($format) : $format;
}
$postfix = $this->getI18NString('edit.fields.' . $column->getName() . '.postfix', null, false, false);
return parent::getColumnEditTag($column, $params) . ($postfix && $postfix != "null" ? ' .\' \'.' . $postfix . ';' : '');
}
public function getPHPObjectHelper($helperName, $column, $params, $localParams = array())
{
if ($helperName == 'checkbox_tag')
{
$helperName = 'st_admin_checkbox_tag';
}
$params = $this->getObjectTagParams($params, $localParams);
return sprintf('object_%s($%s, \'%s\', %s)', $helperName, $this->getSingularName(), $this->getColumnGetter($column, false), $params);
}
public function getRelatedColumnEditTag($column, $related_column, $params = array())
{
// user defined parameters
$user_params = $this->getParameterValue('edit.fields.' . $column->getName() . '.related_fields.' . $related_column->getName() . '.params');
$user_params = is_array($user_params) ? $user_params : sfToolkit::stringToArray($user_params);
$params = $user_params ? array_merge($params, $user_params) : $params;
if ($column->isComponent())
{
$component = $this->getParameterValue('edit.fields.' . $column->getName() . '.related_fields.' . $related_column->getName() . '.component', lcfirst($column->getPhpName()));
return "st_get_component('" . $this->getParameterValue('edit.fields.' . $column->getName() . '.related_fields.' . $related_column->getName() . '.module', $this->getModuleName()) . "','" . $component . "', array('type' => 'edit', '{$this->getSingularName()}' => \${$this->getSingularName()}, 'forward_parameters' => \$forward_parameters, 'related_object' => \$related_object))";
}
else if ($column->isPartial())
{
$partial = $this->getParameterValue('edit.fields.' . $column->getName() . '.related_fields.' . $related_column->getName() . '.partial', $column->getName());
return "st_get_partial('" . $this->getParameterValue('edit.fields.' . $column->getName() . '.related_fields.' . $related_column->getName() . '.module', $this->getModuleName()) . '/' . $partial . "', array('type' => 'edit', '{$this->getSingularName()}' => \${$this->getSingularName()}, 'forward_parameters' => \$forward_parameters, 'related_object' => \$related_object))";
}
// default control name
$params = array_merge(array('control_name' => $this->getSingularName() . '[' . $column->getName() . '][' . $related_column->getName() . ']'), $params);
// default parameter values
$type = $related_column->getCreoleType();
if ($type == CreoleTypes::DATE)
{
$params = array_merge(array('rich' => true, 'calendar_button_img' => sfConfig::get('sf_admin_web_dir') . '/images/date.png'), $params);
}
else if ($type == CreoleTypes::TIMESTAMP)
{
$params = array_merge(array('rich' => true, 'withtime' => true, 'calendar_button_img' => sfConfig::get('sf_admin_web_dir') . '/images/date.png'), $params);
}
// user sets a specific tag to use
if ($inputType = $this->getParameterValue('edit.fields.' . $column->getName() . '.related_fields.' . $related_column->getName() . '.type'))
{
if ($inputType == 'plain')
{
return $this->getColumnListTag($related_column, $params);
}
else
{
return $this->getPHPObjectHelper($inputType, $related_column, $params);
}
}
// guess the best tag to use with column type
return parent::getCrudColumnEditTag($related_column, $params);
}
public function showConfigCulturePicker($type)
{
$fields = $this->getParameterValue($type . '.fields');
foreach ($fields as $field => $params)
{
if (isset($params['is_i18n']))
{
return true;
}
}
return false;
}
public function normalizeColumnName($name)
{
return trim(preg_replace('/[^a-z0-9_]+/', '_', strtolower(stTextAnalyzer::unaccent($name))), '_');
}
/**
* Returns form control HTML code for a column in $type mode.
*
* @param sfAdminColumn $column column object
* @param string $type mode
* @param array $params HTML parameters
* @return HTML code
*/
public function getColumnFormTag($column, $type, $params = array())
{
$i18n = sfContext::getInstance()->getI18N();
$user_params = $this->getParameterValue($type . '.fields.' . $column->getName() . '.params');
$user_params = is_array($user_params) ? $user_params : sfToolkit::stringToArray($user_params);
$params = $user_params ? array_merge($params, $user_params) : $params;
if ($this->getParameterValue($type . '.fields.' . $column->getName() . '.support'))
{
$params['class'] = "support";
}
$name = "{$type}[{$column->getName()}]";
$is_i18n = $this->getParameterValue($type . '.fields.' . $column->getName() . '.is_i18n', false);
$value = sprintf('$%s->get(\'%s\', null, %s)', $type, $column->getName(), $is_i18n ? 'true' : 'false');
if ($callback = $this->getParameterValue($type . '.fields.' . $column->getName() . '.callback'))
{
$obj_params = var_export($params, true);
return sprintf('%s(\'%s\', %s, %s)', $callback, $name, $value, $obj_params);
}
elseif ($column->isComponent())
{
$component = $this->getParameterValue($type . '.fields.' . $column->getName() . '.component', lcfirst($column->getPhpName()));
return "st_get_component('" . $this->getParameterValue($type . '.fields.' . $column->getName() . '.module', $this->getModuleName()) . "','" . $component . "', array('type' => '$type', 'name' => '$name', '$type' => \$$type, 'forward_parameters' => \$forward_parameters))";
}
else if ($column->isPartial())
{
$partial = $this->getParameterValue($type . '.fields.' . $column->getName() . '.partial', $column->getName());
return "st_get_partial('" . $this->getParameterValue($type . '.fields.' . $column->getName() . '.module', $this->getModuleName()) . '/' . $partial . "', array('type' => '$type', 'name' => '$name', '$type' => \$$type, 'forward_parameters' => \$forward_parameters))";
}
$inputType = $this->getParameterValue($type . '.fields.' . $column->getName() . '.type');
if ($inputType == 'date')
{
$params = array_merge(array('rich' => true, 'calendar_button_img' => sfConfig::get('sf_admin_web_dir') . '/images/date.png'), $params);
}
elseif ($inputType == 'datetime')
{
$params = array_merge(array('rich' => true, 'withtime' => true, 'calendar_button_img' => sfConfig::get('sf_admin_web_dir') . '/images/date.png'), $params);
}
$format = $this->getParameterValue($type . '.fields.' . $column->getName() . '.format');
$postfix = $this->getParameterValue($type . '.fields.' . $column->getName() . '.postfix');
if ($format)
{
$params['data-format'] = $format;
}
if ($inputType == 'st_admin_input_file_tag')
{
$uploadDir = isset($params['upload_dir']) ? $params['upload_dir'] : sfInflector::underscore($this->getModuleName());
if ($is_i18n)
{
$params['upload_dir'] = "'".trim($uploadDir, '/')."/'.stSimpleLanguageHelper::cultureToShortcut(\$config->getCulture())";
}
else
{
$params['upload_dir'] = "'".trim($uploadDir, '/')."'";
}
$this->addIgnoreEscapeTagParams('upload_dir');
}
$width = $this->getParameterValue($type . '.fields.' . $column->getName() . '.width');
if ($width)
{
if (intval($width) === $width)
{
$width .= 'px';
}
$params['style'] = 'width: ' . ($width == 'auto' ? '100%' : $width);
}
$obj_params = $this->getObjectTagParams($params);
switch ($inputType)
{
case 'plain':
$content = $value;
break;
case '':
case 'text':
case 'input_tag':
$content = "input_tag('$name', $value, $obj_params)" . ($postfix ? ". ' <span style=\"vertical-align: middle\">' . __('$postfix') . '</span>' " : '');
break;
case 'date':
case 'datetime':
case 'input_date_tag':
$content = "input_date_tag('$name', $value, $obj_params)" . ($postfix ? ". ' <span style=\"vertical-align: middle\">' . __('$postfix') . '</span>' " : '');
break;
case 'password':
case 'input_password_tag':
$content = "input_password_tag('$name', $value, $obj_params)" . ($postfix ? ". ' <span style=\"vertical-align: middle\">' . __('$postfix') . '</span>' " : '');
break;
case 'textarea':
case 'textarea_tag':
$content = "textarea_tag('$name', $value, $obj_params)";
break;
case 'checkbox':
case 'checkbox_tag':
if ($this->getParameterValue($type . '.fields.' . $column->getName() . '.checked', false))
{
$value = sprintf('$%s->get(\'%s\', true, %s)', $type, $column->getName(), $is_i18n ? 'true' : 'false');
}
$content = "st_admin_checkbox_tag('$name', 1, $value, $obj_params)";
break;
case 'select':
case 'select_tag':
$select_options = array();
$selected = $this->getParameterValue($type . '.fields.' . $column->getName() . '.selected');
if ($this->getParameterValue($type . '.fields.' . $column->getName() . '.display'))
{
$options = $this->getParameterValue($type . '.fields.' . $column->getName() . '.options');
if ($selected)
{
$selected = $this->getParameterValue($type . '.fields.' . $column->getName() . '.options.' . $selected . '.value', $selected);
}
foreach ($this->getParameterValue($type . '.fields.' . $column->getName() . '.display') as $option)
{
$opt_value = isset($options[$option]['value']) ? $options[$option]['value'] : $option;
$opt_name = isset($options[$option]['name']) ? $options[$option]['name'] : $option;
$i18nCatalogue = isset($options[$option]['i18n']) ? $options[$option]['i18n'] : $this->getModuleName();
if ($selected == $opt_value)
{
$select_options[] = sprintf('\'%s\' => [\'label\' => __(\'%s\', array(), \'%s\'), \'selected\' => true]', $opt_value, $opt_name, $i18nCatalogue);
}
else
{
$select_options[] = sprintf('\'%s\' => __(\'%s\', array(), \'%s\')', $opt_value, $opt_name, $i18nCatalogue);
}
}
}
else
{
$options = $this->getParameterValue($type . '.fields.' . $column->getName() . '.options');
foreach ($options as $opValue => $opParams)
{
$selectOptionsParams = [];
$i18nCatalogue = isset($opParams['i18n']) ? $opParams['i18n'] : $this->getModuleName();
if (isset($opParams['params']))
{
$selectOptionsParams = is_array($opParams['params']) ? $opParams['params'] : sfToolkit::stringToArray($opParams['params']);
}
$select_options[] = sprintf('\'%s\' => [\'label\' => __(\'%s\', array(), \'%s\'), \'attr\' => %s]', $opValue, isset($opParams['name']) ? $opParams['name'] : $opValue, $i18nCatalogue, $this->getObjectTagParams($selectOptionsParams));
}
}
$params['selected'] = $value;
$this->addIgnoreEscapeTagParams('selected');
$obj_params = $this->getObjectTagParams($params);
$content = "select_tag('$name', array(" . implode(', ', $select_options) . "), $obj_params)" . ($postfix ? ". ' <span style=\"vertical-align: middle\">' . __('$postfix') . '</span>' " : '');
break;
case 'st_colorpicker_input_tag':
return "st_colorpicker_input_tag('$name', $value, $obj_params)";
break;
case 'st_admin_input_file_tag':
return "st_admin_input_file_tag('$name', $value, $obj_params)";
break;
default:
$content = $this->getConfigObjectHelper($inputType, $column, $params);
break;
}
return $content;
}
public function getConfigObjectHelper($helperName, $column, $params)
{
$params = $this->getObjectTagParams($params, array('control_name' => 'config[' . $column->getName() . ']'));
return sprintf('object_%s($%s, [\'get\', [\'%s\']], %s)', $helperName, 'config', $column->getName(), $params);
}
/**
* Zwraca tytuł aplikacji
*
* @return string|bool
*/
public function getAppTitle()
{
if (null === $this->appTitle)
{
$this->appTitle = $this->getParameterValue('title', false, false);
if (false === $this->appTitle)
{
$this->appTitle = $this->getParameterValue('label', false, false);
}
}
return $this->appTitle;
}
public function getHelp($column, $type = '')
{
$help = $this->getParameterValue($type . '.fields.' . $column->getName() . '.help');
if ($help)
{
$i18n = $this->getParameterValue($type . '.fields.' . $column->getName() . '.i18n', $this->getModuleName());
return "<div class=\"sf_admin_edit_help\">[?php echo __('" . trim($help) . "', array(), '$i18n') ?]</div>";
}
return '';
}
/**
*
* @param string The column name
* @param array The parameters
* @return string HTML code
*/
public function getColumnListTag($column, $params = array())
{
$custom_value = $this->getParameterValue('list.fields.' . $column->getName() . '.custom_value');
if ($custom_value)
{
return $this->getI18NString(null, $custom_value, false);
}
$user_params = $this->getParameterValue('list.fields.' . $column->getName() . '.params');
$user_params = is_array($user_params) ? $user_params : sfToolkit::stringToArray($user_params);
$params = $user_params ? array_merge($params, $user_params) : $params;
$type = $column->getCreoleType();
$columnGetter = $this->getColumnGetter($column, true);
$editable = $this->getParameterValue('list.editable', []);
if ($callback = $this->getParameterValue('list.fields.' . $column->getName() . '.callback'))
{
$result = "$callback(\${$this->getSingularName()}, null, '{$this->getColumnGetter($column, false)}')";
}
elseif ($column->isComponent())
{
$result = $this->getComponentFromColumn($column, $this->getParameterValue('list.fields.' . $column->getName() . '.module'), key_exists($column->getName(), $editable));
}
else if ($column->isPartial())
{
$result = $this->getPartialFromColumn($column, $this->getParameterValue('list.fields.' . $column->getName() . '.module'), key_exists($column->getName(), $editable));
}
else if ($type == CreoleTypes::DATE || $type == CreoleTypes::TIMESTAMP)
{
$format = isset($params['date_format']) ? $params['date_format'] : ($type == CreoleTypes::DATE ? 'dd-MM-yyyy' : 'dd-MM-yyyy, HH:mm');
$result = "($columnGetter !== null && $columnGetter !== '') ? st_format_date($columnGetter, \"$format\") : ''";
}
elseif ($type == CreoleTypes::BOOLEAN)
{
$result = "$columnGetter ? st_admin_get_icon('check-circle') : '&nbsp;'";
}
else
{
$result = "$columnGetter";
}
if (isset($params['truncate_text']))
{
$truncateLines = isset($params['truncate_text_lines']) ? $params['truncate_text_lines'] : 'null';
$result = "st_admin_truncate_text($result, $truncateLines)";
}
return $result;
}
public function getEditColumnListTag($column, $params = array())
{
$editable = $this->getParameterValue('list.editable.' . $column->getName());
if ($callback = $this->getParameterValue('list.fields.' . $column->getName() . '.callback'))
{
return "$callback(\${$this->getSingularName()}, \$list_mode, '{$this->getColumnGetter($column, false)}');";
}
elseif ($column->isComponent())
{
return $this->getComponentFromColumn($column, $this->getParameterValue('list.fields.' . $column->getName() . '.module'), true);
}
else if ($column->isPartial())
{
return $this->getPartialFromColumn($column, $this->getParameterValue('list.fields.' . $column->getName() . '.module'), true);
}
elseif (null !== $editable && $column->isReal())
{
$type = $column->getCreoleType();
$column_getter = $this->getColumnGetter($column, true);
$singular_name = $this->getSingularName();
$column_name = $column->getName();
$params = isset($editable['params']) ? sfToolkit::stringToArray($editable['params']) : array();
if ($column->getCreoleType() != CreoleTypes::BOOLEAN)
{
return "input_tag('{$singular_name}['.\${$singular_name}->getPrimaryKey().'][$column_name]', \$sf_request->hasErrors() ? \$sf_request->getParameter('{$singular_name}['.\${$singular_name}->getPrimaryKey().'][$column_name]') : $column_getter, " . var_export($params, true) . ")";
}
elseif ($column->getCreoleType() == CreoleTypes::BOOLEAN)
{
return "st_admin_checkbox_tag('{$singular_name}['.\${$singular_name}->getPrimaryKey().'][$column_name]', true, \$sf_request->hasErrors() ? \$sf_request->getParameter('{$singular_name}['.\${$singular_name}->getPrimaryKey().'][$column_name]') : $column_getter, " . var_export($params, true) . ")";
}
}
else
{
return $this->getColumnListTag($column);
}
}
/**
* Poprawka - poprawia wydajność podczas przechodzenia pomiędzy modelami bazy danych
*
* @author Marcin Butlak <marcin.butlak@sote.pl>
*/
protected function loadMapBuilderClasses()
{
if (!$this->map)
{
parent::loadMapBuilderClasses();
}
else
{
if (!class_exists($this->getPeerClassName()))
{
throw new PropelException("Class {$this->getPeerClassName()} does not exist");
}
$this->tableMap = $this->map->getDatabaseMap()->getTable(constant($this->getPeerClassName() . '::TABLE_NAME'));
}
}
/**
* Poprawka - zapewnia poprawne ładowanie kluczy podczas przechodzenia pomiędzy modelami bazy danych
*
* @author Marcin Butlak <marcin.butlak@sote.pl>
*/
protected function loadPrimaryKeys()
{
$this->primaryKey = array();
parent::loadPrimaryKeys();
}
/**
* Zmienia nazwę klasy modelu na podstawie której przebiega generowanie modułu
*
* @param string $modelClass
*/
protected function changeModelClass($modelClass, $backwardCompatibility = true)
{
try
{
if ($this->getClassName() != $modelClass)
{
$this->setScaffoldingClassName($modelClass);
// get some model metadata
$this->loadMapBuilderClasses();
// load all primary keys
$this->loadPrimaryKeys();
/**
* PHP case-insensitive class name fix
*/
$this->setScaffoldingClassName($this->tableMap->getPhpName());
}
}
catch (PropelException $e)
{
if ($backwardCompatibility)
{
$this->className = null;
try
{
$this->changeModelClass(lcfirst($modelClass), false);
}
catch (PropelException $e)
{
throw new PropelException("Class $modelClass does not exist");
}
}
else
{
throw $e;
}
}
}
/**
* Przywraca poprzednio ustawiony model
*/
protected function restoreModelClass()
{
$this->changeModelClass(isset($this->params[$this->customAction . '_model_class']) ? $this->params[$this->customAction . '_model_class'] : $this->params['model_class']);
}
public function getAllColumns()
{
if (false === $this->getClassName())
{
return array();
}
return parent::getAllColumns();
}
/**
* Zwraca kolumne na podstawie jej nazwy PHP i nazwy modelu (opcjonalnie)
*
* @param string $phpName Nazwa php
* @param string $modelClass Nazwa modelu (opcjonalna)
* @return sfAdminColumn
*/
public function getColumnForPhpName($phpName, $modelClass = null)
{
if (false === $this->getClassName())
{
return null;
}
$column = parent::getColumnForPhpName($phpName);
// $this->restoreModelClass();
return $column;
}
public function changeModelClassFromField($field)
{
if (is_array($field))
{
$modelClass = $field[0];
}
else
{
$tmp = explode('.', $field);
if (isset($tmp[1]) && strpos($tmp[0], ''))
{
$modelClass = sfInflector::camelize($tmp[0]);
}
else
{
$modelClass = null;
}
}
$this->changeModelClass($modelClass ? $modelClass : $this->getClassName());
}
/**
* Zwraca obiekt sfAdminColumn na podstawie nazwy pola
*
* @param string $field Nazwa pola
* @return sfAdminColumn
*/
public function getAdminColumnFromField($field, &$modelClass = null)
{
if (is_array($field))
{
$modelClass = $field[0];
$field = $field[1];
$flags = '';
}
else
{
$tmp = explode('.', $field);
if (isset($tmp[1]))
{
$modelClass = sfInflector::camelize($tmp[0]);
$field = $tmp[1];
}
else
{
$field = $tmp[0];
}
list($field, $flags) = $this->splitFlag($field);
}
$this->className = null;
$this->changeModelClass(null === $modelClass ? $this->getClassName() : $modelClass);
$column = $this->getAdminColumnForField($field, $flags);
$modelClass = $this->getClassName();
$this->changeModelClass($modelClass);
$this->restoreModelClass();
return $column;
}
/**
* Wygeneruj
*
* @param unknown_type $params
* @return unknown
*/
public function generate($params = array())
{
$this->params = $params;
$required_parameters = array('model_class', 'moduleName');
foreach ($required_parameters as $entry)
{
if (!isset($this->params[$entry]))
{
$error = 'You must specify a "%s"';
$error = sprintf($error, $entry);
throw new sfParseException($error);
}
}
$modelClass = isset($this->params['model_class']) ? $this->params['model_class'] : false;
$this->setModuleName($this->params['moduleName']);
$this->setGeneratedModuleName('auto' . ucfirst($this->params['moduleName']));
foreach ($this->params as $key => $val)
{
if (is_array($val) && key_exists('include_file', $val))
{
$app_yml = sfYaml::load(self::getAppYmlPath($val['include_file']));
$module_yml = sfYaml::load(self::getModuleYmlPath($this->getModuleName(), $val['include_file']));
$plugin_yml = sfYaml::load(self::getPluginYmlPath($this->getModuleName(), $val['include_file']));
$this->params = self::array_merge_recursive($app_yml, $module_yml, $plugin_yml, $this->params);
}
}
$this->dispatcher->notify(new sfEvent($this, 'stAdminGenerator.generate', array('moduleName' => $this->getModuleName())));
$this->dispatcher->notify(new sfEvent($this, 'stAdminGenerator.generate' . ucfirst($this->getModuleName())));
if (false !== $modelClass)
{
if (!class_exists($modelClass))
{
$error = 'Unable to scaffold unexistant model "%s"';
$error = sprintf($error, $modelClass);
throw new sfInitializationException($error);
}
$this->setScaffoldingClassName($modelClass);
}
else
{
$this->className = false;
}
if (false !== $modelClass)
{
// get some model metadata
$this->loadMapBuilderClasses();
// load all primary keys
$this->loadPrimaryKeys();
}
// theme exists?
$theme = isset($this->params['theme']) ? $this->params['theme'] : 'simple';
$themeDir = sfLoader::getGeneratorTemplate($this->getGeneratorClass(), $theme, '');
if (!is_dir($themeDir))
{
$error = 'The theme "%s" does not exist.';
$error = sprintf($error, $theme);
throw new sfConfigurationException($error);
}
$this->setTheme($theme);
if (false !== $modelClass)
{
$templateFiles = sfFinder::type('file')->name('*.php')->relative()->in($themeDir . '/templates');
$configFiles = sfFinder::type('file')->name('*.yml')->relative()->in($themeDir . '/config');
$libFiles = sfFinder::type('file')->name('*.php')->relative()->in($themeDir . '/lib');
}
else
{
$templateFiles = sfFinder::type('file')->not_name('_list*.php', '_edit*.php', '_custom', 'edit*.php', 'list*.php')->relative()->in($themeDir . '/templates');
$configFiles = sfFinder::type('file')->name('*.yml')->relative()->in($themeDir . '/config');
$libFiles = sfFinder::type('file')->name('breadcrumbs.class.php')->relative()->in($themeDir . '/lib');
}
$data = $this->generatePhpFiles($this->generatedModuleName, $templateFiles, $configFiles, $libFiles);
foreach ($this->getColumnCategories('custom_actions') as $category)
{
foreach ($this->getColumns('custom_actions', $category) as $column)
{
$this->generatePhpTemplatesForCustomAction($this->generatedModuleName, $templateFiles, $column->getName(), $category);
}
}
return $data;
}
protected function generatePhpTemplatesForCustomAction($generatedModuleName, $templateFiles = array(), $actionName, $actionType)
{
$ignore = array('_edit_header.php', '_edit_footer.php', '_edit_header_title.php', '_list_messages.php', '_edit_messages.php', '_custom_messages.php', '_config_messages.php');
$this->setParameterValuePrefix($actionName);
foreach ($templateFiles as $template)
{
if (in_array($template, $ignore)) continue;
if (strpos($template, $actionType . 'Success.php') === 0)
{
$retval = $this->evalTemplate('templates/' . $template);
// save template file
$this->getGeneratorManager()->getCache()->set($this->getCustomActionNameCamelized() . ucfirst($template), $generatedModuleName . DIRECTORY_SEPARATOR . 'templates', $retval);
}
elseif (strpos($template, '_' . $actionType) === 0)
{
$retval = $this->evalTemplate('templates/' . $template);
if ($template == sfInflector::underscore($template))
{
$this->getGeneratorManager()->getCache()->set($this->getCustomActionName('_') . $template, $generatedModuleName . DIRECTORY_SEPARATOR . 'templates', $retval);
}
else
{
$this->getGeneratorManager()->getCache()->set(($template[0] == '_' ? '_' : '') . $this->getCustomActionNameCamelized() . ucfirst(ltrim($template, '_')), $generatedModuleName . DIRECTORY_SEPARATOR . 'templates', $retval);
}
}
}
$this->resetParameterValuePrefix();
}
/**
* Wygeneruj pliki php
*
* @param unknown_type $generatedModuleName
* @param unknown_type $templateFiles
* @param unknown_type $configFiles
* @param unknown_type $libFiles
* @return unknown
*/
protected function generatePhpFiles($generatedModuleName, $templateFiles = array(), $configFiles = array(), $libFiles = array())
{
parent::generatePhpFiles($generatedModuleName, $templateFiles, $configFiles);
$retval = $this->evalTemplate('actions/components.class.php');
// save actions class
$this->getGeneratorManager()->getCache()->set('components.class.php', $generatedModuleName . DIRECTORY_SEPARATOR . 'actions', $retval);
// require generated action class
$data = "require_once(sfConfig::get('sf_module_cache_dir').'/" . $generatedModuleName . "/actions/actions.class.php');\n";
$data .= "require_once(sfConfig::get('sf_module_cache_dir').'/" . $generatedModuleName . "/actions/components.class.php');\n";
// generate config files
foreach ($libFiles as $lib)
{
// eval config file
$retval = $this->evalTemplate('lib/' . $lib);
// save config file
$this->getGeneratorManager()->getCache()->set($lib, $generatedModuleName . DIRECTORY_SEPARATOR . 'lib', $retval);
$data .= "require_once(sfConfig::get('sf_module_cache_dir').'/" . $generatedModuleName . "/lib/$lib');\n";
}
return $data;
}
public function replaceConstantsForMenu($value, $double_quoted = false)
{
// find %%xx%% strings
preg_match_all('/%%([^%]+)%%/', $value, $matches, PREG_PATTERN_ORDER);
foreach ($matches[1] as $name)
{
$column = $this->getAdminColumnForField($name);
$value = str_replace('%%' . $column->getName() . '%%', '" . (isset($forward_parameters[\'' . $column->getName() . '\']) ? $forward_parameters[\'' . $column->getName() . '\'] : ' . $this->getColumnGetter($column, true) . ') . "', $value);
}
if ($double_quoted)
{
$value = '"' . $value . '"';
}
return $value;
}
public function getI18nCatalogue($parameterKey)
{
$i18n = $this->getParameterValue($parameterKey.'.i18n_catalogue');
if (null === $i18n)
{
$i18n = $this->getParameterValue($parameterKey.'.i18n', $this->getModuleName());
}
return $i18n;
}
/**
* Wraps a content for I18N.
*
* @param string The key name
* @param string The defaul value
* @return string HTML code
*/
public function getI18NString($key, $default = null, $withEcho = true, $htmlContainer = true, $prefix = '')
{
$value = $this->getParameterValue($key, $default);
if (!$value)
{
return "null";
}
$value = $this->escapeString($value);
list($namespace) = explode(".", $key);
$i18n = $this->getParameterValue($namespace.'.i18n', $this->getModuleName());
if (is_array($i18n))
{
$i18n = $this->getModuleName();
}
// find %%xx%% strings
preg_match_all('/%%([^%]+)%%/', $value, $matches, PREG_PATTERN_ORDER);
$vars = array();
foreach ($matches[1] as $name)
{
list($field, $flags) = $this->splitFlag($name);
$column = $this->getAdminColumnForField($field, $flags);
$columnGetter = $this->getColumnGetter($column, true, $prefix);
$partialModuleName = $this->getParameterValue($namespace . '.fields.' . $column->getName() . '.module', $this->getModuleName());
if ($column->isLink())
{
$content = 'link_to(' . $columnGetter . ', \'' . $this->getModuleName() . '/edit?' . $this->getPrimaryKeyUrlParams() . ')';
}
elseif ($column->isPartial())
{
if ($namespace == 'list')
{
$content = "st_get_partial('" . $partialModuleName . '/' . $column->getName() . "', array('related_object' => \$related_object, 'forward_parameters' => \$forward_parameters))";
}
else
{
$content = "st_get_partial('" . $partialModuleName . '/' . $column->getName() . "', array('{$this->getSingularName()}' => \${$this->getSingularName()}, 'forward_parameters' => \$forward_parameters))";
}
}
else if ($column->isComponent())
{
$component = $column->getPhpName();
$component[0] = strtolower($component[0]);
if ($namespace == 'list')
{
$content = "st_get_component('" . $partialModuleName . "','" . $component . "', array('related_object' => \$related_object, 'forward_parameters' => \$forward_parameters))";
}
else
{
$content = "st_get_component('" . $partialModuleName . "','" . $component . "', array('{$this->getSingularName()}' => \${$this->getSingularName()}, 'forward_parameters' => \$forward_parameters))";
}
}
else
{
$content = $columnGetter;
}
if ($htmlContainer)
{
$vars[] = '\'%%' . $name . '%%\' => ' . $content;
}
else
{
$vars[] = '\'%%' . $name . '%%\' => ' . $content;
}
}
// strip all = signs
$value = preg_replace('/%%=([^%]+)%%/', '%%$1%%', $value);
if (is_array($i18n))
{
throw new Exception(var_export($i18n, true));
}
$i18n = '__(\'' . $value . '\', ' . "\n" . 'array(' . implode(",\n", $vars) . '), \'' . $i18n . '\')';
return $withEcho ? '[?php echo ' . $i18n . ' ?]' : $i18n;
}
/**
* Pobierz przycisk do akcji
*
* @param string $actionName
* @param array $params
* @param bool $pk_link
* @return string
*/
public function getButtonToAction($actionName, $params, $pk_link = false, $type = 'edit')
{
$force_submit = false;
$i18n = sfContext::getInstance()->getI18N();
$defaultLabels = array(
'list' => 'Pokaż listę',
'save' => 'Zapisz',
'save_and_add' => 'Zapisz i dodaj',
'save_and_list' => 'Zapisz i wyświetl listę',
'delete' => 'Usuń',
'create' => 'Dodaj',
);
$params = (array) $params;
$options = isset($params['params']) ? $params['params'] : array();
$method = 'button_to';
$only_for = isset($params['only_for']) ? $params['only_for'] : null;
$callback = null;
if (is_string($options))
{
$options = sfToolkit::stringToArray($options);
}
if (isset($options['force_submit']))
{
$force_submit = $options['force_submit'];
unset($options['force_submit']);
}
if (isset($options['callback']))
{
$callback = $options['callback'];
unset($options['callback']);
}
// default values
if ($actionName[0] == '_')
{
$actionName = substr($actionName, 1);
$defaultIcon = $actionName;
$default_action = $actionName;
$name = isset($defaultLabels[$actionName]) ? $defaultLabels[$actionName] : $actionName;
if ($actionName == 'save' || $actionName == 'save_and_add' || $actionName == 'save_and_list')
{
$method = 'submit_tag';
$defaultIcon = 'check';
}
elseif ($actionName == 'delete')
{
if (!isset($options['confirm']))
{
$options['confirm'] = $i18n->__('Jesteś pewien?', null, 'stAdminGeneratorPlugin');
}
$only_for = 'edit';
$defaultIcon = 'delete';
}
}
else
{
$name = strtr($actionName, '_', ' ');
$default_action = 'List' . sfInflector::camelize($actionName);
$defaultIcon = $actionName;
}
$icon = isset($params['icon']) ? $params['icon'] : $defaultIcon;
$action = isset($params['action']) ? $params['action'] : $default_action;
if (!isset($params['name']))
{
$params['name'] = $name;
}
if (isset($params['type']))
{
$options['type'] = $params['type'];
}
$url_params = array();
if ($pk_link)
{
$url_params[] = $this->getPrimaryKeyUrlParams();
}
$html = '';
if ($only_for == 'edit')
{
$html .= '[?php if (' . $this->getPrimaryKeyIsSet() . '): ?]' . "\n";
}
else if ($only_for == 'create')
{
$html .= '[?php if (!' . $this->getPrimaryKeyIsSet() . '): ?]' . "\n";
}
else if ($only_for !== null)
{
throw new sfConfigurationException(sprintf('The "only_for" parameter can only take "create" or "edit" as argument ("%s")', $only_for));
}
$i18n_catalogue = isset($params['i18n']) ? $params['i18n'] : $this->getModuleName();
$options['name'] = $actionName;
$options_string = '';
$options_string = '"icon" => "'.$icon.'",';
foreach ($options as $key => $value)
{
if ($key == 'confirm')
{
$options_string .= '"' . $key . '"' . ' => __("' . $value . '"),';
}
else
{
$options_string .= '"' . $key . '"' . ' => "' . $value . '",';
}
}
if ($method == 'submit_tag' || $force_submit)
{
$html .= '[?php echo st_get_admin_action(\'' . $actionName . '\', __(\'' . $params['name'] . '\', null, \'' . $i18n_catalogue . '\'), null, array(' . $options_string . ')) ?]';
}
else
{
if ($action[0] == '@')
{
$action = $this->replaceConstantsForTemplate($action) . '\'';
}
else
{
$action = $action[0] == '/' ? $this->replaceConstantsForTemplate($action) . '\'' : $this->getModuleName() . '/' . $action . ($url_params ? '?' . implode(".'&", $url_params) : '\'');
}
$action = "'" . $action;
if ($callback)
{
$action = "is_callable('$callback') ? {$callback}() : $action";
}
$html .= '[?php echo st_get_admin_action(\'' . $icon . '\', __(\'' . $params['name'] . '\', null, \'' . $i18n_catalogue . '\'), stAdminGeneratorHelper::applyParametersToUrl(' . $action . ', $forward_parameters), array(' . $options_string . ')) ?]';
}
if ($only_for !== null)
{
$html .= '[?php endif; ?]' . "\n";
}
return $html;
}
/**
* Returns HTML code for an action link.
*
* @param string The action name
* @param array The parameters
* @param boolean Whether to add a primary key link or not
* @return string HTML code
*/
public function getLinkToAction($actionName, $params, $pk_link = false, $type = 'list')
{
$options = isset($params['params']) ? sfToolkit::stringToArray($params['params']) : array();
// default values
if ($actionName[0] == '_')
{
$actionName = substr($actionName, 1);
$name = $actionName;
$icon = $actionName;
$action = $actionName;
if ($actionName == 'delete')
{
$options['post'] = true;
if (!isset($options['confirm']))
{
$options['confirm'] = 'Jesteś pewien?';
$params['i18n'] = 'stAdminGenerator';
}
}
}
else
{
$name = isset($params['name']) ? $params['name'] : $actionName;
$icon = isset($params['icon']) ? sfToolkit::replaceConstants($params['icon']) : $actionName;
}
if ($icon == 'delete')
{
$icon = 'delete-circle';
}
$action = isset($params['action']) ? $this->replaceConstantsForTemplate($params['action']) : 'list' . sfInflector::camelize($actionName);
if ($action[0] == '@')
{
$url = 'url_for(stAdminGeneratorHelper::applyParametersToUrl(\'' . $action . '\', $forward_parameters))';
}
else
{
if (strpos($action, '?') !== false)
{
$pk_link = false;
}
$url_params = $pk_link ? '?' . $this->getPrimaryKeyUrlParams() : '\'';
$url = $action[0] == '/' || isset($params['action']) && $params['action'][0] == '%' ? '\'' . $action . '\'' : 'url_for(stAdminGeneratorHelper::applyParametersToUrl(\'' . $this->getModuleName() . '/' . $action . $url_params . ', $forward_parameters))';
}
$i18n = isset($params['i18n']) ? $params['i18n'] : $this->getModuleName();
if (isset($options['confirm']))
{
$confirm = 'data-admin-confirm="[?php echo __(\'' . addcslashes($options['confirm'], "'") . '\', null, \''.$i18n.'\') ?]"';
}
else
{
$confirm = '';
}
$title = addcslashes($name, "'");
if ($title == 'edit')
{
$title = 'Edycja';
}
elseif ($title == 'delete')
{
$title = 'Usuń';
}
$params = isset($params['params']) ? sfToolkit::stringToArray($params['params']) : array();
$target = isset($params['target']) ? $params['target'] : '_self';
$showPreloader = isset($params['show_preloader']) && $params['show_preloader'] ? 'data-admin-action-show-preloader' : '';
return <<<HTML
<li>
<a href="[?php echo $url ?]" data-admin-action="$actionName" $confirm $showPreloader target="$target">
[?php echo st_admin_get_icon('$icon', array('title' => __('$title', null, '$i18n'), 'class' => 'tooltip')) ?]
</a>
</li>
HTML;
}
/**
* Replaces constants in a string (this is a modified version for view layer)
*
* @param string $value
* @return string
*/
public function replaceConstantsForTemplate($value, $prefix = '')
{
// find %%xx%% strings
preg_match_all('/%%([^%]+)%%/', $value, $matches, PREG_PATTERN_ORDER);
foreach ($matches[1] as $name)
{
$column = $this->getAdminColumnForField($name);
$field = $prefix ? $prefix . $this->getColumnGetter($column, false) . '()' : $this->getColumnGetter($column, true);
$value = str_replace('%%' . $column->getName() . '%%', '\'.' . $field . '.\'', $value);
}
return $value;
}
public function replaceConstants($value, $prefix = null)
{
// find %%xx%% strings
preg_match_all('/%%([^%]+)%%/', $value, $matches, PREG_PATTERN_ORDER);
foreach ($matches[1] as $name)
{
$column = $this->getAdminColumnForField($name);
$field = $prefix ? '$'.$prefix . $this->getColumnGetter($column, false) . '()' : $this->getColumnGetter($column, true, 'this->');
$value = str_replace('%%' . $column->getName() . '%%', '{' . $field . '}', $value);
}
return $value;
}
/**
* Dołącz plik admin generatora
*
* @param unknown_type $module_name
* @param unknown_type $filename
*/
public function attachAdminGeneratorFile($module_name, $filename)
{
$module_yml = sfYaml::load(self::getModuleYmlPath($module_name, $filename));
$plugin_yml = sfYaml::load(self::getPluginYmlPath($module_name, $filename));
$this->params = self::array_merge_recursive($this->params, $module_yml, $plugin_yml);
}
public function getForwardParameters($type = 'edit')
{
$id = $this->getCustomActionName('', '_'.$type, $type);
if (!isset($this->forwardParameters[$id]))
{
if ($this->customAction)
{
$this->forwardParameters[$id] = array_merge($this->getParameterValue($type . '.forward_parameters', array()), $this->getParameterValue('edit.forward_parameters', array(), false));
}
else
{
$this->forwardParameters[$id] = $this->getParameterValue($type . '.forward_parameters', array());
}
}
return $this->forwardParameters[$id];
}
public function getForwardParametersForUrl($params_prefix = '$', $query_prefix = '&', $type = 'edit', $postfix = "'", $cameCaseNaming = false)
{
$forwardParameterName = $cameCaseNaming ? 'forwardParameters' : 'forward_parameters';
$params = '';
foreach ($this->getForwardParameters($type) as $parameter)
{
$params .= $parameter . "='.{$params_prefix}{$forwardParameterName}['$parameter'].'&";
}
return $params ? $query_prefix . rtrim($params, ".'&") : $postfix;
}
public function getReturnUrl()
{
$list = $this->getParameterValue('edit.actions._list');
if (isset($list['action']))
{
$route = $this->replaceConstants($list['action'], 'related_object->');
}
else
{
$route = $this->getModuleName().'/'.$this->getCustomActionNameCamelized('', 'List', 'list');
}
return "stAdminGeneratorHelper::applyParametersToUrl(\"{$route}\", \$forward_parameters)";
}
/**
* Returns full path to plugin yml generator file
*
* @param string $plugin_name Plugin name
* @param string $yml_file yml File name with extension (example: menu.yml)
* @return string Returns full path to yml file
*/
public static function getPluginYmlPath($plugin_name, $yml_file)
{
return sfConfig::get('sf_plugins_dir') . DIRECTORY_SEPARATOR . $plugin_name . DIRECTORY_SEPARATOR . sfConfig::get('sf_app_config_dir_name') . DIRECTORY_SEPARATOR . 'generator' . DIRECTORY_SEPARATOR . $yml_file;
}
/**
* Returns full path to module yml generator file
*
* @param string $module_name Module name
* @param string $yml_file File name with extension (example: menu.yml)
* @return string Returns full path to yml file
*/
public static function getModuleYmlPath($module_name, $yml_file)
{
return sfConfig::get('sf_app_module_dir') . DIRECTORY_SEPARATOR . $module_name . DIRECTORY_SEPARATOR . sfConfig::get('sf_app_module_config_dir_name') . DIRECTORY_SEPARATOR . 'generator' . DIRECTORY_SEPARATOR . $yml_file;
}
/**
* Enter description here...
*
* @param string $yml_file File name with extension (example: menu.yml)
* @return string Returns full path to yml file
*/
public static function getAppYmlPath($yml_file)
{
return sfConfig::get('sf_app_config_dir') . DIRECTORY_SEPARATOR . 'generator' . $yml_file;
}
/**
* An alternative to array_merge_recursive PHP function
*
* @param array $array1
* @param array $array2
* @param array [optional]
* @return array Merge arrays
*/
public static function array_merge_recursive($array1, $array2)
{
$arrays = func_get_args();
$narrays = count($arrays);
// check arguments
// comment out if more performance is necessary (in this case the foreach loop will trigger a warning if the argument is not an array)
for ($i = 0; $i < $narrays; $i++)
{
if (!is_array($arrays[$i]))
{
// also array_merge_recursive returns nothing in this case
throw new sfException('Argument #' . ($i + 1) . ' is not an array - trying to merge array with scalar!');
}
}
// the first array is in the output set in every case
$ret = $arrays[0];
// merege $ret with the remaining arrays
for ($i = 1; $i < $narrays; $i++)
{
foreach ($arrays[$i] as $key => $value)
{
if (((string) $key) === ((string) intval($key)))
{ // integer or string as integer key - append
$ret[] = $value;
}
else
{ // string key - megre
if (is_array($value) && isset($ret[$key]) && !empty($value))
{
// if $ret[$key] is not an array you try to merge an scalar value with an array - the result is not defined (incompatible arrays)
// in this case the call will trigger an E_USER_WARNING and the $ret[$key] will be null.
if ($key == 'display' && isset($ret[$key]['NONE']) && isset($value[0]))
{
$ret[$key]['NONE'] = self::array_merge_recursive($ret[$key]['NONE'], $value);
}
else
{
$ret[$key] = self::array_merge_recursive($ret[$key], $value);
}
}
else
{
$ret[$key] = $value;
}
}
}
}
return $ret;
}
/**
* Zwraca komponent na podstawie kolumny
*
* @param sfAdminColumn $column Kolumna
* @return string
*/
public function getComponentFromColumn($column, $default_module = null, $editable = false)
{
$tmp = explode('.', $column->getName());
if (isset($tmp[1]))
{
$module = lcfirst(sfInflector::camelize($tmp[0]));
$component = lcfirst(sfInflector::camelize($tmp[1]));
}
else
{
$module = is_null($default_module) ? $this->getModuleName() : $default_module;
$component = lcfirst(sfInflector::camelize($tmp[0]));
}
if ($editable)
{
return "st_get_component('" . $module . "', '" . $component . "', array('type' => 'list', '{$this->getSingularName()}' => isset(\${$this->getSingularName()}) ? \${$this->getSingularName()} : null, 'entity' => isset(\${$this->getSingularName()}) ? \${$this->getSingularName()} : null, 'forward_parameters' => \$forward_parameters, 'list_mode' => \$list_mode))";
}
else
{
return "st_get_component('" . $module . "', '" . $component . "', array('type' => 'list', '{$this->getSingularName()}' => isset(\${$this->getSingularName()}) ? \${$this->getSingularName()} : null, 'entity' => isset(\${$this->getSingularName()}) ? \${$this->getSingularName()} : null, 'forward_parameters' => \$forward_parameters))";
}
}
/**
* Zwraca partial na podstawie kolumny
*
* @param sfAdminColumn $column Kolumna
* @return string
*/
public function getPartialFromColumn($column, $default_module = null, $editable = false)
{
$tmp = explode('.', $column->getName());
if (isset($tmp[1]))
{
$module = lcfirst(sfInflector::camelize($tmp[0]));
$partial = $tmp[1];
}
else
{
$module = is_null($default_module) ? $this->getModuleName() : $default_module;
$partial = $tmp[0];
}
if ($editable)
{
return "st_get_partial('" . $module . "/" . $partial . "', array('type' => 'list', '{$this->getSingularName()}' => isset(\${$this->getSingularName()}) ? \${$this->getSingularName()} : null, 'entity' => isset(\${$this->getSingularName()}) ? \${$this->getSingularName()} : null, 'forward_parameters' => \$forward_parameters, 'list_mode' => \$list_mode))";
}
else
{
return "st_get_partial('" . $module . "/" . $partial . "', array('type' => 'list', '{$this->getSingularName()}' => isset(\${$this->getSingularName()}) ? \${$this->getSingularName()} : null, 'entity' => isset(\${$this->getSingularName()}) ? \${$this->getSingularName()} : null, 'forward_parameters' => \$forward_parameters))";
}
}
protected function getValueFromKey($key, $default = null)
{
$ref = &$this->params;
$parts = explode('.', $key);
$count = count($parts);
for ($i = 0; $i < $count; $i++)
{
$partKey = $parts[$i];
if (!isset($ref[$partKey]))
{
return $default;
}
if ($count == $i + 1)
{
if ($key == 'applications' && stMenuModifier::hasHeadApplications($this->getModuleName()))
{
return stMenuModifier::getHeadApplications($this->getModuleName(), $ref[$partKey]);
}
return $ref[$partKey];
}
else
{
$ref = &$ref[$partKey];
}
}
return $default;
}
}