Class yii\console\controllers\MessageController
從原始碼檔案中提取待翻譯的訊息。
提取的訊息可以依據設定檔中 `format` 的設定,儲存為以下格式
- PHP 訊息來源檔案。
- ".po" 檔案。
- 資料庫。
用法
- 使用 'message/config' 命令建立設定檔:yii message/config /path/to/myapp/messages/config.php
- 編輯建立的設定檔,依照您的網頁應用程式需求進行調整。
- 執行 'message/extract' 命令,使用建立的設定檔:yii message /path/to/myapp/messages/config.php
公開屬性
公共方法
受保護的方法
事件
事件 | 類型 | 描述 | 定義於 |
---|---|---|---|
EVENT_AFTER_ACTION | yii\base\ActionEvent | 在執行控制器動作後立即引發的事件。 | yii\base\Controller |
EVENT_BEFORE_ACTION | yii\base\ActionEvent | 在執行控制器動作前立即引發的事件。 | yii\base\Controller |
常數
常數 | 值 | 描述 | 定義於 |
---|---|---|---|
EXIT_CODE_ERROR | 1 | 自 2.0.13 版本起已棄用。請改用 yii\console\ExitCode::UNSPECIFIED_ERROR。 | yii\console\Controller |
EXIT_CODE_NORMAL | 0 | 自 2.0.13 版本起已棄用。請改用 yii\console\ExitCode::OK。 | yii\console\Controller |
屬性詳細資料
指定哪些檔案/目錄不應被處理的模式列表。如果為空或未設定,將處理所有檔案/目錄。有關模式匹配規則,請參閱 helpers/FileHelper::findFiles() 描述。如果檔案/目錄同時符合 "only" 和 "except" 中的模式,則將不被處理。
要忽略的訊息類別。例如,'yii'、'app*'、'widgets/menu' 等。
另請參閱 isCategoryIgnored()。
是否標記不再出現在原始碼中的訊息。預設為 true,這表示每個這些訊息將以一對 '@@' 標記括起來。
指定哪些檔案(非目錄)應被處理的模式列表。如果為空或未設定,將處理所有檔案。有關模式匹配規則,請參閱 helpers/FileHelper::findFiles() 描述。如果檔案/目錄同時符合 "only" 和 "except" 中的模式,則將不被處理。
用於產生的 PHP 檔案中訊息陣列的 DocBlock。如果為 null
,將使用預設 DocBlock。此屬性僅在 $format 為 "php" 時使用。
包含訊息的產生的 PHP 檔案中的檔案標頭。此屬性僅在 $format 為 "php" 時使用。
在將新訊息與現有訊息合併時,是否按鍵排序訊息。預設為 false,這表示新的(未翻譯的)訊息將與舊的(已翻譯的)訊息分開。
"db" 格式的來源訊息表的自訂名稱。
用於翻譯訊息的函數名稱。這用作標記以查找要翻譯的訊息。您可以為單個函數名稱使用字串,或為多個函數名稱使用陣列。
方法詳細資料
定義於: yii\base\Component::__call()
調用非類別方法的指定名稱方法。
此方法將會檢查是否有任何附加的行為 (behavior) 具有指定名稱的方法,若有的話則會執行它。
請勿直接呼叫此方法,因為它是 PHP 的魔術方法 (magic method),當調用未知方法時會被隱式地呼叫。
public mixed __call ( $name, $params ) | ||
$name | string |
方法名稱 |
$params | array |
方法參數 |
回傳 | mixed |
方法回傳值 |
---|---|---|
拋出 | yii\base\UnknownMethodException |
當呼叫未知方法時 |
public function __call($name, $params)
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $object) {
if ($object->hasMethod($name)) {
return call_user_func_array([$object, $name], $params);
}
}
throw new UnknownMethodException('Calling unknown method: ' . get_class($this) . "::$name()");
}
public void __clone ( ) |
public function __clone()
{
$this->_events = [];
$this->_eventWildcards = [];
$this->_behaviors = null;
}
public void __construct ( $id, $module, $config = [] ) | ||
$id | string |
此控制器的 ID。 |
$module | yii\base\Module |
此控制器所屬的模組。 |
$config | array |
將用於初始化物件屬性的名稱-值組。 |
public function __construct($id, $module, $config = [])
{
$this->id = $id;
$this->module = $module;
parent::__construct($config);
}
定義於: yii\base\Component::__get()
傳回組件屬性的值。
此方法將依序檢查並採取相應的行動
- 由 getter 定義的屬性:回傳 getter 結果
- 行為 (behavior) 的屬性:回傳行為屬性值
請勿直接呼叫此方法,因為它是 PHP 的魔術方法 (magic method),當執行 $value = $component->property;
時會被隱式地呼叫。
另請參閱 __set()。
public mixed __get ( $name ) | ||
$name | string |
屬性名稱 |
回傳 | mixed |
屬性值或行為 (behavior) 屬性的值 |
---|---|---|
拋出 | yii\base\UnknownPropertyException |
如果屬性未定義 |
拋出 | yii\base\InvalidCallException |
如果屬性為唯寫。 |
public function __get($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
// read property, e.g. getName()
return $this->$getter();
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name;
}
}
if (method_exists($this, 'set' . $name)) {
throw new InvalidCallException('Getting write-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Getting unknown property: ' . get_class($this) . '::' . $name);
}
定義於: yii\base\Component::__isset()
檢查屬性是否已設定,即已定義且非 null。
此方法將依序檢查並採取相應的行動
- 由 setter 定義的屬性:回傳屬性是否已設定
- 行為 (behavior) 的屬性:回傳屬性是否已設定
- 對於不存在的屬性回傳
false
請勿直接呼叫此方法,因為它是 PHP 的魔術方法 (magic method),當執行 isset($component->property)
時會被隱式地呼叫。
public boolean __isset ( $name ) | ||
$name | string |
屬性名稱或事件名稱 |
回傳 | boolean |
具名屬性是否已設定 |
---|
public function __isset($name)
{
$getter = 'get' . $name;
if (method_exists($this, $getter)) {
return $this->$getter() !== null;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name)) {
return $behavior->$name !== null;
}
}
return false;
}
定義於: yii\base\Component::__set()
設定組件屬性的值。
此方法將依序檢查並採取相應的行動
- 由 setter 定義的屬性:設定屬性值
- 格式為 "on xyz" 的事件:將處理器附加到 "xyz" 事件
- 格式為 "as xyz" 的行為 (behavior):附加名為 "xyz" 的行為
- 行為 (behavior) 的屬性:設定行為屬性值
請勿直接呼叫此方法,因為它是 PHP 的魔術方法 (magic method),當執行 $component->property = $value;
時會被隱式地呼叫。
另請參閱 __get()。
public void __set ( $name, $value ) | ||
$name | string |
屬性名稱或事件名稱 |
$value | mixed |
屬性值 |
拋出 | yii\base\UnknownPropertyException |
如果屬性未定義 |
---|---|---|
拋出 | yii\base\InvalidCallException |
如果屬性為唯讀。 |
public function __set($name, $value)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
// set property
$this->$setter($value);
return;
} elseif (strncmp($name, 'on ', 3) === 0) {
// on event: attach event handler
$this->on(trim(substr($name, 3)), $value);
return;
} elseif (strncmp($name, 'as ', 3) === 0) {
// as behavior: attach behavior
$name = trim(substr($name, 3));
$this->attachBehavior($name, $value instanceof Behavior ? $value : Yii::createObject($value));
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = $value;
return;
}
}
if (method_exists($this, 'get' . $name)) {
throw new InvalidCallException('Setting read-only property: ' . get_class($this) . '::' . $name);
}
throw new UnknownPropertyException('Setting unknown property: ' . get_class($this) . '::' . $name);
}
定義於: yii\base\Component::__unset()
將組件屬性設定為 null。
此方法將依序檢查並採取相應的行動
- 由 setter 定義的屬性:將屬性值設定為 null
- 行為 (behavior) 的屬性:將屬性值設定為 null
請勿直接呼叫此方法,因為它是 PHP 的魔術方法 (magic method),當執行 unset($component->property)
時會被隱式地呼叫。
public void __unset ( $name ) | ||
$name | string |
屬性名稱 |
拋出 | yii\base\InvalidCallException |
如果屬性為唯讀。 |
---|
public function __unset($name)
{
$setter = 'set' . $name;
if (method_exists($this, $setter)) {
$this->$setter(null);
return;
}
// behavior property
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name)) {
$behavior->$name = null;
return;
}
}
throw new InvalidCallException('Unsetting an unknown or read-only property: ' . get_class($this) . '::' . $name);
}
使用指定的命令行選項為 "extract" 命令建立配置文件。
產生的設定檔包含提取原始碼訊息所需的參數。您可以將此設定檔與 "extract" 命令一起使用。
public integer actionConfig ( $filePath ) | ||
$filePath | string |
輸出檔案名稱或別名。 |
回傳 | integer |
CLI 結束代碼 |
---|---|---|
拋出 | yii\console\Exception |
在失敗時。 |
public function actionConfig($filePath)
{
$filePath = Yii::getAlias($filePath);
$dir = dirname($filePath);
if (file_exists($filePath)) {
if (!$this->confirm("File '{$filePath}' already exists. Do you wish to overwrite it?")) {
return ExitCode::OK;
}
}
$array = VarDumper::export($this->getOptionValues($this->action->id));
$content = <<<EOD
p
onfiguration file for 'yii {$this->id}/{$this->defaultAction}' command.
his file is automatically generated by 'yii {$this->id}/{$this->action->id}' command.
t contains parameters for source code messages extraction.
ou may modify this file to suit your needs.
ou can use 'yii {$this->id}/{$this->action->id}-template' command to create
emplate configuration file with detailed description for each parameter.
rn $array;
if (FileHelper::createDirectory($dir) === false || file_put_contents($filePath, $content, LOCK_EX) === false) {
$this->stdout("Configuration file was NOT created: '{$filePath}'.\n\n", Console::FG_RED);
return ExitCode::UNSPECIFIED_ERROR;
}
$this->stdout("Configuration file created: '{$filePath}'.\n\n", Console::FG_GREEN);
return ExitCode::OK;
}
為 "extract" 命令建立配置文件範本。
建立的設定檔包含關於如何自訂它以符合您需求的詳細說明。自訂之後,您可以將此設定檔與 "extract" 命令一起使用。
public integer actionConfigTemplate ( $filePath ) | ||
$filePath | string |
輸出檔案名稱或別名。 |
回傳 | integer |
CLI 結束代碼 |
---|---|---|
拋出 | yii\console\Exception |
在失敗時。 |
public function actionConfigTemplate($filePath)
{
$filePath = Yii::getAlias($filePath);
if (file_exists($filePath)) {
if (!$this->confirm("File '{$filePath}' already exists. Do you wish to overwrite it?")) {
return ExitCode::OK;
}
}
if (!copy(Yii::getAlias('@yii/views/messageConfig.php'), $filePath)) {
$this->stdout("Configuration file template was NOT created at '{$filePath}'.\n\n", Console::FG_RED);
return ExitCode::UNSPECIFIED_ERROR;
}
$this->stdout("Configuration file template created at '{$filePath}'.\n\n", Console::FG_GREEN);
return ExitCode::OK;
}
從原始碼提取要翻譯的訊息。
此命令將搜尋原始碼檔案並提取需要翻譯成不同語言的訊息。
public void actionExtract ( $configFile = null ) | ||
$configFile | string|null |
設定檔的路徑或別名。您可以使用 "yii message/config" 命令來產生此檔案,然後根據您的需求進行自訂。 |
拋出 | yii\console\Exception |
在失敗時。 |
---|
public function actionExtract($configFile = null)
{
$this->initConfig($configFile);
$files = FileHelper::findFiles(realpath($this->config['sourcePath']), $this->config);
$messages = [];
foreach ($files as $file) {
$messages = array_merge_recursive($messages, $this->extractMessages($file, $this->config['translator'], $this->config['ignoreCategories']));
}
$catalog = isset($this->config['catalog']) ? $this->config['catalog'] : 'messages';
if (in_array($this->config['format'], ['php', 'po'])) {
foreach ($this->config['languages'] as $language) {
$dir = $this->config['messagePath'] . DIRECTORY_SEPARATOR . $language;
if (!is_dir($dir) && !@mkdir($dir)) {
throw new Exception("Directory '{$dir}' can not be created.");
}
if ($this->config['format'] === 'po') {
$this->saveMessagesToPO($messages, $dir, $this->config['overwrite'], $this->config['removeUnused'], $this->config['sort'], $catalog, $this->config['markUnused']);
} else {
$this->saveMessagesToPHP($messages, $dir, $this->config['overwrite'], $this->config['removeUnused'], $this->config['sort'], $this->config['markUnused']);
}
}
} elseif ($this->config['format'] === 'db') {
/** @var Connection $db */
$db = Instance::ensure($this->config['db'], Connection::className());
$sourceMessageTable = isset($this->config['sourceMessageTable']) ? $this->config['sourceMessageTable'] : '{{%source_message}}';
$messageTable = isset($this->config['messageTable']) ? $this->config['messageTable'] : '{{%message}}';
$this->saveMessagesToDb(
$messages,
$db,
$sourceMessageTable,
$messageTable,
$this->config['removeUnused'],
$this->config['languages'],
$this->config['markUnused']
);
} elseif ($this->config['format'] === 'pot') {
$this->saveMessagesToPOT($messages, $this->config['messagePath'], $catalog);
}
}
定義於: yii\base\Controller::actions()
為控制器宣告外部動作。
此方法旨在被覆寫,以宣告控制器的外部動作 (action)。它應該回傳一個陣列,陣列的鍵為動作 ID,而陣列的值為相應的動作類別名稱或動作配置陣列。例如:
return [
'action1' => 'app\components\Action1',
'action2' => [
'class' => 'app\components\Action2',
'property1' => 'value1',
'property2' => 'value2',
],
];
Yii::createObject() 將在稍後用於使用此處提供的配置建立請求的動作。
public array actions ( ) |
public function actions()
{
return [];
}
定義於: yii\base\Controller::afterAction()
在動作執行後立即調用此方法。
此方法將觸發 EVENT_AFTER_ACTION 事件。此方法的回傳值將用作動作回傳值。
如果您覆寫此方法,您的程式碼應如下所示:
public function afterAction($action, $result)
{
$result = parent::afterAction($action, $result);
// your custom code here
return $result;
}
public mixed afterAction ( $action, $result ) | ||
$action | yii\base\Action |
剛執行的動作。 |
$result | mixed |
動作回傳結果。 |
回傳 | mixed |
已處理的動作結果。 |
---|
public function afterAction($action, $result)
{
$event = new ActionEvent($action);
$event->result = $result;
$this->trigger(self::EVENT_AFTER_ACTION, $event);
return $event->result;
}
定義於: yii\console\Controller::ansiFormat()
使用 ANSI 代碼格式化字串。
您可以使用 yii\helpers\Console 中定義的常數來傳遞其他參數。
範例
echo $this->ansiFormat('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
public string ansiFormat ( $string ) | ||
$string | string |
要格式化的字串 |
public function ansiFormat($string)
{
if ($this->isColorEnabled()) {
$args = func_get_args();
array_shift($args);
$string = Console::ansiFormat($string, $args);
}
return $string;
}
定義於: yii\base\Component::attachBehavior()
將行為附加到此組件。
此方法將根據給定的配置建立行為 (behavior) 物件。之後,將透過呼叫 yii\base\Behavior::attach() 方法將行為物件附加到此元件。
另請參閱 detachBehavior()。
public yii\base\Behavior attachBehavior ( $name, $behavior ) | ||
$name | string |
行為 (behavior) 的名稱。 |
$behavior | string|array|yii\base\Behavior |
行為 (behavior) 配置。這可以是下列其中之一:
|
回傳 | yii\base\Behavior |
行為物件 |
---|
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
定義於: yii\base\Component::attachBehaviors()
將行為列表附加到組件。
每個行為 (behavior) 都以其名稱索引,並且應該是 yii\base\Behavior 物件、指定行為類別的字串,或是用於建立行為的配置陣列。
另請參閱 attachBehavior()。
public void attachBehaviors ( $behaviors ) | ||
$behaviors | array |
要附加到元件的行為 (behavior) 列表 |
public function attachBehaviors($behaviors)
{
$this->ensureBehaviors();
foreach ($behaviors as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
定義於: yii\console\Controller::beforeAction()
在動作執行前立即調用此方法。
此方法將觸發 EVENT_BEFORE_ACTION 事件。此方法的回傳值將決定是否應繼續執行動作。
如果動作不應執行,則應在 beforeAction
程式碼內處理請求,方法是提供必要的輸出或重新導向請求。否則,回應將為空。
如果您覆寫此方法,您的程式碼應如下所示:
public function beforeAction($action)
{
// your custom code here, if you want the code to run before action filters,
// which are triggered on the [[EVENT_BEFORE_ACTION]] event, e.g. PageCache or AccessControl
if (!parent::beforeAction($action)) {
return false;
}
// other custom code here
return true; // or false to not run the action
}
public boolean beforeAction ( $action ) | ||
$action | yii\base\Action |
要執行的動作。 |
回傳 | boolean |
是否應繼續執行動作。 |
---|
public function beforeAction($action)
{
$silentExit = $this->silentExitOnException !== null ? $this->silentExitOnException : YII_ENV_TEST;
Yii::$app->errorHandler->silentExitOnException = $silentExit;
return parent::beforeAction($action);
}
定義於: yii\base\Component::behaviors()
傳回此組件應表現為的行為列表。
子類別可以覆寫此方法,以指定它們想要表現為的行為 (behavior)。
此方法的回傳值應為行為 (behavior) 物件或配置的陣列,並以行為名稱索引。行為配置可以是指定行為類別的字串,或具有以下結構的陣列:
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
請注意,行為類別必須從 yii\base\Behavior 擴展。行為可以使用名稱或匿名方式附加。當名稱用作陣列鍵時,使用此名稱,稍後可以使用 getBehavior() 檢索行為,或使用 detachBehavior() 分離行為。匿名行為無法檢索或分離。
在此方法中宣告的行為將自動 (按需) 附加到元件。
public array behaviors ( ) | ||
回傳 | array |
行為 (behavior) 配置。 |
---|
public function behaviors()
{
return [];
}
定義於: yii\console\Controller::bindActionParams()
將參數繫結到動作。
當 yii\base\Action 開始使用給定的參數執行時,將調用此方法。此方法將首先將參數與動作可用的 options 綁定。然後,它會驗證給定的參數。
public array bindActionParams ( $action, $params ) | ||
$action | yii\base\Action |
要與參數綁定的動作 |
$params | array |
要綁定到動作的參數 |
回傳 | array |
動作可以執行的有效參數。 |
---|---|---|
拋出 | yii\console\Exception |
如果存在未知的選項或遺失的參數 |
public function bindActionParams($action, $params)
{
if ($action instanceof InlineAction) {
$method = new \ReflectionMethod($this, $action->actionMethod);
} else {
$method = new \ReflectionMethod($action, 'run');
}
$args = [];
$missing = [];
$actionParams = [];
$requestedParams = [];
foreach ($method->getParameters() as $i => $param) {
$name = $param->getName();
$key = null;
if (array_key_exists($i, $params)) {
$key = $i;
} elseif (array_key_exists($name, $params)) {
$key = $name;
}
if ($key !== null) {
if (PHP_VERSION_ID >= 80000) {
$isArray = ($type = $param->getType()) instanceof \ReflectionNamedType && $type->getName() === 'array';
} else {
$isArray = $param->isArray();
}
if ($isArray) {
$params[$key] = $params[$key] === '' ? [] : preg_split('/\s*,\s*/', $params[$key]);
}
$args[] = $actionParams[$key] = $params[$key];
unset($params[$key]);
} elseif (
PHP_VERSION_ID >= 70100
&& ($type = $param->getType()) !== null
&& $type instanceof \ReflectionNamedType
&& !$type->isBuiltin()
) {
try {
$this->bindInjectedParams($type, $name, $args, $requestedParams);
} catch (\yii\base\Exception $e) {
throw new Exception($e->getMessage());
}
} elseif ($param->isDefaultValueAvailable()) {
$args[] = $actionParams[$i] = $param->getDefaultValue();
} else {
$missing[] = $name;
}
}
if (!empty($missing)) {
throw new Exception(Yii::t('yii', 'Missing required arguments: {params}', ['params' => implode(', ', $missing)]));
}
// We use a different array here, specifically one that doesn't contain service instances but descriptions instead.
if (\Yii::$app->requestedParams === null) {
\Yii::$app->requestedParams = array_merge($actionParams, $requestedParams);
}
return array_merge($args, $params);
}
定義於: yii\base\Controller::bindInjectedParams()
根據動作方法簽名中的類型和名稱填寫參數。
protected void bindInjectedParams ( ReflectionType $type, $name, &$args, &$requestedParams ) | ||
$type | ReflectionType |
動作參數的反射型別。 |
$name | string |
參數的名稱。 |
$args | array |
動作的參數陣列,此函數可能會將項目附加到其中。 |
$requestedParams | array |
包含請求參數的陣列,此函數可能會將特定鍵寫入其中。 |
拋出 | yii\base\ErrorException |
當我們無法載入所需的服務時。 |
---|---|---|
拋出 | yii\base\InvalidConfigException |
當 DI 配置中存在錯誤時拋出。 |
拋出 | yii\di\NotInstantiableException |
當定義無法解析為具體類別時拋出 (例如,介面型別提示),而容器中沒有適當的定義。 |
final protected function bindInjectedParams(\ReflectionType $type, $name, &$args, &$requestedParams)
{
// Since it is not a builtin type it must be DI injection.
$typeName = $type->getName();
if (($component = $this->module->get($name, false)) instanceof $typeName) {
$args[] = $component;
$requestedParams[$name] = 'Component: ' . get_class($component) . " \$$name";
} elseif ($this->module->has($typeName) && ($service = $this->module->get($typeName)) instanceof $typeName) {
$args[] = $service;
$requestedParams[$name] = 'Module ' . get_class($this->module) . " DI: $typeName \$$name";
} elseif (\Yii::$container->has($typeName) && ($service = \Yii::$container->get($typeName)) instanceof $typeName) {
$args[] = $service;
$requestedParams[$name] = "Container DI: $typeName \$$name";
} elseif ($type->allowsNull()) {
$args[] = null;
$requestedParams[$name] = "Unavailable service: $name";
} else {
throw new Exception('Could not load required service: ' . $name);
}
}
定義於: yii\base\Component::canGetProperty()
傳回一個值,指示是否可以讀取屬性。
如果符合以下條件,則可以讀取屬性:
- 類別具有與指定名稱關聯的 getter 方法 (在這種情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數 (當
$checkVars
為 true 時); - 附加的行為 (behavior) 具有給定名稱的可讀屬性 (當
$checkBehaviors
為 true 時)。
另請參閱 canSetProperty()。
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為 (behavior) 的屬性視為此元件的屬性 |
回傳 | boolean |
屬性是否可以讀取 |
---|
public function canGetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'get' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canGetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
定義於: yii\base\Component::canSetProperty()
傳回一個值,指示是否可以設定屬性。
如果符合以下條件,則可以寫入屬性:
- 類別具有與指定名稱關聯的 setter 方法 (在這種情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數 (當
$checkVars
為 true 時); - 附加的行為 (behavior) 具有給定名稱的可寫屬性 (當
$checkBehaviors
為 true 時)。
另請參閱 canGetProperty()。
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為 (behavior) 的屬性視為此元件的屬性 |
回傳 | boolean |
屬性是否可以寫入 |
---|
public function canSetProperty($name, $checkVars = true, $checkBehaviors = true)
{
if (method_exists($this, 'set' . $name) || $checkVars && property_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->canSetProperty($name, $checkVars)) {
return true;
}
}
}
return false;
}
::class
。
定義於: yii\base\BaseObject::className()
傳回此類別的完整限定名稱。
public static string className ( ) | ||
回傳 | string |
此類別的完整限定名稱。 |
---|
public static function className()
{
return get_called_class();
}
定義於: yii\console\Controller::confirm()
要求使用者輸入 y 或 n 以進行確認。
典型的用法如下所示:
if ($this->confirm("Are you sure?")) {
echo "user typed yes\n";
} else {
echo "user typed no\n";
}
public boolean confirm ( $message, $default = false ) | ||
$message | string |
等待使用者輸入之前要輸出的訊息 |
$default | boolean |
如果未進行選擇,則回傳此值。 |
回傳 | boolean |
使用者是否確認。如果 $interactive 為 false,則將回傳 true。 |
---|
public function confirm($message, $default = false)
{
if ($this->interactive) {
return Console::confirm($message, $default);
}
return true;
}
定義於: yii\base\Controller::createAction()
根據給定的動作 ID 建立動作。
此方法首先檢查動作 ID 是否已在 actions() 中宣告。如果是,它將使用那裡宣告的配置來建立動作物件。如果不是,它將尋找控制器方法,其名稱格式為 actionXyz
,其中 xyz
是動作 ID。如果找到,將建立並回傳代表該方法的 yii\base\InlineAction。
public yii\base\Action|null createAction ( $id ) | ||
$id | string |
動作 ID。 |
回傳 | yii\base\Action|null |
新建立的動作實例。如果 ID 未解析為任何動作,則為 Null。 |
---|
public function createAction($id)
{
if ($id === '') {
$id = $this->defaultAction;
}
$actionMap = $this->actions();
if (isset($actionMap[$id])) {
return Yii::createObject($actionMap[$id], [$id, $this]);
}
if (preg_match('/^(?:[a-z0-9_]+-)*[a-z0-9_]+$/', $id)) {
$methodName = 'action' . str_replace(' ', '', ucwords(str_replace('-', ' ', $id)));
if (method_exists($this, $methodName)) {
$method = new \ReflectionMethod($this, $methodName);
if ($method->isPublic() && $method->getName() === $methodName) {
return new InlineAction($id, $this, $methodName);
}
}
}
return null;
}
定義於: yii\base\Component::detachBehavior()
從組件分離行為。
將調用行為 (behavior) 的 yii\base\Behavior::detach() 方法。
public yii\base\Behavior|null detachBehavior ( $name ) | ||
$name | string |
行為的名稱。 |
回傳 | yii\base\Behavior|null |
已分離的行為。如果行為不存在,則為 Null。 |
---|
public function detachBehavior($name)
{
$this->ensureBehaviors();
if (isset($this->_behaviors[$name])) {
$behavior = $this->_behaviors[$name];
unset($this->_behaviors[$name]);
$behavior->detach();
return $behavior;
}
return null;
}
定義於: yii\base\Component::detachBehaviors()
從組件分離所有行為。
public void detachBehaviors ( ) |
public function detachBehaviors()
{
$this->ensureBehaviors();
foreach ($this->_behaviors as $name => $behavior) {
$this->detachBehavior($name);
}
}
定義於: yii\base\Component::ensureBehaviors()
確保在 behaviors() 中宣告的行為已附加到此組件。
public void ensureBehaviors ( ) |
public function ensureBehaviors()
{
if ($this->_behaviors === null) {
$this->_behaviors = [];
foreach ($this->behaviors() as $name => $behavior) {
$this->attachBehaviorInternal($name, $behavior);
}
}
}
從檔案中提取訊息。
protected array extractMessages ( $fileName, $translator, $ignoreCategories = [] ) | ||
$fileName | string |
要從中提取訊息的檔案名稱 |
$translator | string |
用於翻譯訊息的函數名稱 |
$ignoreCategories | array |
要忽略的訊息類別。此參數自 2.0.4 版本起可用。 |
protected function extractMessages($fileName, $translator, $ignoreCategories = [])
{
$this->stdout('Extracting messages from ');
$this->stdout($fileName, Console::FG_CYAN);
$this->stdout("...\n");
$subject = file_get_contents($fileName);
$messages = [];
$tokens = token_get_all($subject);
foreach ((array) $translator as $currentTranslator) {
$translatorTokens = token_get_all('<?php ' . $currentTranslator);
array_shift($translatorTokens);
$messages = array_merge_recursive($messages, $this->extractMessagesFromTokens($tokens, $translatorTokens, $ignoreCategories));
}
$this->stdout("\n");
return $messages;
}
從已剖析的 PHP 令牌列表中提取訊息。
protected array extractMessagesFromTokens ( array $tokens, array $translatorTokens, array $ignoreCategories ) | ||
$tokens | array |
要處理的 Token。 |
$translatorTokens | array |
翻譯器 Token。 |
$ignoreCategories | array |
要忽略的訊息類別。 |
回傳 | array |
訊息。 |
---|
protected function extractMessagesFromTokens(array $tokens, array $translatorTokens, array $ignoreCategories)
{
$messages = [];
$translatorTokensCount = count($translatorTokens);
$matchedTokensCount = 0;
$buffer = [];
$pendingParenthesisCount = 0;
foreach ($tokens as $tokenIndex => $token) {
// finding out translator call
if ($matchedTokensCount < $translatorTokensCount) {
if ($this->tokensEqual($token, $translatorTokens[$matchedTokensCount])) {
$matchedTokensCount++;
} else {
$matchedTokensCount = 0;
}
} elseif ($matchedTokensCount === $translatorTokensCount) {
// translator found
// end of function call
if ($this->tokensEqual(')', $token)) {
$pendingParenthesisCount--;
if ($pendingParenthesisCount === 0) {
// end of translator call or end of something that we can't extract
if (isset($buffer[0][0], $buffer[1], $buffer[2][0]) && $buffer[0][0] === T_CONSTANT_ENCAPSED_STRING && $buffer[1] === ',' && $buffer[2][0] === T_CONSTANT_ENCAPSED_STRING) {
// is valid call we can extract
$category = stripcslashes($buffer[0][1]);
$category = mb_substr($category, 1, -1);
if (!$this->isCategoryIgnored($category, $ignoreCategories)) {
$fullMessage = mb_substr($buffer[2][1], 1, -1);
$i = 3;
while ($i < count($buffer) - 1 && !is_array($buffer[$i]) && $buffer[$i] === '.') {
$fullMessage .= mb_substr($buffer[$i + 1][1], 1, -1);
$i += 2;
}
$message = stripcslashes($fullMessage);
$messages[$category][] = $message;
}
$nestedTokens = array_slice($buffer, 3);
if (count($nestedTokens) > $translatorTokensCount) {
// search for possible nested translator calls
$messages = array_merge_recursive($messages, $this->extractMessagesFromTokens($nestedTokens, $translatorTokens, $ignoreCategories));
}
} else {
// invalid call or dynamic call we can't extract
$line = Console::ansiFormat($this->getLine($buffer), [Console::FG_CYAN]);
$skipping = Console::ansiFormat('Skipping line', [Console::FG_YELLOW]);
$this->stdout("$skipping $line. Make sure both category and message are static strings.\n");
}
// prepare for the next match
$matchedTokensCount = 0;
$pendingParenthesisCount = 0;
$buffer = [];
} else {
$buffer[] = $token;
}
} elseif ($this->tokensEqual('(', $token)) {
// count beginning of function call, skipping translator beginning
// If we are not yet inside the translator, make sure that it's beginning of the real translator.
// See https://github.com/yiisoft/yii2/issues/16828
if ($pendingParenthesisCount === 0) {
$previousTokenIndex = $tokenIndex - $matchedTokensCount - 1;
if (is_array($tokens[$previousTokenIndex])) {
$previousToken = $tokens[$previousTokenIndex][0];
if (in_array($previousToken, [T_OBJECT_OPERATOR, T_PAAMAYIM_NEKUDOTAYIM], true)) {
$matchedTokensCount = 0;
continue;
}
}
}
if ($pendingParenthesisCount > 0) {
$buffer[] = $token;
}
$pendingParenthesisCount++;
} elseif (isset($token[0]) && !in_array($token[0], [T_WHITESPACE, T_COMMENT])) {
// ignore comments and whitespaces
$buffer[] = $token;
}
}
}
return $messages;
}
定義於: yii\base\Controller::findLayoutFile()
尋找適用的佈局檔案。
public string|boolean findLayoutFile ( $view ) | ||
$view | yii\base\View |
要渲染版面配置檔案的視圖物件。 |
回傳 | string|boolean |
版面配置檔案路徑,如果不需要版面配置則為 false。請參考 render() 以了解如何指定此參數。 |
---|---|---|
拋出 | yii\base\InvalidArgumentException |
如果使用無效的路徑別名來指定版面配置。 |
public function findLayoutFile($view)
{
$module = $this->module;
$layout = null;
if (is_string($this->layout)) {
$layout = $this->layout;
} elseif ($this->layout === null) {
while ($module !== null && $module->layout === null) {
$module = $module->module;
}
if ($module !== null && is_string($module->layout)) {
$layout = $module->layout;
}
}
if ($layout === null) {
return false;
}
if (strncmp($layout, '@', 1) === 0) {
$file = Yii::getAlias($layout);
} elseif (strncmp($layout, '/', 1) === 0) {
$file = Yii::$app->getLayoutPath() . DIRECTORY_SEPARATOR . substr($layout, 1);
} else {
$file = $module->getLayoutPath() . DIRECTORY_SEPARATOR . $layout;
}
if (pathinfo($file, PATHINFO_EXTENSION) !== '') {
return $file;
}
$path = $file . '.' . $view->defaultExtension;
if ($view->defaultExtension !== 'php' && !is_file($path)) {
$path = $file . '.php';
}
return $path;
}
定義於: yii\console\Controller::getActionArgsHelp()
傳回動作的匿名引數的幫助資訊。
傳回值應為陣列。鍵名是引數名稱,值是相應的幫助資訊。每個值都必須是以下結構的陣列
- required: bool,此引數是否為必填
- type: string|null,此引數的 PHP 類型
- default: mixed,此引數的預設值
- comment: string,此引數的描述
預設實作將傳回從與動作方法相對應的參數的 Reflection 或 DocBlock 中提取的幫助資訊。
public array getActionArgsHelp ( $action ) | ||
$action | yii\base\Action |
動作實例 |
回傳 | array |
動作引數的幫助資訊 |
---|
public function getActionArgsHelp($action)
{
$method = $this->getActionMethodReflection($action);
$tags = $this->parseDocCommentTags($method);
$tags['param'] = isset($tags['param']) ? (array) $tags['param'] : [];
$phpDocParams = [];
foreach ($tags['param'] as $i => $tag) {
if (preg_match('/^(?<type>\S+)(\s+\$(?<name>\w+))?(?<comment>.*)/us', $tag, $matches) === 1) {
$key = empty($matches['name']) ? $i : $matches['name'];
$phpDocParams[$key] = ['type' => $matches['type'], 'comment' => $matches['comment']];
}
}
unset($tags);
$args = [];
/** @var \ReflectionParameter $parameter */
foreach ($method->getParameters() as $i => $parameter) {
$type = null;
$comment = '';
if (PHP_MAJOR_VERSION > 5 && $parameter->hasType()) {
$reflectionType = $parameter->getType();
if (PHP_VERSION_ID >= 70100) {
$types = method_exists($reflectionType, 'getTypes') ? $reflectionType->getTypes() : [$reflectionType];
foreach ($types as $key => $reflectionType) {
$types[$key] = $reflectionType->getName();
}
$type = implode('|', $types);
} else {
$type = (string) $reflectionType;
}
}
// find PhpDoc tag by property name or position
$key = isset($phpDocParams[$parameter->name]) ? $parameter->name : (isset($phpDocParams[$i]) ? $i : null);
if ($key !== null) {
$comment = $phpDocParams[$key]['comment'];
if ($type === null && !empty($phpDocParams[$key]['type'])) {
$type = $phpDocParams[$key]['type'];
}
}
// if type still not detected, then using type of default value
if ($type === null && $parameter->isDefaultValueAvailable() && $parameter->getDefaultValue() !== null) {
$type = gettype($parameter->getDefaultValue());
}
$args[$parameter->name] = [
'required' => !$parameter->isOptional(),
'type' => $type,
'default' => $parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null,
'comment' => $comment,
];
}
return $args;
}
定義於: yii\console\Controller::getActionHelp()
傳回指定動作的詳細幫助資訊。
public string getActionHelp ( $action ) | ||
$action | yii\base\Action |
要取得幫助的動作 |
回傳 | string |
指定動作的詳細幫助資訊。 |
---|
public function getActionHelp($action)
{
return $this->parseDocCommentDetail($this->getActionMethodReflection($action));
}
定義於: yii\console\Controller::getActionHelpSummary()
傳回描述指定動作的單行簡短摘要。
public string getActionHelpSummary ( $action ) | ||
$action | yii\base\Action |
要取得摘要的動作 |
回傳 | string |
描述指定動作的單行簡短摘要。 |
---|
public function getActionHelpSummary($action)
{
if ($action === null) {
return $this->ansiFormat(Yii::t('yii', 'Action not found.'), Console::FG_RED);
}
return $this->parseDocCommentSummary($this->getActionMethodReflection($action));
}
protected ReflectionFunctionAbstract getActionMethodReflection ( $action ) | ||
$action | yii\base\Action |
protected function getActionMethodReflection($action)
{
if (!isset($this->_reflections[$action->id])) {
if ($action instanceof InlineAction) {
$this->_reflections[$action->id] = new \ReflectionMethod($this, $action->actionMethod);
} else {
$this->_reflections[$action->id] = new \ReflectionMethod($action, 'run');
}
}
return $this->_reflections[$action->id];
}
定義於: yii\console\Controller::getActionOptionsHelp()
傳回動作的選項的幫助資訊。
傳回值應為陣列。鍵名是選項名稱,值是相應的幫助資訊。每個值都必須是以下結構的陣列
- type: string,此引數的 PHP 類型。
- default: string,此引數的預設值
- comment: string,此引數的註解
預設實作將傳回從與動作選項相對應的屬性的 doc-comment 中提取的幫助資訊。
public array getActionOptionsHelp ( $action ) | ||
$action | yii\base\Action | |
回傳 | array |
動作選項的幫助資訊 |
---|
public function getActionOptionsHelp($action)
{
$optionNames = $this->options($action->id);
if (empty($optionNames)) {
return [];
}
$class = new \ReflectionClass($this);
$options = [];
foreach ($class->getProperties() as $property) {
$name = $property->getName();
if (!in_array($name, $optionNames, true)) {
continue;
}
$defaultValue = $property->getValue($this);
$tags = $this->parseDocCommentTags($property);
// Display camelCase options in kebab-case
$name = Inflector::camel2id($name, '-', true);
if (isset($tags['var']) || isset($tags['property'])) {
$doc = isset($tags['var']) ? $tags['var'] : $tags['property'];
if (is_array($doc)) {
$doc = reset($doc);
}
if (preg_match('/^(\S+)(.*)/s', $doc, $matches)) {
$type = $matches[1];
$comment = $matches[2];
} else {
$type = null;
$comment = $doc;
}
$options[$name] = [
'type' => $type,
'default' => $defaultValue,
'comment' => $comment,
];
} else {
$options[$name] = [
'type' => null,
'default' => $defaultValue,
'comment' => '',
];
}
}
return $options;
}
定義於: yii\base\Component::getBehavior()
傳回指定的行為物件。
public yii\base\Behavior|null getBehavior ( $name ) | ||
$name | string |
行為名稱 |
回傳 | yii\base\Behavior|null |
行為物件,如果行為不存在則為 null |
---|
public function getBehavior($name)
{
$this->ensureBehaviors();
return isset($this->_behaviors[$name]) ? $this->_behaviors[$name] : null;
}
定義於: yii\base\Component::getBehaviors()
傳回附加到此組件的所有行為。
public yii\base\Behavior[] getBehaviors ( ) | ||
回傳 | yii\base\Behavior[] |
附加到此元件的行為列表 |
---|
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
public string getHelp ( ) |
public function getHelp()
{
return $this->parseDocCommentDetail(new \ReflectionClass($this));
}
定義於: yii\console\Controller::getHelpSummary()
傳回描述此控制器的單行簡短摘要。
您可以覆寫此方法以傳回自訂的摘要。預設實作會傳回 PHPDoc 註解中的第一行。
public string getHelpSummary ( ) |
public function getHelpSummary()
{
return $this->parseDocCommentSummary(new \ReflectionClass($this));
}
找出找到的第一個非字元 PHP 令牌的行。
protected integer|string getLine ( $tokens ) | ||
$tokens | array |
protected function getLine($tokens)
{
foreach ($tokens as $token) {
if (isset($token[2])) {
return $token[2];
}
}
return 'unknown';
}
public yii\base\Module[] getModules ( ) | ||
回傳 | yii\base\Module[] |
此控制器所在的全部祖先模組。 |
---|
public function getModules()
{
$modules = [$this->module];
$module = $this->module;
while ($module->module !== null) {
array_unshift($modules, $module->module);
$module = $module->module;
}
return $modules;
}
定義於: yii\console\Controller::getOptionValues()
傳回對應於動作 id 選項的屬性。子類別可以覆寫此方法以指定可能的屬性。
public array getOptionValues ( $actionID ) | ||
$actionID | string |
當前請求的動作 ID |
回傳 | array |
與動作選項相對應的屬性 |
---|
public function getOptionValues($actionID)
{
// $actionId might be used in subclasses to provide properties specific to action id
$properties = [];
foreach ($this->options($this->action->id) as $property) {
$properties[$property] = $this->$property;
}
return $properties;
}
定義於: yii\console\Controller::getPassedOptionValues()
傳回對應於傳遞選項的屬性。
public array getPassedOptionValues ( ) | ||
回傳 | array |
與傳遞的選項相對應的屬性 |
---|
public function getPassedOptionValues()
{
$properties = [];
foreach ($this->_passedOptions as $property) {
$properties[$property] = $this->$property;
}
return $properties;
}
定義於: yii\console\Controller::getPassedOptions()
傳回執行期間傳遞的有效選項名稱。
public array getPassedOptions ( ) | ||
回傳 | array |
執行期間傳遞的選項名稱 |
---|
public function getPassedOptions()
{
return $this->_passedOptions;
}
定義於: yii\base\Controller::getRoute()
傳回目前請求的路由。
public string getRoute ( ) | ||
回傳 | string |
目前請求的路由(模組 ID、控制器 ID 和動作 ID)。 |
---|
public function getRoute()
{
return $this->action !== null ? $this->action->getUniqueId() : $this->getUniqueId();
}
定義於: yii\base\Controller::getUniqueId()
傳回控制器的唯一 ID。
public string getUniqueId ( ) | ||
回傳 | string |
以模組 ID(如果有的話)為前綴的控制器 ID。 |
---|
public function getUniqueId()
{
return $this->module instanceof Application ? $this->id : $this->module->getUniqueId() . '/' . $this->id;
}
定義於: yii\base\Controller::getView()
傳回可用於渲染視圖或視圖檔案的視圖物件。
render()、renderPartial() 和 renderFile() 方法將使用此視圖物件來實作實際的視圖渲染。如果未設定,則預設為 "view" 應用程式元件。
public yii\base\View|yii\web\View getView ( ) | ||
回傳 | yii\base\View|yii\web\View |
可用於渲染視圖或視圖檔案的視圖物件。 |
---|
public function getView()
{
if ($this->_view === null) {
$this->_view = Yii::$app->getView();
}
return $this->_view;
}
定義於: yii\base\Controller::getViewPath()
傳回包含此控制器視圖檔案的目錄。
public string getViewPath ( ) | ||
回傳 | string |
包含此控制器的視圖檔案的目錄。 |
---|
public function getViewPath()
{
if ($this->_viewPath === null) {
$this->_viewPath = $this->module->getViewPath() . DIRECTORY_SEPARATOR . $this->id;
}
return $this->_viewPath;
}
定義於: yii\base\Component::hasEventHandlers()
傳回一個值,指示是否有名稱事件的任何處理常式附加。
public boolean hasEventHandlers ( $name ) | ||
$name | string |
事件名稱 |
回傳 | boolean |
是否有任何處理常式附加到事件。 |
---|
public function hasEventHandlers($name)
{
$this->ensureBehaviors();
if (!empty($this->_events[$name])) {
return true;
}
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (!empty($handlers) && StringHelper::matchWildcard($wildcard, $name)) {
return true;
}
}
return Event::hasHandlers($this, $name);
}
定義於: yii\base\Component::hasMethod()
傳回一個值,指示是否已定義方法。
如果符合以下條件,則定義了方法:
- 類別具有具有指定名稱的方法
- 附加的行為具有給定名稱的方法(當
$checkBehaviors
為 true 時)。
public boolean hasMethod ( $name, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkBehaviors | boolean |
是否將行為的方法視為此元件的方法 |
回傳 | boolean |
方法是否已定義 |
---|
public function hasMethod($name, $checkBehaviors = true)
{
if (method_exists($this, $name)) {
return true;
} elseif ($checkBehaviors) {
$this->ensureBehaviors();
foreach ($this->_behaviors as $behavior) {
if ($behavior->hasMethod($name)) {
return true;
}
}
}
return false;
}
定義於: yii\base\Component::hasProperty()
傳回一個值,指示是否為此組件定義了屬性。
如果符合以下條件,則定義了屬性:
- 類別具有與指定名稱相關聯的 getter 或 setter 方法(在這種情況下,屬性名稱不區分大小寫);
- 類別具有具有指定名稱的成員變數 (當
$checkVars
為 true 時); - 附加的行為具有給定名稱的屬性(當
$checkBehaviors
為 true 時)。
另請參閱
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
屬性名稱 |
$checkVars | boolean |
是否將成員變數視為屬性 |
$checkBehaviors | boolean |
是否將行為 (behavior) 的屬性視為此元件的屬性 |
回傳 | boolean |
屬性是否已定義 |
---|
public function hasProperty($name, $checkVars = true, $checkBehaviors = true)
{
return $this->canGetProperty($name, $checkVars, $checkBehaviors) || $this->canSetProperty($name, false, $checkBehaviors);
}
public void init ( ) |
public function init()
{
parent::init();
$this->request = Instance::ensure($this->request, Request::className());
$this->response = Instance::ensure($this->response, Response::className());
}
protected void initConfig ( $configFile ) | ||
$configFile | string | |
拋出 | yii\console\Exception |
如果組態檔不存在。 |
---|
protected function initConfig($configFile)
{
$configFileContent = [];
if ($configFile !== null) {
$configFile = Yii::getAlias($configFile);
if (!is_file($configFile)) {
throw new Exception("The configuration file does not exist: $configFile");
}
$configFileContent = require $configFile;
}
$this->config = array_merge(
$this->getOptionValues($this->action->id),
$configFileContent,
$this->getPassedOptionValues()
);
$this->config['sourcePath'] = Yii::getAlias($this->config['sourcePath']);
$this->config['messagePath'] = Yii::getAlias($this->config['messagePath']);
if (!isset($this->config['sourcePath'], $this->config['languages'])) {
throw new Exception('The configuration file must specify "sourcePath" and "languages".');
}
if (!is_dir($this->config['sourcePath'])) {
throw new Exception("The source path {$this->config['sourcePath']} is not a valid directory.");
}
if (empty($this->config['format']) || !in_array($this->config['format'], ['php', 'po', 'pot', 'db'])) {
throw new Exception('Format should be either "php", "po", "pot" or "db".');
}
if (in_array($this->config['format'], ['php', 'po', 'pot'])) {
if (!isset($this->config['messagePath'])) {
throw new Exception('The configuration file must specify "messagePath".');
}
if (!is_dir($this->config['messagePath'])) {
throw new Exception("The message path {$this->config['messagePath']} is not a valid directory.");
}
}
if (empty($this->config['languages'])) {
throw new Exception('Languages cannot be empty.');
}
if ($this->config['format'] === 'php' && $this->config['phpDocBlock'] === null) {
$this->config['phpDocBlock'] = <<<DOCBLOCK
essage translations.
his file is automatically generated by 'yii {$this->id}/{$this->action->id}' command.
t contains the localizable messages extracted from source code.
ou may modify this file by translating the extracted messages.
ach array element represents the translation (value) of a message (key).
f the value is empty, the message is considered as not translated.
essages that no longer need translation will have their translations
nclosed between a pair of '@@' marks.
essage string can be used with plural forms format. Check i18n section
f the guide for details.
OTE: this file must be saved in UTF-8 encoding.
LOCK;
}
}
該方法檢查 $category 是否根據 $ignoreCategories 陣列被忽略。
範例
myapp
- 將僅忽略myapp
類別;myapp*
- 將被所有以myapp
開頭的類別忽略 (myapp
、myapplication
、myapprove
、myapp/widgets
、myapp.widgets
等)。
protected boolean isCategoryIgnored ( $category, array $ignoreCategories ) | ||
$category | string |
正在檢查的類別 |
$ignoreCategories | array |
要忽略的訊息類別。 |
protected function isCategoryIgnored($category, array $ignoreCategories)
{
if (!empty($ignoreCategories)) {
if (in_array($category, $ignoreCategories, true)) {
return true;
}
foreach ($ignoreCategories as $pattern) {
if (strpos($pattern, '*') > 0 && strpos($category, rtrim($pattern, '*')) === 0) {
return true;
}
}
}
return false;
}
定義於: yii\console\Controller::isColorEnabled()
傳回一個值,指示是否已啟用 ANSI 彩色。
僅當 $color 設定為 true 或未設定且終端機支援 ANSI 顏色時,才會啟用 ANSI 顏色。
public boolean isColorEnabled ( $stream = \STDOUT ) | ||
$stream | resource |
要檢查的流。 |
回傳 | boolean |
是否在輸出中啟用 ANSI 樣式。 |
---|
public function isColorEnabled($stream = \STDOUT)
{
return $this->color === null ? Console::streamSupportsAnsiColors($stream) : $this->color;
}
定義於: yii\base\Component::off()
從此組件分離現有的事件處理常式。
此方法與 on() 的作用相反。
注意:如果為事件名稱傳遞了萬用字元模式,則只會移除使用此萬用字元註冊的處理器,而使用符合此萬用字元的純名稱註冊的處理器將會保留。
另請參閱 on()。
public boolean off ( $name, $handler = null ) | ||
$name | string |
事件名稱 |
$handler | callable|null |
要移除的事件處理器。如果為 null,則會移除附加到具名事件的所有處理器。 |
回傳 | boolean |
如果找到並分離處理器 |
---|
public function off($name, $handler = null)
{
$this->ensureBehaviors();
if (empty($this->_events[$name]) && empty($this->_eventWildcards[$name])) {
return false;
}
if ($handler === null) {
unset($this->_events[$name], $this->_eventWildcards[$name]);
return true;
}
$removed = false;
// plain event names
if (isset($this->_events[$name])) {
foreach ($this->_events[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_events[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_events[$name] = array_values($this->_events[$name]);
return true;
}
}
// wildcard event names
if (isset($this->_eventWildcards[$name])) {
foreach ($this->_eventWildcards[$name] as $i => $event) {
if ($event[0] === $handler) {
unset($this->_eventWildcards[$name][$i]);
$removed = true;
}
}
if ($removed) {
$this->_eventWildcards[$name] = array_values($this->_eventWildcards[$name]);
// remove empty wildcards to save future redundant regex checks:
if (empty($this->_eventWildcards[$name])) {
unset($this->_eventWildcards[$name]);
}
}
}
return $removed;
}
將事件處理常式附加到事件。
事件處理器必須是有效的 PHP 回呼。以下是一些範例
function ($event) { ... } // anonymous function
[$object, 'handleClick'] // $object->handleClick()
['Page', 'handleClick'] // Page::handleClick()
'handleClick' // global function handleClick()
事件處理器必須使用以下簽名來定義,
function ($event)
其中 $event
是一個 yii\base\Event 物件,其中包含與事件相關聯的參數。
自 2.0.14 版本起,您可以將事件名稱指定為萬用字元模式
$component->on('event.group.*', function ($event) {
Yii::trace($event->name . ' is triggered.');
});
另請參閱 off()。
public void on ( $name, $handler, $data = null, $append = true ) | ||
$name | string |
事件名稱 |
$handler | callable |
事件處理器 |
$data | mixed |
事件觸發時要傳遞給事件處理器的資料。當調用事件處理器時,可以透過 yii\base\Event::$data 存取此資料。 |
$append | boolean |
是否將新的事件處理器附加到現有處理器列表的末尾。如果為 false,則新的處理器將插入到現有處理器列表的開頭。 |
public function on($name, $handler, $data = null, $append = true)
{
$this->ensureBehaviors();
if (strpos($name, '*') !== false) {
if ($append || empty($this->_eventWildcards[$name])) {
$this->_eventWildcards[$name][] = [$handler, $data];
} else {
array_unshift($this->_eventWildcards[$name], [$handler, $data]);
}
return;
}
if ($append || empty($this->_events[$name])) {
$this->_events[$name][] = [$handler, $data];
} else {
array_unshift($this->_events[$name], [$handler, $data]);
}
}
傳回選項別名。
子類別可以覆寫此方法以指定別名選項。
public array optionAliases ( ) | ||
回傳 | array |
適用於動作的選項別名,其中鍵是選項的別名,值是選項名稱。 |
---|
public function optionAliases()
{
return array_merge(parent::optionAliases(), [
'c' => 'catalog',
'e' => 'except',
'f' => 'format',
'i' => 'ignoreCategories',
'l' => 'languages',
'u' => 'markUnused',
'p' => 'messagePath',
'o' => 'only',
'w' => 'overwrite',
'S' => 'sort',
't' => 'translator',
'm' => 'sourceMessageTable',
's' => 'sourcePath',
'r' => 'removeUnused',
]);
}
傳回動作 (id) 的有效選項名稱。選項需要存在一個公共成員變數,其名稱為選項名稱。
子類別可以覆寫此方法以指定可能的選項。
請注意,透過選項設定的值在 beforeAction() 被呼叫之前都不可用。
public string[] options ( $actionID ) | ||
$actionID | string |
當前請求的動作 ID |
回傳 | string[] |
適用於動作的選項名稱 |
---|
public function options($actionID)
{
return array_merge(parent::options($actionID), [
'sourcePath',
'messagePath',
'languages',
'translator',
'sort',
'overwrite',
'removeUnused',
'markUnused',
'except',
'only',
'format',
'db',
'sourceMessageTable',
'messageTable',
'catalog',
'ignoreCategories',
'phpFileHeader',
'phpDocBlock',
]);
}
定義於: yii\console\Controller::parseDocCommentDetail()
從 docblock 傳回完整描述。
protected string parseDocCommentDetail ( $reflection ) | ||
$reflection | ReflectionClass|ReflectionProperty|ReflectionFunctionAbstract |
protected function parseDocCommentDetail($reflection)
{
$comment = strtr(trim(preg_replace('/^\s*\**([ \t])?/m', '', trim($reflection->getDocComment(), '/'))), "\r", '');
if (preg_match('/^\s*@\w+/m', $comment, $matches, PREG_OFFSET_CAPTURE)) {
$comment = trim(substr($comment, 0, $matches[0][1]));
}
if ($comment !== '') {
return rtrim(Console::renderColoredString(Console::markdownToAnsi($comment)));
}
return '';
}
定義於: yii\console\Controller::parseDocCommentSummary()
傳回 docblock 的第一行。
protected string parseDocCommentSummary ( $reflection ) | ||
$reflection | ReflectionClass|ReflectionProperty|ReflectionFunctionAbstract |
protected function parseDocCommentSummary($reflection)
{
$docLines = preg_split('~\R~u', $reflection->getDocComment());
if (isset($docLines[1])) {
return trim($docLines[1], "\t *");
}
return '';
}
定義於: yii\console\Controller::parseDocCommentTags()
將註解塊剖析為標籤。
protected array parseDocCommentTags ( $reflection ) | ||
$reflection | ReflectionClass|ReflectionProperty|ReflectionFunctionAbstract |
註解區塊 |
回傳 | array |
已剖析的標籤 |
---|
protected function parseDocCommentTags($reflection)
{
$comment = $reflection->getDocComment();
$comment = "@description \n" . strtr(trim(preg_replace('/^\s*\**([ \t])?/m', '', trim($comment, '/'))), "\r", '');
$parts = preg_split('/^\s*@/m', $comment, -1, PREG_SPLIT_NO_EMPTY);
$tags = [];
foreach ($parts as $part) {
if (preg_match('/^(\w+)(.*)/ms', trim($part), $matches)) {
$name = $matches[1];
if (!isset($tags[$name])) {
$tags[$name] = trim($matches[2]);
} elseif (is_array($tags[$name])) {
$tags[$name][] = trim($matches[2]);
} else {
$tags[$name] = [$tags[$name], trim($matches[2])];
}
}
}
return $tags;
}
定義於: yii\console\Controller::prompt()
提示使用者輸入並驗證它。
public string prompt ( $text, $options = [] ) | ||
$text | string |
提示字串 |
$options | array |
驗證輸入的選項
如何使用帶有驗證器函式的 prompt 方法的範例。
|
回傳 | string |
使用者輸入 |
---|
public function prompt($text, $options = [])
{
if ($this->interactive) {
return Console::prompt($text, $options);
}
return isset($options['default']) ? $options['default'] : '';
}
定義於: yii\base\Controller::render()
渲染視圖並在可用時應用佈局。
要呈現的視圖可以用以下格式之一指定
- 路徑別名 (例如 "@app/views/site/index");
- 應用程式內的絕對路徑 (例如 "//site/index"):視圖名稱以雙斜線開頭。實際的視圖檔案將在應用程式的 視圖路徑 下尋找。
- 模組內的絕對路徑 (例如 "/site/index"):視圖名稱以單斜線開頭。實際的視圖檔案將在 視圖路徑 的 $module 下尋找。
- 相對路徑 (例如 "index"):實際的視圖檔案將在 $viewPath 下尋找。
為了確定應套用哪個版面配置,將執行以下兩個步驟
- 在第一步中,它確定版面配置名稱和上下文模組
- 如果 $layout 被指定為字串,則將其用作版面配置名稱,並將 $module 用作上下文模組;
- 如果 $layout 為 null,則搜尋此控制器所有祖先模組,並找到第一個 layout 不為 null 的模組。版面配置和相應的模組將分別用作版面配置名稱和上下文模組。如果找不到這樣的模組,或相應的版面配置不是字串,則它將傳回 false,表示沒有適用的版面配置。
- 在第二步中,它根據先前找到的版面配置名稱和上下文模組確定實際的版面配置檔案。版面配置名稱可以是
- 路徑別名 (例如 "@app/views/layouts/main");
- 絕對路徑 (例如 "/main"):版面配置名稱以斜線開頭。實際的版面配置檔案將在應用程式的 版面配置路徑 下尋找;
- 相對路徑 (例如 "main"):實際的版面配置檔案將在上下文模組的 版面配置路徑 下尋找。
如果版面配置名稱不包含檔案副檔名,它將使用預設副檔名 .php
。
public string render ( $view, $params = [] ) | ||
$view | string |
視圖名稱。 |
$params | array |
應在視圖中提供的參數(名稱-值對)。這些參數在版面配置中不可用。 |
回傳 | string |
呈現結果。 |
---|---|---|
拋出 | yii\base\InvalidArgumentException |
如果視圖檔案或版面配置檔案不存在。 |
public function render($view, $params = [])
{
$content = $this->getView()->render($view, $params, $this);
return $this->renderContent($content);
}
定義於: yii\base\Controller::renderContent()
通過應用佈局渲染靜態字串。
public string renderContent ( $content ) | ||
$content | string |
要呈現的靜態字串 |
回傳 | string |
具有給定靜態字串作為 |
---|
public function renderContent($content)
{
$layoutFile = $this->findLayoutFile($this->getView());
if ($layoutFile !== false) {
return $this->getView()->renderFile($layoutFile, ['content' => $content], $this);
}
return $content;
}
定義於: yii\base\Controller::renderFile()
渲染視圖檔案。
public string renderFile ( $file, $params = [] ) | ||
$file | string |
要呈現的視圖檔案。這可以是檔案路徑或 路徑別名。 |
$params | array |
應在視圖中提供的參數(名稱-值對)。 |
回傳 | string |
呈現結果。 |
---|---|---|
拋出 | yii\base\InvalidArgumentException |
如果視圖檔案不存在。 |
public function renderFile($file, $params = [])
{
return $this->getView()->renderFile($file, $params, $this);
}
public string renderPartial ( $view, $params = [] ) | ||
$view | string |
視圖名稱。請參閱 render() 以了解如何指定視圖名稱。 |
$params | array |
應在視圖中提供的參數(名稱-值對)。 |
回傳 | string |
呈現結果。 |
---|---|---|
拋出 | yii\base\InvalidArgumentException |
如果視圖檔案不存在。 |
public function renderPartial($view, $params = [])
{
return $this->getView()->render($view, $params, $this);
}
定義於: yii\base\Controller::run()
執行以路由形式指定的請求。
路由可以是此控制器內動作的 ID,也可以是由模組 ID、控制器 ID 和動作 ID 組成的完整路由。如果路由以斜線 '/' 開頭,則路由的剖析將從應用程式開始;否則,它將從此控制器的父模組開始。
另請參閱 runAction()。
public mixed run ( $route, $params = [] ) | ||
$route | string |
要處理的路由,例如 'view'、'comment/view'、'/admin/comment/view'。 |
$params | array |
要傳遞給動作的參數。 |
回傳 | mixed |
動作的結果。 |
---|
public function run($route, $params = [])
{
$pos = strpos($route, '/');
if ($pos === false) {
return $this->runAction($route, $params);
} elseif ($pos > 0) {
return $this->module->runAction($route, $params);
}
return Yii::$app->runAction(ltrim($route, '/'), $params);
}
定義於: yii\console\Controller::runAction()
使用指定的動作 ID 和參數執行動作。
如果動作 ID 為空,則此方法將使用 $defaultAction。
另請參閱 createAction()。
public integer runAction ( $id, $params = [] ) | ||
$id | string |
要執行的動作的 ID。 |
$params | array |
要傳遞給動作的參數(名稱-值對)。 |
回傳 | integer |
動作執行的狀態。0 表示正常,其他值表示異常。 |
---|---|---|
拋出 | yii\base\InvalidRouteException |
如果請求的動作 ID 無法成功解析為動作。 |
拋出 | yii\console\Exception |
如果存在未知的選項或遺失的參數 |
public function runAction($id, $params = [])
{
if (!empty($params)) {
// populate options here so that they are available in beforeAction().
$options = $this->options($id === '' ? $this->defaultAction : $id);
if (isset($params['_aliases'])) {
$optionAliases = $this->optionAliases();
foreach ($params['_aliases'] as $name => $value) {
if (array_key_exists($name, $optionAliases)) {
$params[$optionAliases[$name]] = $value;
} else {
$message = Yii::t('yii', 'Unknown alias: -{name}', ['name' => $name]);
if (!empty($optionAliases)) {
$aliasesAvailable = [];
foreach ($optionAliases as $alias => $option) {
$aliasesAvailable[] = '-' . $alias . ' (--' . $option . ')';
}
$message .= '. ' . Yii::t('yii', 'Aliases available: {aliases}', [
'aliases' => implode(', ', $aliasesAvailable)
]);
}
throw new Exception($message);
}
}
unset($params['_aliases']);
}
foreach ($params as $name => $value) {
// Allow camelCase options to be entered in kebab-case
if (!in_array($name, $options, true) && strpos($name, '-') !== false) {
$kebabName = $name;
$altName = lcfirst(Inflector::id2camel($kebabName));
if (in_array($altName, $options, true)) {
$name = $altName;
}
}
if (in_array($name, $options, true)) {
$default = $this->$name;
if (is_array($default) && is_string($value)) {
$this->$name = preg_split('/\s*,\s*(?![^()]*\))/', $value);
} elseif ($default !== null) {
settype($value, gettype($default));
$this->$name = $value;
} else {
$this->$name = $value;
}
$this->_passedOptions[] = $name;
unset($params[$name]);
if (isset($kebabName)) {
unset($params[$kebabName]);
}
} elseif (!is_int($name)) {
$message = Yii::t('yii', 'Unknown option: --{name}', ['name' => $name]);
if (!empty($options)) {
$message .= '. ' . Yii::t('yii', 'Options available: {options}', ['options' => '--' . implode(', --', $options)]);
}
throw new Exception($message);
}
}
}
if ($this->help) {
$route = $this->getUniqueId() . '/' . $id;
return Yii::$app->runAction('help', [$route]);
}
return parent::runAction($id, $params);
}
將類別訊息寫入 PHP 檔案。
protected integer saveMessagesCategoryToPHP ( $messages, $fileName, $overwrite, $removeUnused, $sort, $category, $markUnused ) | ||
$messages | array | |
$fileName | string |
要寫入的檔案名稱 |
$overwrite | boolean |
如果應該覆寫現有檔案而不備份 |
$removeUnused | boolean |
如果應該移除過時的翻譯 |
$sort | boolean |
是否應對翻譯進行排序 |
$category | string |
訊息類別 |
$markUnused | boolean |
是否應標記過時的翻譯 |
回傳 | integer |
結束代碼 |
---|
protected function saveMessagesCategoryToPHP($messages, $fileName, $overwrite, $removeUnused, $sort, $category, $markUnused)
{
if (is_file($fileName)) {
$rawExistingMessages = require $fileName;
$existingMessages = $rawExistingMessages;
sort($messages);
ksort($existingMessages);
if (array_keys($existingMessages) === $messages && (!$sort || array_keys($rawExistingMessages) === $messages)) {
$this->stdout("Nothing new in \"$category\" category... Nothing to save.\n\n", Console::FG_GREEN);
return ExitCode::OK;
}
unset($rawExistingMessages);
$merged = [];
$untranslated = [];
foreach ($messages as $message) {
if (array_key_exists($message, $existingMessages) && $existingMessages[$message] !== '') {
$merged[$message] = $existingMessages[$message];
} else {
$untranslated[] = $message;
}
}
ksort($merged);
sort($untranslated);
$todo = [];
foreach ($untranslated as $message) {
$todo[$message] = '';
}
ksort($existingMessages);
foreach ($existingMessages as $message => $translation) {
if (!$removeUnused && !isset($merged[$message]) && !isset($todo[$message])) {
if (!$markUnused || (!empty($translation) && (strncmp($translation, '@@', 2) === 0 && substr_compare($translation, '@@', -2, 2) === 0))) {
$todo[$message] = $translation;
} else {
$todo[$message] = '@@' . $translation . '@@';
}
}
}
$merged = array_merge($merged, $todo);
if ($sort) {
ksort($merged);
}
if (false === $overwrite) {
$fileName .= '.merged';
}
$this->stdout("Translation merged.\n");
} else {
$merged = [];
foreach ($messages as $message) {
$merged[$message] = '';
}
ksort($merged);
}
$array = VarDumper::export($merged);
$content = <<<EOD
p
is->config['phpFileHeader']}{$this->config['phpDocBlock']}
rn $array;
if (file_put_contents($fileName, $content, LOCK_EX) === false) {
$this->stdout("Translation was NOT saved.\n\n", Console::FG_RED);
return ExitCode::UNSPECIFIED_ERROR;
}
$this->stdout("Translation saved.\n\n", Console::FG_GREEN);
return ExitCode::OK;
}
將訊息儲存到資料庫。
protected void saveMessagesToDb ( $messages, $db, $sourceMessageTable, $messageTable, $removeUnused, $languages, $markUnused ) | ||
$messages | array | |
$db | yii\db\Connection | |
$sourceMessageTable | string | |
$messageTable | string | |
$removeUnused | boolean | |
$languages | array | |
$markUnused | boolean |
protected function saveMessagesToDb($messages, $db, $sourceMessageTable, $messageTable, $removeUnused, $languages, $markUnused)
{
$currentMessages = [];
$rows = (new Query())->select(['id', 'category', 'message'])->from($sourceMessageTable)->all($db);
foreach ($rows as $row) {
$currentMessages[$row['category']][$row['id']] = $row['message'];
}
$new = [];
$obsolete = [];
foreach ($messages as $category => $msgs) {
$msgs = array_unique($msgs);
if (isset($currentMessages[$category])) {
$new[$category] = array_diff($msgs, $currentMessages[$category]);
// obsolete messages per category
$obsolete += array_diff($currentMessages[$category], $msgs);
} else {
$new[$category] = $msgs;
}
}
// obsolete categories
foreach (array_diff(array_keys($currentMessages), array_keys($messages)) as $category) {
$obsolete += $currentMessages[$category];
}
if (!$removeUnused) {
foreach ($obsolete as $pk => $msg) {
// skip already marked unused
if (strncmp($msg, '@@', 2) === 0 && substr($msg, -2) === '@@') {
unset($obsolete[$pk]);
}
}
}
$this->stdout('Inserting new messages...');
$insertCount = 0;
foreach ($new as $category => $msgs) {
foreach ($msgs as $msg) {
$insertCount++;
$db->schema->insert($sourceMessageTable, ['category' => $category, 'message' => $msg]);
}
}
$this->stdout($insertCount ? "{$insertCount} saved.\n" : "Nothing to save.\n");
$this->stdout($removeUnused ? 'Deleting obsoleted messages...' : 'Updating obsoleted messages...');
if (empty($obsolete)) {
$this->stdout("Nothing obsoleted...skipped.\n");
}
if ($obsolete) {
if ($removeUnused) {
$affected = $db->createCommand()
->delete($sourceMessageTable, ['in', 'id', array_keys($obsolete)])
->execute();
$this->stdout("{$affected} deleted.\n");
} elseif ($markUnused) {
$marked = 0;
$rows = (new Query())
->select(['id', 'message'])
->from($sourceMessageTable)
->where(['in', 'id', array_keys($obsolete)])
->all($db);
foreach ($rows as $row) {
$marked++;
$db->createCommand()->update(
$sourceMessageTable,
['message' => '@@' . $row['message'] . '@@'],
['id' => $row['id']]
)->execute();
}
$this->stdout("{$marked} updated.\n");
} else {
$this->stdout("kept untouched.\n");
}
}
// get fresh message id list
$freshMessagesIds = [];
$rows = (new Query())->select(['id'])->from($sourceMessageTable)->all($db);
foreach ($rows as $row) {
$freshMessagesIds[] = $row['id'];
}
$this->stdout('Generating missing rows...');
$generatedMissingRows = [];
foreach ($languages as $language) {
$count = 0;
// get list of ids of translations for this language
$msgRowsIds = [];
$msgRows = (new Query())->select(['id'])->from($messageTable)->where([
'language' => $language,
])->all($db);
foreach ($msgRows as $row) {
$msgRowsIds[] = $row['id'];
}
// insert missing
foreach ($freshMessagesIds as $id) {
if (!in_array($id, $msgRowsIds)) {
$db->createCommand()
->insert($messageTable, ['id' => $id, 'language' => $language])
->execute();
$count++;
}
}
if ($count) {
$generatedMissingRows[] = "{$count} for {$language}";
}
}
$this->stdout($generatedMissingRows ? implode(', ', $generatedMissingRows) . ".\n" : "Nothing to do.\n");
$this->stdout('Dropping unused languages...');
$droppedLanguages = [];
$currentLanguages = [];
$rows = (new Query())->select(['language'])->from($messageTable)->groupBy('language')->all($db);
foreach ($rows as $row) {
$currentLanguages[] = $row['language'];
}
foreach ($currentLanguages as $currentLanguage) {
if (!in_array($currentLanguage, $languages)) {
$deleted = $db->createCommand()->delete($messageTable, 'language=:language', [
'language' => $currentLanguage,
])->execute();
$droppedLanguages[] = "removed {$deleted} rows for $currentLanguage";
}
}
$this->stdout($droppedLanguages ? implode(', ', $droppedLanguages) . ".\n" : "Nothing to do.\n");
}
將訊息寫入 PHP 檔案。
protected void saveMessagesToPHP ( $messages, $dirName, $overwrite, $removeUnused, $sort, $markUnused ) | ||
$messages | array | |
$dirName | string |
要寫入的目錄名稱 |
$overwrite | boolean |
如果應該覆寫現有檔案而不備份 |
$removeUnused | boolean |
如果應該移除過時的翻譯 |
$sort | boolean |
是否應對翻譯進行排序 |
$markUnused | boolean |
是否應標記過時的翻譯 |
protected function saveMessagesToPHP($messages, $dirName, $overwrite, $removeUnused, $sort, $markUnused)
{
foreach ($messages as $category => $msgs) {
$file = str_replace('\\', '/', "$dirName/$category.php");
$path = dirname($file);
FileHelper::createDirectory($path);
$msgs = array_values(array_unique($msgs));
$coloredFileName = Console::ansiFormat($file, [Console::FG_CYAN]);
$this->stdout("Saving messages to $coloredFileName...\n");
$this->saveMessagesCategoryToPHP($msgs, $file, $overwrite, $removeUnused, $sort, $category, $markUnused);
}
if ($removeUnused) {
$this->deleteUnusedPhpMessageFiles(array_keys($messages), $dirName);
}
}
將訊息寫入 PO 檔案。
protected void saveMessagesToPO ( $messages, $dirName, $overwrite, $removeUnused, $sort, $catalog, $markUnused ) | ||
$messages | array | |
$dirName | string |
要寫入的目錄名稱 |
$overwrite | boolean |
如果應該覆寫現有檔案而不備份 |
$removeUnused | boolean |
如果應該移除過時的翻譯 |
$sort | boolean |
是否應對翻譯進行排序 |
$catalog | string |
訊息目錄 |
$markUnused | boolean |
是否應標記過時的翻譯 |
protected function saveMessagesToPO($messages, $dirName, $overwrite, $removeUnused, $sort, $catalog, $markUnused)
{
$file = str_replace('\\', '/', "$dirName/$catalog.po");
FileHelper::createDirectory(dirname($file));
$this->stdout("Saving messages to $file...\n");
$poFile = new GettextPoFile();
$merged = [];
$todos = [];
$hasSomethingToWrite = false;
foreach ($messages as $category => $msgs) {
$notTranslatedYet = [];
$msgs = array_values(array_unique($msgs));
if (is_file($file)) {
$existingMessages = $poFile->load($file, $category);
sort($msgs);
ksort($existingMessages);
if (array_keys($existingMessages) == $msgs) {
$this->stdout("Nothing new in \"$category\" category...\n");
sort($msgs);
foreach ($msgs as $message) {
$merged[$category . chr(4) . $message] = $existingMessages[$message];
}
ksort($merged);
continue;
}
// merge existing message translations with new message translations
foreach ($msgs as $message) {
if (array_key_exists($message, $existingMessages) && $existingMessages[$message] !== '') {
$merged[$category . chr(4) . $message] = $existingMessages[$message];
} else {
$notTranslatedYet[] = $message;
}
}
ksort($merged);
sort($notTranslatedYet);
// collect not yet translated messages
foreach ($notTranslatedYet as $message) {
$todos[$category . chr(4) . $message] = '';
}
// add obsolete unused messages
foreach ($existingMessages as $message => $translation) {
if (!$removeUnused && !isset($merged[$category . chr(4) . $message]) && !isset($todos[$category . chr(4) . $message])) {
if (!$markUnused || (!empty($translation) && (substr($translation, 0, 2) === '@@' && substr($translation, -2) === '@@'))) {
$todos[$category . chr(4) . $message] = $translation;
} else {
$todos[$category . chr(4) . $message] = '@@' . $translation . '@@';
}
}
}
$merged = array_merge($merged, $todos);
if ($sort) {
ksort($merged);
}
if ($overwrite === false) {
$file .= '.merged';
}
} else {
sort($msgs);
foreach ($msgs as $message) {
$merged[$category . chr(4) . $message] = '';
}
ksort($merged);
}
$this->stdout("Category \"$category\" merged.\n");
$hasSomethingToWrite = true;
}
if ($hasSomethingToWrite) {
$poFile->save($file, $merged);
$this->stdout("Translation saved.\n", Console::FG_GREEN);
} else {
$this->stdout("Nothing to save.\n", Console::FG_GREEN);
}
}
將訊息寫入 POT 檔案。
protected void saveMessagesToPOT ( $messages, $dirName, $catalog ) | ||
$messages | array | |
$dirName | string |
要寫入的目錄名稱 |
$catalog | string |
訊息目錄 |
protected function saveMessagesToPOT($messages, $dirName, $catalog)
{
$file = str_replace('\\', '/', "$dirName/$catalog.pot");
FileHelper::createDirectory(dirname($file));
$this->stdout("Saving messages to $file...\n");
$poFile = new GettextPoFile();
$merged = [];
$hasSomethingToWrite = false;
foreach ($messages as $category => $msgs) {
$msgs = array_values(array_unique($msgs));
sort($msgs);
foreach ($msgs as $message) {
$merged[$category . chr(4) . $message] = '';
}
$this->stdout("Category \"$category\" merged.\n");
$hasSomethingToWrite = true;
}
if ($hasSomethingToWrite) {
ksort($merged);
$poFile->save($file, $merged);
$this->stdout("Translation saved.\n", Console::FG_GREEN);
} else {
$this->stdout("Nothing to save.\n", Console::FG_GREEN);
}
}
定義於: yii\console\Controller::select()
為使用者提供選項以進行選擇。輸入 '?' 將顯示可供選擇的選項列表及其說明。
public string select ( $prompt, $options = [], $default = null ) | ||
$prompt | string |
提示訊息 |
$options | array |
要從中選擇的選項的鍵值陣列 |
$default | string|null |
當使用者未提供選項時要使用的值。如果預設值為 |
回傳 | string |
使用者選擇的選項字元 |
---|
版本 | 描述 |
---|---|
2.0.49 | 新增了 $default 參數 |
public function select($prompt, $options = [], $default = null)
{
if ($this->interactive) {
return Console::select($prompt, $options, $default);
}
return $default;
}
定義於: yii\base\Controller::setView()
設定要由此控制器使用的視圖物件。
public void setView ( $view ) | ||
$view | yii\base\View|yii\web\View |
可用於渲染視圖或視圖檔案的視圖物件。 |
public function setView($view)
{
$this->_view = $view;
}
定義於: yii\base\Controller::setViewPath()
設定包含視圖檔案的目錄。
public void setViewPath ( $path ) | ||
$path | string |
視圖檔案的根目錄。 |
拋出 | yii\base\InvalidArgumentException |
如果目錄無效 |
---|
public function setViewPath($path)
{
$this->_viewPath = Yii::getAlias($path);
}
定義於: yii\console\Controller::stderr()
將字串列印到 STDERR。
您可以選擇性地使用 ANSI 代碼格式化字串,方法是使用 yii\helpers\Console 中定義的常數傳遞其他參數。
範例
$this->stderr('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
public integer|boolean stderr ( $string ) | ||
$string | string |
要列印的字串 |
回傳 | integer|boolean |
列印的位元組數,錯誤時為 false |
---|
public function stderr($string)
{
if ($this->isColorEnabled(\STDERR)) {
$args = func_get_args();
array_shift($args);
$string = Console::ansiFormat($string, $args);
}
return fwrite(\STDERR, $string);
}
定義於: yii\console\Controller::stdout()
將字串列印到 STDOUT。
您可以選擇性地使用 ANSI 代碼格式化字串,方法是使用 yii\helpers\Console 中定義的常數傳遞其他參數。
範例
$this->stdout('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
public integer|boolean stdout ( $string ) | ||
$string | string |
要列印的字串 |
回傳 | integer|boolean |
列印的位元組數,錯誤時為 false |
---|
public function stdout($string)
{
if ($this->isColorEnabled()) {
$args = func_get_args();
array_shift($args);
$string = Console::ansiFormat($string, $args);
}
return Console::stdout($string);
}
找出兩個 PHP 令牌是否相等。
protected boolean tokensEqual ( $a, $b ) | ||
$a | array|string | |
$b | array|string |
protected function tokensEqual($a, $b)
{
if (is_string($a) && is_string($b)) {
return $a === $b;
}
if (isset($a[0], $a[1], $b[0], $b[1])) {
return $a[0] === $b[0] && $a[1] == $b[1];
}
return false;
}
public void trigger ( $name, yii\base\Event $event = null ) | ||
$name | string |
事件名稱 |
$event | yii\base\Event|null |
事件實例。如果未設定,將會建立預設的 yii\base\Event 物件。 |
public function trigger($name, Event $event = null)
{
$this->ensureBehaviors();
$eventHandlers = [];
foreach ($this->_eventWildcards as $wildcard => $handlers) {
if (StringHelper::matchWildcard($wildcard, $name)) {
$eventHandlers[] = $handlers;
}
}
if (!empty($this->_events[$name])) {
$eventHandlers[] = $this->_events[$name];
}
if (!empty($eventHandlers)) {
$eventHandlers = call_user_func_array('array_merge', $eventHandlers);
if ($event === null) {
$event = new Event();
}
if ($event->sender === null) {
$event->sender = $this;
}
$event->handled = false;
$event->name = $name;
foreach ($eventHandlers as $handler) {
$event->data = $handler[1];
call_user_func($handler[0], $event);
// stop further handling if the event is handled
if ($event->handled) {
return;
}
}
}
// invoke class-level attached handlers
Event::trigger($this, $name, $event);
}
註冊 或 登入 以進行評論。