From 786e8646303d0e3a02f4a5d63a0ea5bb501eb832 Mon Sep 17 00:00:00 2001 From: Koen Punt Date: Tue, 9 Dec 2014 12:01:43 +0100 Subject: [PATCH 1/2] Code quality using PHP_CodeSniffer omit use of call_user_func_array remove error suppression --- ActiveRecord.php | 98 ++++----- composer.json | 3 +- lib/Cache.php | 5 +- lib/CallBack.php | 17 +- lib/Column.php | 390 ++++++++++++++++----------------- lib/Config.php | 12 +- lib/Connection.php | 5 +- lib/DateTime.php | 12 +- lib/Exceptions.php | 4 +- lib/Expressions.php | 384 ++++++++++++++++---------------- lib/Inflector.php | 245 +++++++++++---------- lib/Model.php | 195 +++++++++-------- lib/Relationship.php | 36 +-- lib/SQLBuilder.php | 36 +-- lib/Serialization.php | 76 +++---- lib/Singleton.php | 3 +- lib/Table.php | 98 +++++---- lib/Utils.php | 280 +++++++++++------------ lib/Validations.php | 32 ++- lib/adapters/MysqlAdapter.php | 11 +- lib/adapters/OciAdapter.php | 44 ++-- lib/adapters/PgsqlAdapter.php | 12 +- lib/adapters/SqliteAdapter.php | 17 +- lib/cache/Memcache.php | 4 +- ruleset.xml | 46 ++++ 25 files changed, 1093 insertions(+), 972 deletions(-) create mode 100644 ruleset.xml diff --git a/ActiveRecord.php b/ActiveRecord.php index 17b325703..5de1bfb0b 100644 --- a/ActiveRecord.php +++ b/ActiveRecord.php @@ -1,49 +1,49 @@ -get_model_directory(); - $root = realpath(isset($path) ? $path : '.'); - - if (($namespaces = ActiveRecord\get_namespaces($class_name))) - { - $class_name = array_pop($namespaces); - $directories = array(); - - foreach ($namespaces as $directory) - $directories[] = $directory; - - $root .= DIRECTORY_SEPARATOR . implode($directories, DIRECTORY_SEPARATOR); - } - - $file = "$root/$class_name.php"; - - if (file_exists($file)) - require_once $file; -} \ No newline at end of file +get_model_directory(); + $root = realpath(isset($path) ? $path : '.'); + + if (($namespaces = ActiveRecord\get_namespaces($class_name))) + { + $class_name = array_pop($namespaces); + $directories = array(); + + foreach ($namespaces as $directory) + $directories[] = $directory; + + $root .= DIRECTORY_SEPARATOR . implode($directories, DIRECTORY_SEPARATOR); + } + + $file = "$root/$class_name.php"; + + if (file_exists($file)) + require_once $file; +} diff --git a/composer.json b/composer.json index a4eed119c..f06c78199 100644 --- a/composer.json +++ b/composer.json @@ -11,7 +11,8 @@ "require-dev": { "phpunit/phpunit": "3.7.*", "pear/pear_exception": "1.0.*@dev", - "pear/Log": "dev-master" + "pear/Log": "dev-master", + "squizlabs/php_codesniffer": "2.*" }, "autoload": { "files": [ "ActiveRecord.php" ] diff --git a/lib/Cache.php b/lib/Cache.php index 958c007a9..4383f11b4 100644 --- a/lib/Cache.php +++ b/lib/Cache.php @@ -50,7 +50,7 @@ public static function initialize($url, $options=array()) else static::$adapter = null; - static::$options = array_merge(array('expire' => 30, 'namespace' => ''),$options); + static::$options = array_merge(array('expire' => 30, 'namespace' => ''), $options); } public static function flush() @@ -110,6 +110,7 @@ public static function delete($key) private static function get_namespace() { - return (isset(static::$options['namespace']) && strlen(static::$options['namespace']) > 0) ? (static::$options['namespace'] . "::") : ""; + return (isset(static::$options['namespace']) && strlen(static::$options['namespace']) > 0) + ? (static::$options['namespace'] . '::') : ''; } } diff --git a/lib/CallBack.php b/lib/CallBack.php index 3aaf50f9f..f875e3091 100644 --- a/lib/CallBack.php +++ b/lib/CallBack.php @@ -114,20 +114,20 @@ public function __construct($model_class_name) foreach (static::$VALID_CALLBACKS as $name) { // look for explicitly defined static callback - if (($definition = $this->klass->getStaticPropertyValue($name,null))) + if (($definition = $this->klass->getStaticPropertyValue($name, null))) { if (!is_array($definition)) $definition = array($definition); foreach ($definition as $method_name) - $this->register($name,$method_name); + $this->register($name, $method_name); } // implicit callbacks that don't need to have a static definition // simply define a method named the same as something in $VALID_CALLBACKS // and the callback is auto-registered elseif ($this->klass->hasMethod($name)) - $this->register($name,$name); + $this->register($name, $name); } } @@ -168,10 +168,11 @@ public function invoke($model, $name, $must_exist=true) else $registry = $this->registry[$name]; - $first = substr($name,0,6); + $first = substr($name, 0, 6); // starts with /(after|before)_(create|update)/ - if (($first == 'after_' || $first == 'before') && (($second = substr($name,7,5)) == 'creat' || $second == 'updat' || $second == 'reate' || $second == 'pdate')) + if (($first == 'after_' || $first == 'before') + && (($second = substr($name, 7, 5)) == 'creat' || $second == 'updat' || $second == 'reate' || $second == 'pdate')) { $temporal_save = str_replace(array('create', 'update'), 'save', $name); @@ -215,7 +216,7 @@ public function register($name, $closure_or_method_name=null, $options=array()) if (!$closure_or_method_name) $closure_or_method_name = $name; - if (!in_array($name,self::$VALID_CALLBACKS)) + if (!in_array($name, self::$VALID_CALLBACKS)) throw new ActiveRecordException("Invalid callback: $name"); if (!($closure_or_method_name instanceof Closure)) @@ -228,8 +229,8 @@ public function register($name, $closure_or_method_name=null, $options=array()) if ($this->klass->hasMethod($closure_or_method_name)) { // Method is private or protected - throw new ActiveRecordException("Callback methods need to be public (or anonymous closures). " . - "Please change the visibility of " . $this->klass->getName() . "->" . $closure_or_method_name . "()"); + throw new ActiveRecordException("Callback methods need to be public (or anonymous closures). + Please change the visibility of {$this->klass->getName()}->{$closure_or_method_name}()"); } else { diff --git a/lib/Column.php b/lib/Column.php index 6cb45c1c2..d80112d1f 100644 --- a/lib/Column.php +++ b/lib/Column.php @@ -1,195 +1,195 @@ - self::DATETIME, - 'timestamp' => self::DATETIME, - 'date' => self::DATE, - 'time' => self::TIME, - - 'tinyint' => self::INTEGER, - 'smallint' => self::INTEGER, - 'mediumint' => self::INTEGER, - 'int' => self::INTEGER, - 'bigint' => self::INTEGER, - - 'float' => self::DECIMAL, - 'double' => self::DECIMAL, - 'numeric' => self::DECIMAL, - 'decimal' => self::DECIMAL, - 'dec' => self::DECIMAL); - - /** - * The true name of this column. - * @var string - */ - public $name; - - /** - * The inflected name of this columns .. hyphens/spaces will be => _. - * @var string - */ - public $inflected_name; - - /** - * The type of this column: STRING, INTEGER, ... - * @var integer - */ - public $type; - - /** - * The raw database specific type. - * @var string - */ - public $raw_type; - - /** - * The maximum length of this column. - * @var int - */ - public $length; - - /** - * True if this column allows null. - * @var boolean - */ - public $nullable; - - /** - * True if this column is a primary key. - * @var boolean - */ - public $pk; - - /** - * The default value of the column. - * @var mixed - */ - public $default; - - /** - * True if this column is set to auto_increment. - * @var boolean - */ - public $auto_increment; - - /** - * Name of the sequence to use for this column if any. - * @var boolean - */ - public $sequence; - - /** - * Cast a value to an integer type safely - * - * This will attempt to cast a value to an integer, - * unless its detected that the casting will cause - * the number to overflow or lose precision, in which - * case the number will be returned as a string, so - * that large integers (BIGINTS, unsigned INTS, etc) - * can still be stored without error - * - * This would ideally be done with bcmath or gmp, but - * requiring a new PHP extension for a bug-fix is a - * little ridiculous - * - * @param mixed $value The value to cast - * @return int|string type-casted value - */ - public static function castIntegerSafely($value) - { - if (is_int($value)) - return $value; - - // Its just a decimal number - elseif (is_numeric($value) && floor($value) != $value) - return (int) $value; - - // If adding 0 to a string causes a float conversion, - // we have a number over PHP_INT_MAX - elseif (is_string($value) && is_float($value + 0)) - return (string) $value; - - // If a float was passed and its greater than PHP_INT_MAX - // (which could be wrong due to floating point precision) - // We'll also check for equal to (>=) in case the precision - // loss creates an overflow on casting - elseif (is_float($value) && $value >= PHP_INT_MAX) - return number_format($value, 0, '', ''); - - return (int) $value; - } - - /** - * Casts a value to the column's type. - * - * @param mixed $value The value to cast - * @param Connection $connection The Connection this column belongs to - * @return mixed type-casted value - */ - public function cast($value, $connection) - { - if ($value === null) - return null; - - switch ($this->type) - { - case self::STRING: return (string)$value; - case self::INTEGER: return static::castIntegerSafely($value); - case self::DECIMAL: return (double)$value; - case self::DATETIME: - case self::DATE: - if (!$value) - return null; - - if ($value instanceof DateTime) - return $value; - - if ($value instanceof \DateTime) - return new DateTime($value->format('Y-m-d H:i:s T')); - - return $connection->string_to_datetime($value); - } - return $value; - } - - /** - * Sets the $type member variable. - * @return mixed - */ - public function map_raw_type() - { - if ($this->raw_type == 'integer') - $this->raw_type = 'int'; - - if (array_key_exists($this->raw_type,self::$TYPE_MAPPING)) - $this->type = self::$TYPE_MAPPING[$this->raw_type]; - else - $this->type = self::STRING; - - return $this->type; - } -} + self::DATETIME, + 'timestamp' => self::DATETIME, + 'date' => self::DATE, + 'time' => self::TIME, + + 'tinyint' => self::INTEGER, + 'smallint' => self::INTEGER, + 'mediumint' => self::INTEGER, + 'int' => self::INTEGER, + 'bigint' => self::INTEGER, + + 'float' => self::DECIMAL, + 'double' => self::DECIMAL, + 'numeric' => self::DECIMAL, + 'decimal' => self::DECIMAL, + 'dec' => self::DECIMAL); + + /** + * The true name of this column. + * @var string + */ + public $name; + + /** + * The inflected name of this columns .. hyphens/spaces will be => _. + * @var string + */ + public $inflected_name; + + /** + * The type of this column: STRING, INTEGER, ... + * @var integer + */ + public $type; + + /** + * The raw database specific type. + * @var string + */ + public $raw_type; + + /** + * The maximum length of this column. + * @var int + */ + public $length; + + /** + * True if this column allows null. + * @var boolean + */ + public $nullable; + + /** + * True if this column is a primary key. + * @var boolean + */ + public $pk; + + /** + * The default value of the column. + * @var mixed + */ + public $default; + + /** + * True if this column is set to auto_increment. + * @var boolean + */ + public $auto_increment; + + /** + * Name of the sequence to use for this column if any. + * @var boolean + */ + public $sequence; + + /** + * Cast a value to an integer type safely + * + * This will attempt to cast a value to an integer, + * unless its detected that the casting will cause + * the number to overflow or lose precision, in which + * case the number will be returned as a string, so + * that large integers (BIGINTS, unsigned INTS, etc) + * can still be stored without error + * + * This would ideally be done with bcmath or gmp, but + * requiring a new PHP extension for a bug-fix is a + * little ridiculous + * + * @param mixed $value The value to cast + * @return int|string type-casted value + */ + public static function castIntegerSafely($value) + { + if (is_int($value)) + return $value; + + // Its just a decimal number + elseif (is_numeric($value) && floor($value) != $value) + return (int)$value; + + // If adding 0 to a string causes a float conversion, + // we have a number over PHP_INT_MAX + elseif (is_string($value) && is_float($value + 0)) + return (string)$value; + + // If a float was passed and its greater than PHP_INT_MAX + // (which could be wrong due to floating point precision) + // We'll also check for equal to (>=) in case the precision + // loss creates an overflow on casting + elseif (is_float($value) && $value >= PHP_INT_MAX) + return number_format($value, 0, '', ''); + + return (int)$value; + } + + /** + * Casts a value to the column's type. + * + * @param mixed $value The value to cast + * @param Connection $connection The Connection this column belongs to + * @return mixed type-casted value + */ + public function cast($value, $connection) + { + if ($value === null) + return null; + + switch ($this->type) + { + case self::STRING: return (string)$value; + case self::INTEGER: return static::castIntegerSafely($value); + case self::DECIMAL: return (double)$value; + case self::DATETIME: + case self::DATE: + if (!$value) + return null; + + if ($value instanceof DateTime) + return $value; + + if ($value instanceof \DateTime) + return new DateTime($value->format('Y-m-d H:i:s T')); + + return $connection->string_to_datetime($value); + } + return $value; + } + + /** + * Sets the $type member variable. + * @return mixed + */ + public function map_raw_type() + { + if ($this->raw_type == 'integer') + $this->raw_type = 'int'; + + if (array_key_exists($this->raw_type, self::$TYPE_MAPPING)) + $this->type = self::$TYPE_MAPPING[$this->raw_type]; + else + $this->type = self::STRING; + + return $this->type; + } +} diff --git a/lib/Config.php b/lib/Config.php index 5038af257..59a627318 100644 --- a/lib/Config.php +++ b/lib/Config.php @@ -98,7 +98,7 @@ class Config extends Singleton * $cfg = ActiveRecord\Config::instance(); * $cfg->set_model_directory('/path/to/your/model_directory'); * $cfg->set_connections(array('development' => - * 'mysql://username:password@localhost/database_name')); + * 'mysql://username:password@localhost/database_name')); * * * @param Closure $initializer A closure @@ -164,7 +164,7 @@ public function get_connection($name) */ public function get_default_connection_string() { - return array_key_exists($this->default_connection,$this->connections) ? + return array_key_exists($this->default_connection, $this->connections) ? $this->connections[$this->default_connection] : null; } @@ -267,7 +267,8 @@ public function get_logger() */ public function get_date_format() { - trigger_error('Use ActiveRecord\Serialization::$DATETIME_FORMAT. Config::get_date_format() has been deprecated.', E_USER_DEPRECATED); + trigger_error('Use ActiveRecord\Serialization::$DATETIME_FORMAT. + Config::get_date_format() has been deprecated.', E_USER_DEPRECATED); return Serialization::$DATETIME_FORMAT; } @@ -276,7 +277,8 @@ public function get_date_format() */ public function set_date_format($format) { - trigger_error('Use ActiveRecord\Serialization::$DATETIME_FORMAT. Config::set_date_format() has been deprecated.', E_USER_DEPRECATED); + trigger_error('Use ActiveRecord\Serialization::$DATETIME_FORMAT. + Config::set_date_format() has been deprecated.', E_USER_DEPRECATED); Serialization::$DATETIME_FORMAT = $format; } @@ -298,6 +300,6 @@ public function set_date_format($format) */ public function set_cache($url, $options=array()) { - Cache::initialize($url,$options); + Cache::initialize($url, $options); } } \ No newline at end of file diff --git a/lib/Connection.php b/lib/Connection.php index c32311bcb..13165d1cc 100644 --- a/lib/Connection.php +++ b/lib/Connection.php @@ -164,10 +164,11 @@ private static function load_adapter_class($adapter) */ public static function parse_connection_url($connection_url) { - $url = @parse_url($connection_url); + $url = parse_url($connection_url); if (!isset($url['host'])) - throw new DatabaseException('Database host must be specified in the connection string. If you want to specify an absolute filename, use e.g. sqlite://unix(/path/to/file)'); + throw new DatabaseException('Database host must be specified in the connection string. + If you want to specify an absolute filename, use e.g. sqlite://unix(/path/to/file)'); $info = new \stdClass(); $info->protocol = $url['scheme']; diff --git a/lib/DateTime.php b/lib/DateTime.php index 9b488236b..b539926ba 100644 --- a/lib/DateTime.php +++ b/lib/DateTime.php @@ -127,24 +127,24 @@ private function flag_dirty() public function setDate($year, $month, $day) { $this->flag_dirty(); - call_user_func_array(array($this,'parent::setDate'),func_get_args()); + parent::setDate($year, $month, $day); } - public function setISODate($year, $week , $day=null) + public function setISODate($year, $week, $day=1) { $this->flag_dirty(); - call_user_func_array(array($this,'parent::setISODate'),func_get_args()); + parent::setISODate($year, $week, $day); } - public function setTime($hour, $minute, $second=null) + public function setTime($hour, $minute, $second=0) { $this->flag_dirty(); - call_user_func_array(array($this,'parent::setTime'),func_get_args()); + parent::setTime($hour, $minute, $second); } public function setTimestamp($unixtimestamp) { $this->flag_dirty(); - call_user_func_array(array($this,'parent::setTimestamp'),func_get_args()); + parent::setTimestamp($unixtimestamp); } } \ No newline at end of file diff --git a/lib/Exceptions.php b/lib/Exceptions.php index 3e2e05173..be5cda400 100644 --- a/lib/Exceptions.php +++ b/lib/Exceptions.php @@ -32,13 +32,13 @@ public function __construct($adapter_or_string_or_mystery) if ($adapter_or_string_or_mystery instanceof Connection) { parent::__construct( - join(", ",$adapter_or_string_or_mystery->connection->errorInfo()), + join(", ", $adapter_or_string_or_mystery->connection->errorInfo()), intval($adapter_or_string_or_mystery->connection->errorCode())); } elseif ($adapter_or_string_or_mystery instanceof \PDOStatement) { parent::__construct( - join(", ",$adapter_or_string_or_mystery->errorInfo()), + join(", ", $adapter_or_string_or_mystery->errorInfo()), intval($adapter_or_string_or_mystery->errorCode())); } else diff --git a/lib/Expressions.php b/lib/Expressions.php index 3fa2962fa..cf51b0ce6 100644 --- a/lib/Expressions.php +++ b/lib/Expressions.php @@ -1,192 +1,192 @@ -connection = $connection; - - if (is_array($expressions)) - { - $glue = func_num_args() > 2 ? func_get_arg(2) : ' AND '; - list($expressions,$values) = $this->build_sql_from_hash($expressions,$glue); - } - - if ($expressions != '') - { - if (!$values) - $values = array_slice(func_get_args(),2); - - $this->values = $values; - $this->expressions = $expressions; - } - } - - /** - * Bind a value to the specific one based index. There must be a bind marker - * for each value bound or to_s() will throw an exception. - */ - public function bind($parameter_number, $value) - { - if ($parameter_number <= 0) - throw new ExpressionsException("Invalid parameter index: $parameter_number"); - - $this->values[$parameter_number-1] = $value; - } - - public function bind_values($values) - { - $this->values = $values; - } - - /** - * Returns all the values currently bound. - */ - public function values() - { - return $this->values; - } - - /** - * Returns the connection object. - */ - public function get_connection() - { - return $this->connection; - } - - /** - * Sets the connection object. It is highly recommended to set this so we can - * use the adapter's native escaping mechanism. - * - * @param string $connection a Connection instance - */ - public function set_connection($connection) - { - $this->connection = $connection; - } - - public function to_s($substitute=false, &$options=null) - { - if (!$options) $options = array(); - - $values = array_key_exists('values',$options) ? $options['values'] : $this->values; - - $ret = ""; - $replace = array(); - $num_values = count($values); - $len = strlen($this->expressions); - $quotes = 0; - - for ($i=0,$n=strlen($this->expressions),$j=0; $i<$n; ++$i) - { - $ch = $this->expressions[$i]; - - if ($ch == self::ParameterMarker) - { - if ($quotes % 2 == 0) - { - if ($j > $num_values-1) - throw new ExpressionsException("No bound parameter for index $j"); - - $ch = $this->substitute($values,$substitute,$i,$j++); - } - } - elseif ($ch == '\'' && $i > 0 && $this->expressions[$i-1] != '\\') - ++$quotes; - - $ret .= $ch; - } - return $ret; - } - - private function build_sql_from_hash(&$hash, $glue) - { - $sql = $g = ""; - - foreach ($hash as $name => $value) - { - if ($this->connection) - $name = $this->connection->quote_name($name); - - if (is_array($value)) - $sql .= "$g$name IN(?)"; - elseif (is_null($value)) - $sql .= "$g$name IS ?"; - else - $sql .= "$g$name=?"; - - $g = $glue; - } - return array($sql,array_values($hash)); - } - - private function substitute(&$values, $substitute, $pos, $parameter_index) - { - $value = $values[$parameter_index]; - - if (is_array($value)) - { - $value_count = count($value); - - if ($value_count === 0) - if ($substitute) - return 'NULL'; - else - return self::ParameterMarker; - - if ($substitute) - { - $ret = ''; - - for ($i=0, $n=$value_count; $i<$n; ++$i) - $ret .= ($i > 0 ? ',' : '') . $this->stringify_value($value[$i]); - - return $ret; - } - return join(',',array_fill(0,$value_count,self::ParameterMarker)); - } - - if ($substitute) - return $this->stringify_value($value); - - return $this->expressions[$pos]; - } - - private function stringify_value($value) - { - if (is_null($value)) - return "NULL"; - - return is_string($value) ? $this->quote_string($value) : $value; - } - - private function quote_string($value) - { - if ($this->connection) - return $this->connection->escape($value); - - return "'" . str_replace("'","''",$value) . "'"; - } -} \ No newline at end of file +connection = $connection; + + if (is_array($expressions)) + { + $glue = func_num_args() > 2 ? func_get_arg(2) : ' AND '; + list($expressions,$values) = $this->build_sql_from_hash($expressions, $glue); + } + + if ($expressions != '') + { + if (!$values) + $values = array_slice(func_get_args(), 2); + + $this->values = $values; + $this->expressions = $expressions; + } + } + + /** + * Bind a value to the specific one based index. There must be a bind marker + * for each value bound or to_s() will throw an exception. + */ + public function bind($parameter_number, $value) + { + if ($parameter_number <= 0) + throw new ExpressionsException("Invalid parameter index: $parameter_number"); + + $this->values[$parameter_number-1] = $value; + } + + public function bind_values($values) + { + $this->values = $values; + } + + /** + * Returns all the values currently bound. + */ + public function values() + { + return $this->values; + } + + /** + * Returns the connection object. + */ + public function get_connection() + { + return $this->connection; + } + + /** + * Sets the connection object. It is highly recommended to set this so we can + * use the adapter's native escaping mechanism. + * + * @param string $connection a Connection instance + */ + public function set_connection($connection) + { + $this->connection = $connection; + } + + public function to_s($substitute=false, &$options=null) + { + if (!$options) $options = array(); + + $values = array_key_exists('values', $options) ? $options['values'] : $this->values; + + $ret = ""; + $replace = array(); + $num_values = count($values); + $len = strlen($this->expressions); + $quotes = 0; + + for ($i=0,$n=strlen($this->expressions),$j=0; $i<$n; ++$i) + { + $ch = $this->expressions[$i]; + + if ($ch == self::PARAMETER_MARKER) + { + if ($quotes % 2 == 0) + { + if ($j > $num_values-1) + throw new ExpressionsException("No bound parameter for index $j"); + + $ch = $this->substitute($values, $substitute, $i, $j++); + } + } + elseif ($ch == '\'' && $i > 0 && $this->expressions[$i-1] != '\\') + ++$quotes; + + $ret .= $ch; + } + return $ret; + } + + private function build_sql_from_hash(&$hash, $glue) + { + $sql = $g = ""; + + foreach ($hash as $name => $value) + { + if ($this->connection) + $name = $this->connection->quote_name($name); + + if (is_array($value)) + $sql .= "$g$name IN(?)"; + elseif (is_null($value)) + $sql .= "$g$name IS ?"; + else + $sql .= "$g$name=?"; + + $g = $glue; + } + return array($sql,array_values($hash)); + } + + private function substitute(&$values, $substitute, $pos, $parameter_index) + { + $value = $values[$parameter_index]; + + if (is_array($value)) + { + $value_count = count($value); + + if ($value_count === 0) + if ($substitute) + return 'NULL'; + else + return self::PARAMETER_MARKER; + + if ($substitute) + { + $ret = ''; + + for ($i=0, $n=$value_count; $i<$n; ++$i) + $ret .= ($i > 0 ? ',' : '') . $this->stringify_value($value[$i]); + + return $ret; + } + return join(',', array_fill(0, $value_count, self::PARAMETER_MARKER)); + } + + if ($substitute) + return $this->stringify_value($value); + + return $this->expressions[$pos]; + } + + private function stringify_value($value) + { + if (is_null($value)) + return "NULL"; + + return is_string($value) ? $this->quote_string($value) : $value; + } + + private function quote_string($value) + { + if ($this->connection) + return $this->connection->escape($value); + + return "'" . str_replace("'", "''", $value) . "'"; + } +} diff --git a/lib/Inflector.php b/lib/Inflector.php index 732fb3422..29a95bf88 100644 --- a/lib/Inflector.php +++ b/lib/Inflector.php @@ -1,119 +1,126 @@ - 0) - $camelized[0] = strtolower($camelized[0]); - - return $camelized; - } - - /** - * Determines if a string contains all uppercase characters. - * - * @param string $s string to check - * @return bool - */ - public static function is_upper($s) - { - return (strtoupper($s) === $s); - } - - /** - * Determines if a string contains all lowercase characters. - * - * @param string $s string to check - * @return bool - */ - public static function is_lower($s) - { - return (strtolower($s) === $s); - } - - /** - * Convert a camelized string to a lowercase, underscored string. - * - * @param string $s string to convert - * @return string - */ - public function uncamelize($s) - { - $normalized = ''; - - for ($i=0,$n=strlen($s); $i<$n; ++$i) - { - if (ctype_alpha($s[$i]) && self::is_upper($s[$i])) - $normalized .= '_' . strtolower($s[$i]); - else - $normalized .= $s[$i]; - } - return trim($normalized,' _'); - } - - /** - * Convert a string with space into a underscored equivalent. - * - * @param string $s string to convert - * @return string - */ - public function underscorify($s) - { - return preg_replace(array('/[_\- ]+/','/([a-z])([A-Z])/'),array('_','\\1_\\2'),trim($s)); - } - - public function keyify($class_name) - { - return strtolower($this->underscorify(denamespace($class_name))) . '_id'; - } - - abstract function variablize($s); -} - -/** - * @package ActiveRecord - */ -class StandardInflector extends Inflector -{ - public function tableize($s) { return Utils::pluralize(strtolower($this->underscorify($s))); } - public function variablize($s) { return str_replace(array('-',' '),array('_','_'),strtolower(trim($s))); } -} \ No newline at end of file + 0) + $camelized[0] = strtolower($camelized[0]); + + return $camelized; + } + + /** + * Determines if a string contains all uppercase characters. + * + * @param string $s string to check + * @return bool + */ + public static function is_upper($s) + { + return (strtoupper($s) === $s); + } + + /** + * Determines if a string contains all lowercase characters. + * + * @param string $s string to check + * @return bool + */ + public static function is_lower($s) + { + return (strtolower($s) === $s); + } + + /** + * Convert a camelized string to a lowercase, underscored string. + * + * @param string $s string to convert + * @return string + */ + public function uncamelize($s) + { + $normalized = ''; + + for ($i=0,$n=strlen($s); $i<$n; ++$i) + { + if (ctype_alpha($s[$i]) && self::is_upper($s[$i])) + $normalized .= '_' . strtolower($s[$i]); + else + $normalized .= $s[$i]; + } + return trim($normalized, ' _'); + } + + /** + * Convert a string with space into a underscored equivalent. + * + * @param string $s string to convert + * @return string + */ + public function underscorify($s) + { + return preg_replace(array('/[_\- ]+/','/([a-z])([A-Z])/'), array('_','\\1_\\2'), trim($s)); + } + + public function keyify($class_name) + { + return strtolower($this->underscorify(denamespace($class_name))) . '_id'; + } + + abstract function variablize($s); +} + +/** + * @package ActiveRecord + */ +class StandardInflector extends Inflector +{ + public function tableize($s) + { + return Utils::pluralize(strtolower($this->underscorify($s))); + } + + public function variablize($s) + { + return str_replace(array('-',' '), array('_','_'), strtolower(trim($s))); + } +} diff --git a/lib/Model.php b/lib/Model.php index 36e0a4918..6892a2277 100644 --- a/lib/Model.php +++ b/lib/Model.php @@ -88,7 +88,8 @@ class Model private $attributes = array(); /** - * Flag whether or not this model's attributes have been modified since it will either be null or an array of column_names that have been modified + * Flag whether or not this model's attributes have been modified since it will either + * be null or an array of column_names that have been modified * * @var array */ @@ -159,7 +160,8 @@ class Model static $cache = false; /** - * Set this to specify an expiration period for this model. If not set, the expire value you set in your cache options will be used. + * Set this to specify an expiration period for this model. If not set, + * the expire value you set in your cache options will be used. * * @var number */ @@ -277,7 +279,7 @@ public function __construct(array $attributes=array(), $guard_attributes=true, $ if ($instantiating_via_find) $this->__dirty = array(); - $this->invoke_callback('after_construct',false); + $this->invoke_callback('after_construct', false); } /** @@ -353,7 +355,7 @@ public function &__get($name) */ public function __isset($attribute_name) { - return array_key_exists($attribute_name,$this->attributes) || array_key_exists($attribute_name,static::$alias_attribute); + return array_key_exists($attribute_name, $this->attributes) || array_key_exists($attribute_name, static::$alias_attribute); } /** @@ -411,25 +413,25 @@ public function __set($name, $value) if (array_key_exists($name, static::$alias_attribute)) $name = static::$alias_attribute[$name]; - elseif (method_exists($this,"set_$name")) + elseif (method_exists($this, "set_$name")) { $name = "set_$name"; return $this->$name($value); } - if (array_key_exists($name,$this->attributes)) - return $this->assign_attribute($name,$value); + if (array_key_exists($name, $this->attributes)) + return $this->assign_attribute($name, $value); if ($name == 'id') - return $this->assign_attribute($this->get_primary_key(true),$value); + return $this->assign_attribute($this->get_primary_key(true), $value); foreach (static::$delegate as &$item) { - if (($delegated_name = $this->is_delegated($name,$item))) + if (($delegated_name = $this->is_delegated($name, $item))) return $this->$item['to']->$delegated_name = $value; } - throw new UndefinedPropertyException(get_called_class(),$name); + throw new UndefinedPropertyException(get_called_class(), $name); } public function __wakeup() @@ -466,7 +468,7 @@ public function assign_attribute($name, $value) // make sure DateTime values know what model they belong to so // dirty stuff works when calling set methods on the DateTime object if ($value instanceof DateTime) - $value->attribute_of($this,$name); + $value->attribute_of($this, $name); $this->attributes[$name] = $value; $this->flag_dirty($name); @@ -489,11 +491,11 @@ public function &read_attribute($name) $name = static::$alias_attribute[$name]; // check for attribute - if (array_key_exists($name,$this->attributes)) + if (array_key_exists($name, $this->attributes)) return $this->attributes[$name]; // check relationships if no attribute - if (array_key_exists($name,$this->__relationships)) + if (array_key_exists($name, $this->__relationships)) return $this->__relationships[$name]; $table = static::table(); @@ -517,7 +519,7 @@ public function &read_attribute($name) foreach (static::$delegate as &$item) { - if (($delegated_name = $this->is_delegated($name,$item))) + if (($delegated_name = $this->is_delegated($name, $item))) { $to = $item['to']; if ($this->$to) @@ -530,7 +532,7 @@ public function &read_attribute($name) } } - throw new UndefinedPropertyException(get_called_class(),$name); + throw new UndefinedPropertyException(get_called_class(), $name); } /** @@ -556,7 +558,7 @@ public function dirty_attributes() if (!$this->__dirty) return null; - $dirty = array_intersect_key($this->attributes,$this->__dirty); + $dirty = array_intersect_key($this->attributes, $this->__dirty); return !empty($dirty) ? $dirty : null; } @@ -600,10 +602,10 @@ public function get_primary_key($first=false) */ public function get_real_attribute_name($name) { - if (array_key_exists($name,$this->attributes)) + if (array_key_exists($name, $this->attributes)) return $name; - if (array_key_exists($name,static::$alias_attribute)) + if (array_key_exists($name, static::$alias_attribute)) return static::$alias_attribute[$name]; return null; @@ -647,7 +649,7 @@ public function get_values_for($attributes) foreach ($attributes as $name) { - if (array_key_exists($name,$this->attributes)) + if (array_key_exists($name, $this->attributes)) $ret[$name] = $this->attributes[$name]; } return $ret; @@ -674,9 +676,9 @@ public static function table_name() private function is_delegated($name, &$delegate) { if ($delegate['prefix'] != '') - $name = substr($name,strlen($delegate['prefix'])+1); + $name = substr($name, strlen($delegate['prefix'])+1); - if (is_array($delegate) && in_array($name,$delegate['delegate'])) + if (is_array($delegate) && in_array($name, $delegate['delegate'])) return $name; return null; @@ -801,7 +803,7 @@ private function insert($validate=true) { $this->verify_not_readonly('insert'); - if (($validate && !$this->_validate() || !$this->invoke_callback('before_create',false))) + if (($validate && !$this->_validate() || !$this->invoke_callback('before_create', false))) return false; $table = static::table(); @@ -824,10 +826,10 @@ private function insert($validate=true) else { // unset pk that was set to null - if (array_key_exists($pk,$attributes)) + if (array_key_exists($pk, $attributes)) unset($attributes[$pk]); - $table->insert($attributes,$pk,$table->sequence); + $table->insert($attributes, $pk, $table->sequence); $use_sequence = true; } } @@ -845,7 +847,7 @@ private function insert($validate=true) } $this->__new_record = false; - $this->invoke_callback('after_create',false); + $this->invoke_callback('after_create', false); $this->update_cache(); return true; @@ -872,12 +874,12 @@ private function update($validate=true) if (empty($pk)) throw new ActiveRecordException("Cannot update, no primary key defined for: " . get_called_class()); - if (!$this->invoke_callback('before_update',false)) + if (!$this->invoke_callback('before_update', false)) return false; $dirty = $this->dirty_attributes(); - static::table()->update($dirty,$pk); - $this->invoke_callback('after_update',false); + static::table()->update($dirty, $pk); + $this->invoke_callback('after_update', false); $this->update_cache(); } @@ -1027,11 +1029,11 @@ public function delete() if (empty($pk)) throw new ActiveRecordException("Cannot delete, no primary key defined for: " . get_called_class()); - if (!$this->invoke_callback('before_destroy',false)) + if (!$this->invoke_callback('before_destroy', false)) return false; static::table()->delete($pk); - $this->invoke_callback('after_destroy',false); + $this->invoke_callback('after_destroy', false); $this->remove_from_cache(); return true; @@ -1086,7 +1088,7 @@ private function _validate() foreach (array('before_validation', "before_$validation_on") as $callback) { - if (!$this->invoke_callback($callback,false)) + if (!$this->invoke_callback($callback, false)) return false; } @@ -1095,7 +1097,7 @@ private function _validate() $validator->validate(); foreach (array('after_validation', "after_$validation_on") as $callback) - $this->invoke_callback($callback,false); + $this->invoke_callback($callback, false); if (!$this->errors->is_empty()) return false; @@ -1207,18 +1209,18 @@ private function set_attributes_via_mass_assignment(array &$attributes, $guard_a foreach ($attributes as $name => $value) { // is a normal field on the table - if (array_key_exists($name,$table->columns)) + if (array_key_exists($name, $table->columns)) { - $value = $table->columns[$name]->cast($value,$connection); + $value = $table->columns[$name]->cast($value, $connection); $name = $table->columns[$name]->inflected_name; } if ($guard_attributes) { - if ($use_attr_accessible && !in_array($name,static::$attr_accessible)) + if ($use_attr_accessible && !in_array($name, static::$attr_accessible)) continue; - if ($use_attr_protected && in_array($name,static::$attr_protected)) + if ($use_attr_protected && in_array($name, static::$attr_protected)) continue; // set valid table data @@ -1235,12 +1237,12 @@ private function set_attributes_via_mass_assignment(array &$attributes, $guard_a continue; // set arbitrary data - $this->assign_attribute($name,$value); + $this->assign_attribute($name, $value); } } if (!empty($exceptions)) - throw new UndefinedPropertyException(get_called_class(),$exceptions); + throw new UndefinedPropertyException(get_called_class(), $exceptions); } /** @@ -1312,7 +1314,9 @@ public function reset_dirty() * * @var array */ - static $VALID_OPTIONS = array('conditions', 'limit', 'offset', 'order', 'select', 'joins', 'include', 'readonly', 'group', 'from', 'having'); + static $VALID_OPTIONS = array( + 'conditions', 'limit', 'offset', 'order', 'select', 'joins', 'include', 'readonly', 'group', 'from', 'having' + ); /** * Enables the use of dynamic finders. @@ -1358,36 +1362,39 @@ public static function __callStatic($method, $args) $options = static::extract_and_validate_options($args); $create = false; - if (substr($method,0,17) == 'find_or_create_by') + if (substr($method, 0, 17) == 'find_or_create_by') { - $attributes = substr($method,17); + $attributes = substr($method, 17); // can't take any finders with OR in it when doing a find_or_create_by - if (strpos($attributes,'_or_') !== false) + if (strpos($attributes, '_or_') !== false) throw new ActiveRecordException("Cannot use OR'd attributes in find_or_create_by"); $create = true; - $method = 'find_by' . substr($method,17); + $method = 'find_by' . substr($method, 17); } - if (substr($method,0,7) === 'find_by') + if (substr($method, 0, 7) === 'find_by') { - $attributes = substr($method,8); - $options['conditions'] = SQLBuilder::create_conditions_from_underscored_string(static::connection(),$attributes,$args,static::$alias_attribute); + $attributes = substr($method, 8); + $options['conditions'] = SQLBuilder::create_conditions_from_underscored_string(static::connection(), + $attributes, $args, static::$alias_attribute); - if (!($ret = static::find('first',$options)) && $create) - return static::create(SQLBuilder::create_hash_from_underscored_string($attributes,$args,static::$alias_attribute)); + if (!($ret = static::find('first', $options)) && $create) + return static::create(SQLBuilder::create_hash_from_underscored_string($attributes, $args, static::$alias_attribute)); return $ret; } - elseif (substr($method,0,11) === 'find_all_by') + elseif (substr($method, 0, 11) === 'find_all_by') { - $options['conditions'] = SQLBuilder::create_conditions_from_underscored_string(static::connection(),substr($method,12),$args,static::$alias_attribute); - return static::find('all',$options); + $options['conditions'] = SQLBuilder::create_conditions_from_underscored_string(static::connection(), + substr($method, 12), $args, static::$alias_attribute); + return static::find('all', $options); } - elseif (substr($method,0,8) === 'count_by') + elseif (substr($method, 0, 8) === 'count_by') { - $options['conditions'] = SQLBuilder::create_conditions_from_underscored_string(static::connection(),substr($method,9),$args,static::$alias_attribute); + $options['conditions'] = SQLBuilder::create_conditions_from_underscored_string(static::connection(), + substr($method, 9), $args, static::$alias_attribute); return static::count($options); } @@ -1434,7 +1441,7 @@ public function __call($method, $args) */ public static function all(/* ... */) { - return call_user_func_array('static::find',array_merge(array('all'),func_get_args())); + return call_user_func_array('static::find', array_merge(array('all'), func_get_args())); } /** @@ -1458,13 +1465,13 @@ public static function count(/* ... */) if (is_hash($args[0])) $options['conditions'] = $args[0]; else - $options['conditions'] = call_user_func_array('static::pk_conditions',$args); + $options['conditions'] = call_user_func_array('static::pk_conditions', $args); } $table = static::table(); $sql = $table->options_to_sql($options); $values = $sql->get_where_values(); - return static::connection()->query_and_fetch_one($sql->to_s(),$values); + return static::connection()->query_and_fetch_one($sql->to_s(), $values); } /** @@ -1481,7 +1488,7 @@ public static function count(/* ... */) */ public static function exists(/* ... */) { - return call_user_func_array('static::count',func_get_args()) > 0 ? true : false; + return call_user_func_array('static::count', func_get_args()) > 0 ? true : false; } /** @@ -1492,7 +1499,7 @@ public static function exists(/* ... */) */ public static function first(/* ... */) { - return call_user_func_array('static::find',array_merge(array('first'),func_get_args())); + return call_user_func_array('static::find', array_merge(array('first'), func_get_args())); } /** @@ -1503,7 +1510,7 @@ public static function first(/* ... */) */ public static function last(/* ... */) { - return call_user_func_array('static::find',array_merge(array('last'),func_get_args())); + return call_user_func_array('static::find', array_merge(array('last'), func_get_args())); } /** @@ -1545,7 +1552,8 @@ public static function last(/* ... */) *
  • select: A SQL fragment for what fields to return such as: '*', 'people.*', 'first_name, last_name, id'
  • *
  • joins: A SQL join fragment such as: 'JOIN roles ON(roles.user_id=user.id)' or a named association on the model
  • *
  • include: TODO not implemented yet
  • - *
  • conditions: A SQL fragment such as: 'id=1', array('id=1'), array('name=? and id=?','Tito',1), array('name IN(?)', array('Tito','Bob')), + *
  • conditions: A SQL fragment such as: + * 'id=1', array('id=1'), array('name=? and id=?','Tito',1), array('name IN(?)', array('Tito','Bob')), * array('name' => 'Tito', 'id' => 1)
  • *
  • limit: Number of records to limit the query to
  • *
  • offset: The row offset to return results from for the query
  • @@ -1581,8 +1589,8 @@ public static function find(/* $type, $options */) break; case 'last': - if (!array_key_exists('order',$options)) - $options['order'] = join(' DESC, ',static::table()->pk) . ' DESC'; + if (!array_key_exists('order', $options)) + $options['order'] = join(' DESC, ', static::table()->pk) . ' DESC'; else $options['order'] = SQLBuilder::reverse_order($options['order']); @@ -1594,7 +1602,7 @@ public static function find(/* $type, $options */) break; } - $args = array_slice($args,1); + $args = array_slice($args, 1); $num_args--; } //find by pk @@ -1668,7 +1676,7 @@ public static function find_by_pk($values, $options) { $class = get_called_class(); if (is_array($values)) - $values = join(',',$values); + $values = join(',', $values); if ($expected == 1) { @@ -1722,12 +1730,12 @@ public static function is_options_hash($array, $throw=true) if (is_hash($array)) { $keys = array_keys($array); - $diff = array_diff($keys,self::$VALID_OPTIONS); + $diff = array_diff($keys, self::$VALID_OPTIONS); if (!empty($diff) && $throw) - throw new ActiveRecordException("Unknown key(s): " . join(', ',$diff)); + throw new ActiveRecordException("Unknown key(s): " . join(', ', $diff)); - $intersect = array_intersect($keys,self::$VALID_OPTIONS); + $intersect = array_intersect($keys, self::$VALID_OPTIONS); if (!empty($intersect)) return true; @@ -1807,30 +1815,30 @@ public function to_xml(array $options=array()) return $this->serialize('Xml', $options); } - /** - * Returns an CSV representation of this model. - * Can take optional delimiter and enclosure - * (defaults are , and double quotes) - * - * Ex: - * - * ActiveRecord\CsvSerializer::$delimiter=';'; - * ActiveRecord\CsvSerializer::$enclosure=''; - * YourModel::find('first')->to_csv(array('only'=>array('name','level'))); - * returns: Joe,2 - * - * YourModel::find('first')->to_csv(array('only_header'=>true,'only'=>array('name','level'))); - * returns: name,level - * - * - * @see Serialization - * @param array $options An array containing options for csv serialization (see {@link Serialization} for valid options) - * @return string CSV representation of the model - */ - public function to_csv(array $options=array()) - { - return $this->serialize('Csv', $options); - } + /** + * Returns an CSV representation of this model. + * Can take optional delimiter and enclosure + * (defaults are , and double quotes) + * + * Ex: + * + * ActiveRecord\CsvSerializer::$delimiter=';'; + * ActiveRecord\CsvSerializer::$enclosure=''; + * YourModel::find('first')->to_csv(array('only'=>array('name','level'))); + * returns: Joe,2 + * + * YourModel::find('first')->to_csv(array('only_header'=>true,'only'=>array('name','level'))); + * returns: name,level + * + * + * @see Serialization + * @param array $options An array containing options for csv serialization (see {@link Serialization} for valid options) + * @return string CSV representation of the model + */ + public function to_csv(array $options=array()) + { + return $this->serialize('Csv', $options); + } /** * Returns an Array representation of this model. @@ -1852,7 +1860,8 @@ public function to_array(array $options=array()) * @@ -1878,7 +1887,7 @@ private function serialize($type, $options) */ private function invoke_callback($method_name, $must_exist=true) { - return static::table()->callback->invoke($this,$method_name,$must_exist); + return static::table()->callback->invoke($this, $method_name, $must_exist); } /** diff --git a/lib/Relationship.php b/lib/Relationship.php index 297d89438..6f188c2dc 100644 --- a/lib/Relationship.php +++ b/lib/Relationship.php @@ -64,7 +64,9 @@ abstract class AbstractRelationship implements InterfaceRelationship * * @var array */ - static protected $valid_association_options = array('class_name', 'class', 'foreign_key', 'conditions', 'select', 'readonly', 'namespace'); + static protected $valid_association_options = array( + 'class_name', 'class', 'foreign_key', 'conditions', 'select', 'readonly', 'namespace' + ); /** * Constructs a relationship. @@ -93,7 +95,8 @@ public function __construct($options=array()) $this->attribute_name = strtolower(Inflector::instance()->variablize($this->attribute_name)); if (!$this->foreign_key && isset($this->options['foreign_key'])) - $this->foreign_key = is_array($this->options['foreign_key']) ? $this->options['foreign_key'] : array($this->options['foreign_key']); + $this->foreign_key = is_array($this->options['foreign_key']) + ? $this->options['foreign_key'] : array($this->options['foreign_key']); } protected function get_table() @@ -126,7 +129,8 @@ public function is_poly() * @param $model_values_keys -> key(s)/value(s) to be used in query from model which is including * @return void */ - protected function query_and_attach_related_models_eagerly(Table $table, $models, $attributes, $includes=array(), $query_keys=array(), $model_values_keys=array()) + protected function query_and_attach_related_models_eagerly(Table $table, $models, $attributes, + $includes=array(), $query_keys=array(), $model_values_keys=array()) { $values = array(); $options = $this->options; @@ -138,7 +142,7 @@ protected function query_and_attach_related_models_eagerly(Table $table, $models $values[] = $value[$inflector->variablize($model_values_key)]; $values = array($values); - $conditions = SQLBuilder::create_conditions_from_underscored_string($table->conn,$query_key,$values); + $conditions = SQLBuilder::create_conditions_from_underscored_string($table->conn, $query_key, $values); if (isset($options['conditions']) && strlen($options['conditions'][0]) > 1) Utils::add_condition($options['conditions'], $conditions); @@ -251,8 +255,8 @@ protected function append_record_to_associate(Model $associate, Model $record) protected function merge_association_options($options) { - $available_options = array_merge(self::$valid_association_options,static::$valid_association_options); - $valid_options = array_intersect_key(array_flip($available_options),$options); + $available_options = array_merge(self::$valid_association_options, static::$valid_association_options); + $valid_options = array_intersect_key(array_flip($available_options), $options); foreach ($valid_options as $option => $v) $valid_options[$option] = $options[$option]; @@ -304,10 +308,11 @@ protected function create_conditions_from_keys(Model $model, $condition_keys=arr $condition_values = array_values($model->get_values_for($value_keys)); // return null if all the foreign key values are null so that we don't try to do a query like "id is null" - if (all(null,$condition_values)) + if (all(null, $condition_values)) return null; - $conditions = SQLBuilder::create_conditions_from_underscored_string(Table::load(get_class($model))->conn,$condition_string,$condition_values); + $conditions = SQLBuilder::create_conditions_from_underscored_string(Table::load(get_class($model))->conn, + $condition_string, $condition_values); # DO NOT CHANGE THE NEXT TWO LINES. add_condition operates on a reference and will screw options array up if (isset($this->options['conditions'])) @@ -333,7 +338,7 @@ public function construct_inner_join_sql(Table $from_table, $using_through=false $join_table = $from_table; $join_table_name = $from_table->get_fully_qualified_table_name(); $from_table_name = Table::load($this->class_name)->get_fully_qualified_table_name(); - } + } else { $join_table = Table::load($this->class_name); @@ -439,7 +444,9 @@ class HasMany extends AbstractRelationship * * @var array */ - static protected $valid_association_options = array('primary_key', 'order', 'group', 'having', 'limit', 'offset', 'through', 'source'); + static protected $valid_association_options = array( + 'primary_key', 'order', 'group', 'having', 'limit', 'offset', 'through', 'source' + ); protected $primary_key; @@ -465,7 +472,8 @@ public function __construct($options=array()) } if (!$this->primary_key && isset($this->options['primary_key'])) - $this->primary_key = is_array($this->options['primary_key']) ? $this->options['primary_key'] : array($this->options['primary_key']); + $this->primary_key = is_array($this->options['primary_key']) + ? $this->options['primary_key'] : array($this->options['primary_key']); if (!$this->class_name) $this->set_inferred_class_name(); @@ -524,7 +532,7 @@ public function load(Model $model) $options = $this->unset_non_finder_options($this->options); $options['conditions'] = $conditions; - return $class_name::find($this->poly_relationship ? 'all' : 'first',$options); + return $class_name::find($this->poly_relationship ? 'all' : 'first', $options); } /** @@ -602,7 +610,7 @@ public function create_association(Model $model, $attributes=array(), $guard_att public function load_eagerly($models=array(), $attributes=array(), $includes, Table $table) { $this->set_keys($table->class->name); - $this->query_and_attach_related_models_eagerly($table,$models,$attributes,$includes,$this->foreign_key, $table->pk); + $this->query_and_attach_related_models_eagerly($table, $models, $attributes, $includes, $this->foreign_key, $table->pk); } } @@ -723,6 +731,6 @@ public function load(Model $model) public function load_eagerly($models=array(), $attributes, $includes, Table $table) { - $this->query_and_attach_related_models_eagerly($table,$models,$attributes,$includes, $this->primary_key,$this->foreign_key); + $this->query_and_attach_related_models_eagerly($table, $models, $attributes, $includes, $this->primary_key, $this->foreign_key); } } \ No newline at end of file diff --git a/lib/SQLBuilder.php b/lib/SQLBuilder.php index ef239ed87..d274dab72 100644 --- a/lib/SQLBuilder.php +++ b/lib/SQLBuilder.php @@ -83,7 +83,7 @@ public function bind_values() $ret = array_values($this->data); if ($this->get_where_values()) - $ret = array_merge($ret,$this->get_where_values()); + $ret = array_merge($ret, $this->get_where_values()); return array_flatten($ret); } @@ -185,20 +185,20 @@ public static function reverse_order($order) if (!trim($order)) return $order; - $parts = explode(',',$order); + $parts = explode(',', $order); for ($i=0,$n=count($parts); $i<$n; ++$i) { $v = strtolower($parts[$i]); - if (strpos($v,' asc') !== false) - $parts[$i] = preg_replace('/asc/i','DESC',$parts[$i]); - elseif (strpos($v,' desc') !== false) - $parts[$i] = preg_replace('/desc/i','ASC',$parts[$i]); + if (strpos($v, ' asc') !== false) + $parts[$i] = preg_replace('/asc/i', 'DESC', $parts[$i]); + elseif (strpos($v, ' desc') !== false) + $parts[$i] = preg_replace('/desc/i', 'ASC', $parts[$i]); else $parts[$i] .= ' DESC'; } - return join(',',$parts); + return join(',', $parts); } /** @@ -216,14 +216,14 @@ public static function create_conditions_from_underscored_string(Connection $con if (!$name) return null; - $parts = preg_split('/(_and_|_or_)/i',$name,-1,PREG_SPLIT_DELIM_CAPTURE); + $parts = preg_split('/(_and_|_or_)/i', $name, -1, PREG_SPLIT_DELIM_CAPTURE); $num_values = count($values); $conditions = array(''); for ($i=0,$j=0,$n=count($parts); $i<$n; $i+=2,++$j) { if ($i >= 2) - $conditions[0] .= preg_replace(array('/_and_/i','/_or_/i'),array(' AND ',' OR '),$parts[$i-1]); + $conditions[0] .= preg_replace(array('/_and_/i','/_or_/i'), array(' AND ',' OR '), $parts[$i-1]); if ($j < $num_values) { @@ -256,7 +256,7 @@ public static function create_conditions_from_underscored_string(Connection $con */ public static function create_hash_from_underscored_string($name, &$values=array(), &$map=null) { - $parts = preg_split('/(_and_|_or_)/i',$name); + $parts = preg_split('/(_and_|_or_)/i', $name); $hash = array(); for ($i=0,$n=count($parts); $i<$n; ++$i) @@ -297,20 +297,20 @@ private function apply_where_conditions($args) if ($num_args == 1 && is_hash($args[0])) { $hash = is_null($this->joins) ? $args[0] : $this->prepend_table_name_to_fields($args[0]); - $e = new Expressions($this->connection,$hash); + $e = new Expressions($this->connection, $hash); $this->where = $e->to_s(); $this->where_values = array_flatten($e->values()); } elseif ($num_args > 0) { // if the values has a nested array then we'll need to use Expressions to expand the bind marker for us - $values = array_slice($args,1); + $values = array_slice($args, 1); foreach ($values as $name => &$value) { if (is_array($value)) { - $e = new Expressions($this->connection,$args[0]); + $e = new Expressions($this->connection, $args[0]); $e->bind_values($values); $this->where = $e->to_s(); $this->where_values = array_flatten($e->values()); @@ -337,7 +337,7 @@ private function build_delete() $sql .= " ORDER BY $this->order"; if ($this->limit) - $sql = $this->connection->limit($sql,null,$this->limit); + $sql = $this->connection->limit($sql, null, $this->limit); } return $sql; @@ -346,7 +346,7 @@ private function build_delete() private function build_insert() { require_once 'Expressions.php'; - $keys = join(',',$this->quoted_key_names()); + $keys = join(',', $this->quoted_key_names()); if ($this->sequence) { @@ -357,7 +357,7 @@ private function build_insert() else $sql = "INSERT INTO $this->table($keys) VALUES(?)"; - $e = new Expressions($this->connection,$sql,array_values($this->data)); + $e = new Expressions($this->connection, $sql, array_values($this->data)); return $e->to_s(); } @@ -381,7 +381,7 @@ private function build_select() $sql .= " ORDER BY $this->order"; if ($this->limit || $this->offset) - $sql = $this->connection->limit($sql,$this->offset,$this->limit); + $sql = $this->connection->limit($sql, $this->offset, $this->limit); return $sql; } @@ -404,7 +404,7 @@ private function build_update() $sql .= " ORDER BY $this->order"; if ($this->limit) - $sql = $this->connection->limit($sql,null,$this->limit); + $sql = $this->connection->limit($sql, null, $this->limit); } return $sql; diff --git a/lib/Serialization.php b/lib/Serialization.php index db0208808..4a070608a 100644 --- a/lib/Serialization.php +++ b/lib/Serialization.php @@ -13,8 +13,9 @@ * * * @param array $attrs Validation definition @@ -473,7 +484,7 @@ public function validates_length_of($attrs) $range_options = array_intersect(array_keys(self::$ALL_RANGE_OPTIONS), array_keys($attr)); sort($range_options); - switch (sizeof($range_options)) + switch (count($range_options)) { case 0: throw new ValidationsArgumentError('Range unspecified. Specify the [within], [maximum], or [is] option.'); @@ -494,7 +505,8 @@ public function validates_length_of($attrs) $range = $options[$range_options[0]]; if (!(Utils::is_a('range', $range))) - throw new ValidationsArgumentError("$range_options[0] must be an array composing a range of numbers with key [0] being less than key [1]"); + throw new ValidationsArgumentError($range_options[0] . + " must be an array composing a range of numbers with key [0] being less than key [1]"); $range_options = array('minimum', 'maximum'); $attr['minimum'] = $range[0]; $attr['maximum'] = $range[1]; @@ -593,7 +605,7 @@ public function validates_uniqueness_of($attrs) else { $sql = "{$pk_quoted} != ?"; - array_push($conditions,$pk_value); + array_push($conditions, $pk_value); } foreach ($fields as $field) @@ -601,7 +613,7 @@ public function validates_uniqueness_of($attrs) $field = $this->model->get_real_attribute_name($field); $quoted_field = $connection->quote_name($field); $sql .= " AND {$quoted_field}=?"; - array_push($conditions,$this->model->$field); + array_push($conditions, $this->model->$field); } $conditions[0] = $sql; diff --git a/lib/adapters/MysqlAdapter.php b/lib/adapters/MysqlAdapter.php index 12a50db63..de95152bb 100644 --- a/lib/adapters/MysqlAdapter.php +++ b/lib/adapters/MysqlAdapter.php @@ -56,7 +56,7 @@ public function create_column(&$column) } else { - preg_match('/^([A-Za-z0-9_]+)(\(([0-9]+(,[0-9]+)?)\))?/',$column['type'],$matches); + preg_match('/^([A-Za-z0-9_]+)(\(([0-9]+(,[0-9]+)?)\))?/', $column['type'], $matches); $c->raw_type = (count($matches) > 0 ? $matches[1] : $column['type']); @@ -65,7 +65,7 @@ public function create_column(&$column) } $c->map_raw_type(); - $c->default = $c->cast($column['default'],$this); + $c->default = $c->cast($column['default'], $this); return $c; } @@ -73,10 +73,13 @@ public function create_column(&$column) public function set_encoding($charset) { $params = array($charset); - $this->query('SET NAMES ?',$params); + $this->query('SET NAMES ?', $params); } - public function accepts_limit_and_order_for_update_and_delete() { return true; } + public function accepts_limit_and_order_for_update_and_delete() + { + return true; + } public function native_database_types() { diff --git a/lib/adapters/OciAdapter.php b/lib/adapters/OciAdapter.php index 353fffefa..28f7c03f4 100644 --- a/lib/adapters/OciAdapter.php +++ b/lib/adapters/OciAdapter.php @@ -22,13 +22,17 @@ protected function __construct($info) { try { $this->dsn_params = isset($info->charset) ? ";charset=$info->charset" : ""; - $this->connection = new PDO("oci:dbname=//$info->host/$info->db$this->dsn_params",$info->user,$info->pass,static::$PDO_OPTIONS); + $this->connection = new PDO("oci:dbname=//$info->host/$info->db$this->dsn_params", + $info->user, $info->pass, static::$PDO_OPTIONS); } catch (PDOException $e) { throw new DatabaseException($e); } } - public function supports_sequences() { return true; } + public function supports_sequences() + { + return true; + } public function get_next_sequence_value($sequence_name) { @@ -53,33 +57,33 @@ public function datetime_to_string($datetime) // $string = DD-MON-YYYY HH12:MI:SS(\.[0-9]+) AM public function string_to_datetime($string) { - return parent::string_to_datetime(str_replace('.000000','',$string)); + return parent::string_to_datetime(str_replace('.000000', '', $string)); } public function limit($sql, $offset, $limit) { $offset = intval($offset); $stop = $offset + intval($limit); - return - "SELECT * FROM (SELECT a.*, rownum ar_rnum__ FROM ($sql) a " . - "WHERE rownum <= $stop) WHERE ar_rnum__ > $offset"; + return "SELECT * FROM (SELECT a.*, rownum ar_rnum__ FROM ($sql) a + WHERE rownum <= $stop) WHERE ar_rnum__ > $offset"; } public function query_column_info($table) { - $sql = - "SELECT c.column_name, c.data_type, c.data_length, c.data_scale, c.data_default, c.nullable, " . - "(SELECT a.constraint_type " . - "FROM all_constraints a, all_cons_columns b " . - "WHERE a.constraint_type='P' " . - "AND a.constraint_name=b.constraint_name " . - "AND a.table_name = t.table_name AND b.column_name=c.column_name) AS pk " . - "FROM user_tables t " . - "INNER JOIN user_tab_columns c on(t.table_name=c.table_name) " . - "WHERE t.table_name=?"; + $sql = <<query($sql,$values); + return $this->query($sql, $values); } public function query_for_tables() @@ -90,10 +94,10 @@ public function query_for_tables() public function create_column(&$column) { $column['column_name'] = strtolower($column['column_name']); - $column['data_type'] = strtolower(preg_replace('/\(.*?\)/','',$column['data_type'])); + $column['data_type'] = strtolower(preg_replace('/\(.*?\)/', '', $column['data_type'])); if ($column['data_default'] !== null) - $column['data_default'] = trim($column['data_default'],"' "); + $column['data_default'] = trim($column['data_default'], "' "); if ($column['data_type'] == 'number') { @@ -116,7 +120,7 @@ public function create_column(&$column) $c->raw_type = $column['data_type']; $c->map_raw_type(); - $c->default = $c->cast($column['data_default'],$this); + $c->default = $c->cast($column['data_default'], $this); return $c; } diff --git a/lib/adapters/PgsqlAdapter.php b/lib/adapters/PgsqlAdapter.php index 72da44182..0a67c6b38 100644 --- a/lib/adapters/PgsqlAdapter.php +++ b/lib/adapters/PgsqlAdapter.php @@ -26,7 +26,7 @@ public function get_sequence_name($table, $column_name) public function next_sequence_value($sequence_name) { - return "nextval('" . str_replace("'","\\'",$sequence_name) . "')"; + return "nextval('" . str_replace("'", "\\'", $sequence_name) . "')"; } public function limit($sql, $offset, $limit) @@ -61,7 +61,7 @@ public function query_column_info($table) ORDER BY a.attnum SQL; $values = array($table); - return $this->query($sql,$values); + return $this->query($sql, $values); } public function query_for_tables() @@ -78,7 +78,7 @@ public function create_column(&$column) $c->pk = ($column['pk'] ? true : false); $c->auto_increment = false; - if (substr($column['type'],0,9) == 'timestamp') + if (substr($column['type'], 0, 9) == 'timestamp') { $c->raw_type = 'datetime'; $c->length = 19; @@ -90,7 +90,7 @@ public function create_column(&$column) } else { - preg_match('/^([A-Za-z0-9_]+)(\(([0-9]+(,[0-9]+)?)\))?/',$column['type'],$matches); + preg_match('/^([A-Za-z0-9_]+)(\(([0-9]+(,[0-9]+)?)\))?/', $column['type'], $matches); $c->raw_type = (count($matches) > 0 ? $matches[1] : $column['type']); $c->length = count($matches) >= 4 ? intval($matches[3]) : intval($column['attlen']); @@ -103,12 +103,12 @@ public function create_column(&$column) if ($column['default']) { - preg_match("/^nextval\('(.*)'\)$/",$column['default'],$matches); + preg_match("/^nextval\('(.*)'\)$/", $column['default'], $matches); if (count($matches) == 2) $c->sequence = $matches[1]; else - $c->default = $c->cast($column['default'],$this); + $c->default = $c->cast($column['default'], $this); } return $c; } diff --git a/lib/adapters/SqliteAdapter.php b/lib/adapters/SqliteAdapter.php index 0917043be..f34a26b10 100644 --- a/lib/adapters/SqliteAdapter.php +++ b/lib/adapters/SqliteAdapter.php @@ -21,7 +21,7 @@ protected function __construct($info) if (!file_exists($info->host)) throw new DatabaseException("Could not find sqlite db: $info->host"); - $this->connection = new PDO("sqlite:$info->host",null,null,static::$PDO_OPTIONS); + $this->connection = new PDO("sqlite:$info->host", null, null, static::$PDO_OPTIONS); } public function limit($sql, $offset, $limit) @@ -53,10 +53,10 @@ public function create_column($column) array('INT', 'INTEGER') ) && $c->pk; - $column['type'] = preg_replace('/ +/',' ',$column['type']); - $column['type'] = str_replace(array('(',')'),' ',$column['type']); - $column['type'] = Utils::squeeze(' ',$column['type']); - $matches = explode(' ',$column['type']); + $column['type'] = preg_replace('/ +/', ' ', $column['type']); + $column['type'] = str_replace(array('(',')'), ' ', $column['type']); + $column['type'] = Utils::squeeze(' ', $column['type']); + $matches = explode(' ', $column['type']); if (!empty($matches)) { @@ -79,7 +79,7 @@ public function create_column($column) if ($c->type == Column::INTEGER && !$c->length) $c->length = 8; - $c->default = $c->cast($column['dflt_value'],$this); + $c->default = $c->cast($column['dflt_value'], $this); return $c; } @@ -89,7 +89,10 @@ public function set_encoding($charset) throw new ActiveRecordException("SqliteAdapter::set_charset not supported."); } - public function accepts_limit_and_order_for_update_and_delete() { return true; } + public function accepts_limit_and_order_for_update_and_delete() + { + return true; + } public function native_database_types() { diff --git a/lib/cache/Memcache.php b/lib/cache/Memcache.php index 3bbb96b82..921470b8b 100644 --- a/lib/cache/Memcache.php +++ b/lib/cache/Memcache.php @@ -23,7 +23,7 @@ public function __construct($options) $this->memcache = new \Memcache(); $options['port'] = isset($options['port']) ? $options['port'] : self::DEFAULT_PORT; - if (!$this->memcache->connect($options['host'],$options['port'])) + if (!$this->memcache->connect($options['host'], $options['port'])) throw new CacheException("Could not connect to $options[host]:$options[port]"); } @@ -39,7 +39,7 @@ public function read($key) public function write($key, $value, $expire) { - $this->memcache->set($key,$value,null,$expire); + $this->memcache->set($key, $value, null, $expire); } public function delete($key) diff --git a/ruleset.xml b/ruleset.xml new file mode 100644 index 000000000..bb9c1c967 --- /dev/null +++ b/ruleset.xml @@ -0,0 +1,46 @@ + + + + PHP ActiveRecord coding standard + + examples/* + test/* + vendor/* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file From 0f5a5fd665c5a6bdab5aab850c5010b0a918d107 Mon Sep 17 00:00:00 2001 From: Koen Punt Date: Wed, 10 Dec 2014 00:20:00 +0100 Subject: [PATCH 2/2] add phpcs to travis config --- .travis.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.travis.yml b/.travis.yml index e0810cd75..50818d8a2 100644 --- a/.travis.yml +++ b/.travis.yml @@ -16,4 +16,6 @@ php: - 5.4 - 5.5 -script: ./vendor/bin/phpunit +script: + - ./vendor/bin/phpcs --standard=ruleset.xml --warning-severity=6 ./ + - ./vendor/bin/phpunit