0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

EntityTrait::isEmpty() が deprecated ─ hasValue() への置換は「逆」になるため注意 - CakePHP 5.3

0
Posted at

CakePHP 5.3 で EntityTrait::isEmpty() が deprecatedになりました。

Since 5.3.0: isEmpty() is deprecated. Use hasValue() instead.

公式ドキュメントのマイグレーションガイド(2026年6月時点で日本語版はないので英語版より)には、以下のようにあります。

EntityTrait::isEmpty() is deprecated. Use hasValue() instead.

ただし、「isEmptyhasValue に単純置換」すると return が逆になるので要注意 です。


「逆」になっていること

vendor の定義(要約):

// Cake\Datasource\EntityTrait
public function isEmpty(string $field): bool   // 値が「空なら」true
public function hasValue(string $field): bool  // 値が「有るなら」true

つまり:

$entity->isEmpty($f) === !$entity->hasValue($f)

となる真偽が逆となります。


deprecation対応

// Before
if ($entity->isEmpty('title')) {
    // title が空のときの処理
}

// After(! を付けること)
if (!$entity->hasValue('title')) {
    // title が空のときの処理
}

なぜ deprecated になったのか

議論(PR #18354)で挙がっている理由は次の通りです。

  1. 冗長(逆向きの同じものが2つある)hasValue()isEmpty() の戻り値を否定しただけで、両方を持つ必要がない。どちらかに一本化しよう、という提案。
  2. isEmpty() の挙動が PHP の empty() と違って紛らわしい。CakePHP の isEmpty()/hasValue() は「フィールドに値があるか」を見るもので、PHP ネイティブの empty()0'0' も空扱い)とは判定が異なる。名前から empty() を連想すると紛らわしい。
  3. isEmpty()EntityInterface に無い。インターフェースの正規メンバーは hasValue() のみで、isEmpty() は trait にだけ存在していた。インターフェース側に揃える形で hasValue() を残した。
  4. 6.0 クリーンアップの一環6.0-Ideas wiki )。

真偽が逆なだけの重複メソッドで、しかも empty() と紛らわしく、インターフェースにも無いので、インターフェース側の hasValue() に一本化した」ということのようです。


補足: Collection::isEmpty() と混同に注意

->isEmpty( という文字列は、Entity の isEmpty($field) だけでなく Cake\Collection\Collection::isEmpty()(引数なし・非推奨ではない) もあります。

$entity->isEmpty('title');          // ← 非推奨(Entity・引数あり)
$collection->isEmpty();             // ← こちらは非推奨ではない

まとめ

  • $entity->isEmpty($f)!$entity->hasValue($f)
  • Collection::isEmpty()(引数なし)との混同に注意。
  • 6.0 で削除。5.x のうちに、否定の付け外しを確認しながら修正することを推奨。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?