string型を変換してsaveする

converterを作ってみた。

<?php
class propelConverter
{
  public static function execute($obj, $function, $type = 'string')
  {
    if (!$obj->isModified()) {
      return;
    }
    $peer = $obj->getPeer();
    $tMap = $peer->getTableMap();
    $table = $tMap->getName();
    foreach ($tMap->getColumns() as $column) {
      if ($column->getType() != $type) { continue; }

      $columnName = $column->getColumnName();
      $col = $table.'.'.$columnName;
      if (!$obj->isColumnModified($col)) {
        continue;
      }
      $str = $obj->getByName($col, BasePeer::TYPE_COLNAME);
      if (is_null($str)) { continue; }

      $str = call_user_func($function, $str);
      $obj->setByName($col, $str, BasePeer::TYPE_COLNAME);
    }
  }
}

変更があるcolumnのみ実行するようにしてみた。
typeがstring以外の使い道がない気がするけど、念のため指定できるようにした。


使い方。hogeテーブルのstring型の絵文字を変換してsaveするとか

<?php
class Hoge extends BaseHoge
{
  public function save($con = null)
  {
    propelConverter::execute($this, '絵文字を変換する関数');
    return parent::save($con);
  }
}

※追記
nullにupdateできなくなってしまっていたので、以下を追加

<?php
      if (is_null($str)) { continue; }