クラス yii\console\controllers\MessageController
翻訳対象のメッセージをソースファイルから抽出します。
抽出されたメッセージは、設定ファイル内のformat
設定に応じて、以下のように保存できます。
- PHPメッセージソースファイル。
- ".po"ファイル。
- データベース。
使用法
- 'message/config'コマンドを使用して設定ファイルを作成します: yii message/config /path/to/myapp/messages/config.php
- 作成した設定ファイルを編集し、Webアプリケーションのニーズに合わせて調整します。
- 作成した設定を使用して、'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()。
必須。抽出されたメッセージを翻訳すべき言語コードのリスト。例えば、['zh-CN', 'de']。
ソースコードに表示されなくなったメッセージをマークするかどうか。デフォルトは true で、これらのメッセージは '@@' マークで囲まれます。
処理対象とするファイル(ディレクトリではない)を指定するパターンのリスト。空または設定されていない場合、すべてのファイルが処理されます。パターンのマッチングルールについては、helpers/FileHelper::findFiles() の説明を参照してください。「only」と「except」の両方のパターンに一致するファイル/ディレクトリは、処理されません。
生成されるPHPファイル内のメッセージ配列に使用されるDocBlock。null
の場合、デフォルトのDocBlockが使用されます。このプロパティは、$format が "php" の場合にのみ使用されます。
メッセージを含む生成されたPHPファイルのファイルヘッダー。このプロパティは、$format が "php" の場合にのみ使用されます。
ソースコードに表示されなくなったメッセージを削除するかどうか。デフォルトは false で、これらのメッセージは削除されません。
新しいメッセージを既存のメッセージとマージする際に、キーでメッセージをソートするかどうか。デフォルトは false で、新しい(未翻訳)メッセージは古い(翻訳済み)メッセージとは区別されます。
"db"形式のソースメッセージテーブルのカスタム名。
メッセージを翻訳するための関数名。これは、翻訳されるメッセージを見つけるための目印として使用されます。単一の関数名には文字列を使用し、複数の関数名には配列を使用できます。
メソッドの詳細
定義元: yii\base\Component::__call()
クラスメソッドではない名前付きメソッドを呼び出します。
このメソッドは、添付されたビヘイビアに指定された名前のメソッドがあるかどうかを確認し、あれば実行します。
このメソッドは、不明なメソッドが呼び出されたときに暗黙的に呼び出される PHP のマジックメソッドであるため、直接呼び出さないでください。
public mixed __call ( $name, $params ) | ||
$name | string |
メソッド名 |
$params | array |
メソッドのパラメータ |
return | mixed |
メソッドの戻り値 |
---|---|---|
throws | 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()");
}
定義元: yii\base\Component::__clone()
このメソッドは、既存のオブジェクトを複製してオブジェクトが作成された後に呼び出されます。
古いオブジェクトにアタッチされているため、すべてのビヘイビアを削除します。
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()
コンポーネントプロパティの値を返します。
このメソッドは、次の順序で確認し、それに応じて動作します。
- ゲッターによって定義されたプロパティ: ゲッターの結果を返します
- ビヘイビアのプロパティ: ビヘイビアのプロパティ値を返します
このメソッドは、$value = $component->property;
を実行したときに暗黙的に呼び出される PHP のマジックメソッドであるため、直接呼び出さないでください。
また、__set()も参照してください。
public mixed __get ( $name ) | ||
$name | string |
プロパティ名 |
return | mixed |
プロパティ値またはビヘイビアのプロパティの値 |
---|---|---|
throws | yii\base\UnknownPropertyException |
プロパティが定義されていない場合 |
throws | 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ではないかを確認します。
このメソッドは、次の順序で確認し、それに応じて動作します。
- セッターで定義されたプロパティ: プロパティが設定されているかどうかを返します
- ビヘイビアのプロパティ: プロパティが設定されているかどうかを返します
- 存在しないプロパティの場合は
false
を返します
このメソッドは、isset($component->property)
を実行したときに暗黙的に呼び出される PHP のマジックメソッドであるため、直接呼び出さないでください。
また、https://www.php.net/manual/en/function.isset.phpも参照してください。
public boolean __isset ( $name ) | ||
$name | string |
プロパティ名またはイベント名 |
return | 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()
コンポーネントプロパティの値を設定します。
このメソッドは、次の順序で確認し、それに応じて動作します。
- セッターで定義されたプロパティ: プロパティ値を設定します
- "on xyz"の形式のイベント: ハンドラーをイベント "xyz" にアタッチします
- "as xyz" の形式のビヘイビア: "xyz" という名前のビヘイビアをアタッチします
- ビヘイビアのプロパティ: ビヘイビアのプロパティ値を設定します
このメソッドは、$component->property = $value;
を実行したときに暗黙的に呼び出される PHP のマジックメソッドであるため、直接呼び出さないでください。
また、__get()も参照してください。
public void __set ( $name, $value ) | ||
$name | string |
プロパティ名またはイベント名 |
$value | mixed |
プロパティ値 |
throws | yii\base\UnknownPropertyException |
プロパティが定義されていない場合 |
---|---|---|
throws | 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に設定します。
このメソッドは、次の順序で確認し、それに応じて動作します。
- セッターで定義されたプロパティ: プロパティ値を null に設定します
- ビヘイビアのプロパティ: プロパティ値を null に設定します
このメソッドは直接呼び出さないでください。これはPHPのマジックメソッドであり、unset($component->property)
を実行する際に暗黙的に呼び出されます。
public void __unset ( $name ) | ||
$name | string |
プロパティ名 |
throws | 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 |
出力ファイル名またはエイリアス。 |
return | integer |
CLI終了コード |
---|---|---|
throws | 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 |
出力ファイル名またはエイリアス。 |
return | integer |
CLI終了コード |
---|---|---|
throws | 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" コマンドを使用してこのファイルを生成し、必要に応じてカスタマイズできます。 |
throws | 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()
コントローラーの外部アクションを宣言します。
このメソッドは、コントローラ用の外部アクションを宣言するためにオーバーライドされることを意図しています。アクション 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 |
アクションの戻り値。 |
return | 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()
ビヘイビアをこのコンポーネントにアタッチします。
このメソッドは、指定された構成に基づいてビヘイビアオブジェクトを作成します。その後、yii\base\Behavior::attach() メソッドを呼び出すことで、ビヘイビアオブジェクトがこのコンポーネントにアタッチされます。
detachBehavior() も参照してください。
public yii\base\Behavior attachBehavior ( $name, $behavior ) | ||
$name | string |
ビヘイビアの名前。 |
$behavior | string|array|yii\base\Behavior |
ビヘイビアの構成。これは次のいずれかです。
|
return | yii\base\Behavior |
ビヘイビアオブジェクト |
---|
public function attachBehavior($name, $behavior)
{
$this->ensureBehaviors();
return $this->attachBehaviorInternal($name, $behavior);
}
定義元: yii\base\Component::attachBehaviors()
コンポーネントにビヘイビアのリストをアタッチします。
各ビヘイビアは名前でインデックスが付けられ、yii\base\Behavior オブジェクト、ビヘイビアクラスを指定する文字列、またはビヘイビアを作成するための構成配列である必要があります。
attachBehavior() も参照してください。
public void attachBehaviors ( $behaviors ) | ||
$behaviors | array |
コンポーネントにアタッチするビヘイビアのリスト |
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 |
実行されるアクション。 |
return | 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()
このコンポーネントが動作するビヘイビアのリストを返します。
子クラスは、このメソッドをオーバーライドして、動作させたいビヘイビアを指定できます。
このメソッドの戻り値は、ビヘイビア名でインデックス付けされたビヘイビアオブジェクトまたは構成の配列である必要があります。ビヘイビア構成は、ビヘイビアクラスを指定する文字列、または次の構造の配列のいずれかになります。
'behaviorName' => [
'class' => 'BehaviorClass',
'property1' => 'value1',
'property2' => 'value2',
]
ビヘイビアクラスは yii\base\Behavior から拡張する必要があることに注意してください。ビヘイビアは、名前を使用するか匿名でアタッチできます。名前が配列キーとして使用されている場合、この名前を使用して、後で getBehavior() を使用してビヘイビアを取得したり、detachBehavior() を使用してデタッチしたりできます。匿名のビヘイビアは、取得またはデタッチできません。
このメソッドで宣言されたビヘイビアは、コンポーネントに自動的に(必要に応じて)アタッチされます。
public array behaviors ( ) | ||
return | array |
ビヘイビアの設定。 |
---|
public function behaviors()
{
return [];
}
定義元: yii\console\Controller::bindActionParams()
アクションにパラメーターをバインドします。
このメソッドは、与えられたパラメータで実行を開始するときに、yii\base\Action によって呼び出されます。このメソッドは最初に、アクションで利用可能な options をパラメータと結合します。次に、与えられた引数を検証します。
public array bindActionParams ( $action, $params ) | ||
$action | yii\base\Action |
パラメータと結合されるアクション |
$params | array |
アクションに結合されるパラメータ |
return | array |
アクションが実行できる有効なパラメータ。 |
---|---|---|
throws | 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 |
リクエストされたパラメータを持つ配列。この関数は特定のキーを書き込むことができます。 |
throws | yii\base\ErrorException |
必要なサービスをロードできない場合。 |
---|---|---|
throws | yii\base\InvalidConfigException |
DI設定にエラーがある場合にスローされます。 |
throws | 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()
プロパティが読み取り可能かどうかを示す値を返します。
プロパティは、以下の場合に読み取り可能です。
- クラスが指定された名前に関連付けられたゲッターメソッドを持っている場合(この場合、プロパティ名は大小文字を区別しません)。
- クラスが指定された名前のメンバ変数を持っている場合(
$checkVars
がtrueの場合)。 - アタッチされたビヘイビアが、指定された名前の読み取り可能なプロパティを持っている場合(
$checkBehaviors
がtrueの場合)。
canSetProperty()も参照してください。
public boolean canGetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
プロパティ名 |
$checkVars | boolean |
メンバ変数をプロパティとして扱うかどうか |
$checkBehaviors | boolean |
ビヘイビアのプロパティをこのコンポーネントのプロパティとして扱うかどうか |
return | 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()
プロパティが設定可能かどうかを示す値を返します。
プロパティは、以下の場合に書き込み可能です。
- クラスが指定された名前に関連付けられたセッターメソッドを持っている場合(この場合、プロパティ名は大小文字を区別しません)。
- クラスが指定された名前のメンバ変数を持っている場合(
$checkVars
がtrueの場合)。 - アタッチされたビヘイビアが、指定された名前の書き込み可能なプロパティを持っている場合(
$checkBehaviors
がtrueの場合)。
canGetProperty()も参照してください。
public boolean canSetProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
プロパティ名 |
$checkVars | boolean |
メンバ変数をプロパティとして扱うかどうか |
$checkBehaviors | boolean |
ビヘイビアのプロパティをこのコンポーネントのプロパティとして扱うかどうか |
return | 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 ( ) | ||
return | 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 |
選択が行われなかった場合に返される値。 |
return | 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。 |
return | 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()
コンポーネントからビヘイビアをデタッチします。
ビヘイビアの yii\base\Behavior::detach() メソッドが呼び出されます。
public yii\base\Behavior|null detachBehavior ( $name ) | ||
$name | string |
ビヘイビアの名前。 |
return | 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 |
処理されるトークン。 |
$translatorTokens | array |
トランスレータートークン。 |
$ignoreCategories | array |
無視するメッセージカテゴリ。 |
return | 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 |
レイアウトファイルをレンダリングするためのビューオブジェクト。 |
return | string|boolean |
レイアウトファイルのパス。または、レイアウトが不要な場合は false。render() で、このパラメータの指定方法を参照してください。 |
---|---|---|
throws | 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, この引数の説明
デフォルトの実装では、アクションメソッドに対応するパラメータのリフレクションまたはDocBlockから抽出されたヘルプ情報が返されます。
public array getActionArgsHelp ( $action ) | ||
$action | yii\base\Action |
アクションインスタンス |
return | 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 |
ヘルプを取得するアクション |
return | string |
指定されたアクションの詳細なヘルプ情報。 |
---|
public function getActionHelp($action)
{
return $this->parseDocCommentDetail($this->getActionMethodReflection($action));
}
定義元: yii\console\Controller::getActionHelpSummary()
指定されたアクションを説明する1行の短い要約を返します。
public string getActionHelpSummary ( $action ) | ||
$action | yii\base\Action |
概要を取得するアクション |
return | string |
指定されたアクションを説明する1行の短い要約。 |
---|
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, この引数のコメント
デフォルトの実装では、アクションオプションに対応するプロパティのドキュメントコメントから抽出されたヘルプ情報が返されます。
public array getActionOptionsHelp ( $action ) | ||
$action | yii\base\Action | |
return | 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 |
ビヘイビアの名前 |
return | 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 ( ) | ||
return | yii\base\Behavior[] |
このコンポーネントにアタッチされたビヘイビアのリスト |
---|
public function getBehaviors()
{
$this->ensureBehaviors();
return $this->_behaviors;
}
定義元: yii\console\Controller::getHelp()
このコントローラーのヘルプ情報を返します。
このメソッドをオーバーライドして、カスタマイズされたヘルプを返すことができます。デフォルトの実装では、PHPDocコメントから取得したヘルプ情報が返されます。
public string getHelp ( ) |
public function getHelp()
{
return $this->parseDocCommentDetail(new \ReflectionClass($this));
}
定義元: yii\console\Controller::getHelpSummary()
このコントローラーを説明する1行の短い要約を返します。
このメソッドをオーバーライドして、カスタマイズされた概要を返すことができます。デフォルトの実装では、PHPDocコメントの最初の行を返します。
public string getHelpSummary ( ) |
public function getHelpSummary()
{
return $this->parseDocCommentSummary(new \ReflectionClass($this));
}
最初に見つかった非char 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';
}
定義元: yii\base\Controller::getModules()
このコントローラーのすべての先祖モジュールを返します。
配列の最初のモジュールは最も外側のモジュール (つまり、アプリケーションインスタンス) で、最後のモジュールは最も内側のモジュールです。
public yii\base\Module[] getModules ( ) | ||
return | 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 |
return | 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 ( ) | ||
return | array |
渡されたオプションに対応するプロパティ |
---|
public function getPassedOptionValues()
{
$properties = [];
foreach ($this->_passedOptions as $property) {
$properties[$property] = $this->$property;
}
return $properties;
}
定義元: yii\console\Controller::getPassedOptions()
実行中に渡された有効なオプションの名前を返します。
public array getPassedOptions ( ) | ||
return | array |
実行中に渡されたオプションの名前 |
---|
public function getPassedOptions()
{
return $this->_passedOptions;
}
定義元: yii\base\Controller::getRoute()
現在のリクエストのルートを返します。
public string getRoute ( ) | ||
return | string |
現在のリクエストのルート(モジュールID、コントローラーID、アクションID)。 |
---|
public function getRoute()
{
return $this->action !== null ? $this->action->getUniqueId() : $this->getUniqueId();
}
定義元: yii\base\Controller::getUniqueId()
コントローラーの一意のIDを返します。
public string getUniqueId ( ) | ||
return | 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 ( ) | ||
return | 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()
このコントローラーのビューファイルを含むディレクトリを返します。
デフォルトの実装では、コントローラの $id と同じ名前のディレクトリを、$module の $viewPath ディレクトリの下に返します。
public string getViewPath ( ) | ||
return | 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 |
イベント名 |
return | 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 |
ビヘイビアのメソッドをこのコンポーネントのメソッドとして扱うかどうか |
return | 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()
このコンポーネントにプロパティが定義されているかどうかを示す値を返します。
プロパティが定義されている場合、
- クラスに指定された名前に関連付けられたゲッターまたはセッターメソッドがある (この場合、プロパティ名は大文字小文字を区別しません)。
- クラスが指定された名前のメンバ変数を持っている場合(
$checkVars
がtrueの場合)。 - アタッチされたビヘイビアに指定された名前のプロパティがある (
$checkBehaviors
が true の場合)。
参照
public boolean hasProperty ( $name, $checkVars = true, $checkBehaviors = true ) | ||
$name | string |
プロパティ名 |
$checkVars | boolean |
メンバ変数をプロパティとして扱うかどうか |
$checkBehaviors | boolean |
ビヘイビアのプロパティをこのコンポーネントのプロパティとして扱うかどうか |
return | 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 | |
throws | 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;
}
}
このメソッドは、$ignoreCategories配列に従って、$categoryが無視されるかどうかを確認します。
例
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カラーが有効かどうかを示す値を返します。
ANSI カラーは、$color が true に設定されているか、設定されておらず、ターミナルが ANSI カラーをサポートしている場合にのみ有効になります。
public boolean isColorEnabled ( $stream = \STDOUT ) | ||
$stream | resource |
チェックするストリーム。 |
return | boolean |
出力で ANSI スタイルを有効にするかどうか。 |
---|
public function isColorEnabled($stream = \STDOUT)
{
return $this->color === null ? Console::streamSupportsAnsiColors($stream) : $this->color;
}
このコンポーネントから既存のイベントハンドラーをデタッチします。
このメソッドは、on() の反対です。
注意: イベント名にワイルドカードパターンが渡された場合、このワイルドカードで登録されたハンドラのみが削除され、このワイルドカードに一致するプレーンな名前で登録されたハンドラは残ります。
on() も参照してください。
public boolean off ( $name, $handler = null ) | ||
$name | string |
イベント名 |
$handler | callable|null |
削除するイベントハンドラ。null の場合は、指定されたイベントにアタッチされたすべてのハンドラが削除されます。 |
return | 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 ( ) | ||
return | 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 |
return | 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()
ドックブロックから完全な説明を返します。
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()
ドックブロックの最初の行を返します。
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 |
コメントブロック |
return | 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 |
入力値を検証するためのオプション
validator関数を使ったpromptメソッドの使用例。
|
return | 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 の下で検索されます。
適用するレイアウトを決定するために、次の2つのステップが実行されます
- 最初のステップでは、レイアウト名とコンテキストモジュールを決定します
- $layout が文字列として指定されている場合は、それをレイアウト名として使用し、$module をコンテキストモジュールとして使用します。
- $layout が null の場合は、このコントローラのすべての上位モジュールを検索し、layout が null でない最初のモジュールを見つけます。レイアウトと対応するモジュールは、それぞれレイアウト名とコンテキストモジュールとして使用されます。そのようなモジュールが見つからない場合、または対応するレイアウトが文字列でない場合は、適用可能なレイアウトがないことを意味するfalseを返します。
- 2番目のステップでは、以前に見つかったレイアウト名とコンテキストモジュールに従って、実際のレイアウトファイルを決定します。レイアウト名は次のようになります
- パスエイリアス (例: "@app/views/layouts/main")
- 絶対パス (例: "/main"): レイアウト名はスラッシュで始まります。実際のレイアウトファイルは、アプリケーションのレイアウトパスの下で検索されます。
- 相対パス (例: "main"): 実際のレイアウトファイルは、コンテキストモジュールのレイアウトパスの下で検索されます。
レイアウト名にファイル拡張子が含まれていない場合は、デフォルトの.php
が使用されます。
public string render ( $view, $params = [] ) | ||
$view | string |
ビュー名。 |
$params | array |
ビューで利用可能にするパラメータ(名前と値のペア)。これらのパラメータはレイアウトでは利用できません。 |
return | string |
レンダリング結果。 |
---|---|---|
throws | 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 |
レンダリングされる静的な文字列 |
return | 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 |
ビューで利用可能にするパラメータ(名前と値のペア)。 |
return | string |
レンダリング結果。 |
---|---|---|
throws | yii\base\InvalidArgumentException |
ビューファイルが存在しない場合。 |
public function renderFile($file, $params = [])
{
return $this->getView()->renderFile($file, $params, $this);
}
定義元: yii\base\Controller::renderPartial()
レイアウトを適用せずにビューをレンダリングします。
このメソッドは、レイアウトを適用しないという点で render() とは異なります。
public string renderPartial ( $view, $params = [] ) | ||
$view | string |
ビュー名。ビュー名の指定方法については、render() を参照してください。 |
$params | array |
ビューで利用可能にするパラメータ(名前と値のペア)。 |
return | string |
レンダリング結果。 |
---|---|---|
throws | 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 |
アクションに渡すパラメータ。 |
return | 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 |
アクションに渡すパラメータ(名前と値のペア)。 |
return | integer |
アクションの実行ステータス。0は正常、他の値は異常を意味します。 |
---|---|---|
throws | yii\base\InvalidRouteException |
要求されたアクションIDが正常にアクションに解決できない場合。 |
throws | 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 |
廃止された翻訳をマークするかどうか |
return | 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 |
ユーザーがオプションを選択しなかった場合に使用する値。デフォルトが |
return | 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 |
ビューファイルのルートディレクトリ。 |
throws | yii\base\InvalidArgumentException |
ディレクトリが無効な場合 |
---|
public function setViewPath($path)
{
$this->_viewPath = Yii::getAlias($path);
}
定義元: yii\console\Controller::stderr()
文字列をSTDERRに出力します。
オプションで、yii\helpers\Console で定義された定数を使用し追加のパラメータを渡すことで、ANSIコードで文字列をフォーマットできます。
例
$this->stderr('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
public integer|boolean stderr ( $string ) | ||
$string | string |
出力する文字列 |
return | 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に出力します。
オプションで、yii\helpers\Console で定義された定数を使用し追加のパラメータを渡すことで、ANSIコードで文字列をフォーマットできます。
例
$this->stdout('This will be red and underlined.', Console::FG_RED, Console::UNDERLINE);
public integer|boolean stdout ( $string ) | ||
$string | string |
出力する文字列 |
return | 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);
}
2つの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;
}
定義元: yii\base\Component::trigger()
イベントをトリガーします。
このメソッドはイベントの発生を表します。クラスレベルのハンドラを含む、イベントにアタッチされたすべてのハンドラを呼び出します。
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);
}
サインアップ または ログイン してコメントしてください。