From 4d814ba60b8cafd61a2252e8c1f3fffbce0a3121 Mon Sep 17 00:00:00 2001 From: Fosco Marotto Date: Tue, 31 Mar 2015 14:14:14 -0700 Subject: [PATCH] Updated to full compliance with StyleCI --- autoload.php | 28 +- src/Parse/Internal/AddOperation.php | 69 +- src/Parse/Internal/AddUniqueOperation.php | 120 +- src/Parse/Internal/DeleteOperation.php | 11 +- src/Parse/Internal/Encodable.php | 5 +- src/Parse/Internal/FieldOperation.php | 5 +- src/Parse/Internal/IncrementOperation.php | 50 +- src/Parse/Internal/ParseRelationOperation.php | 275 +-- src/Parse/Internal/RemoveOperation.php | 92 +- src/Parse/Internal/SetOperation.php | 31 +- src/Parse/ParseACL.php | 297 +-- src/Parse/ParseAggregateException.php | 17 +- src/Parse/ParseAnalytics.php | 41 +- src/Parse/ParseBytes.php | 53 +- src/Parse/ParseClient.php | 334 +-- src/Parse/ParseCloud.php | 26 +- src/Parse/ParseConfig.php | 50 +- src/Parse/ParseException.php | 11 +- src/Parse/ParseFile.php | 596 ++--- src/Parse/ParseGeoPoint.php | 38 +- src/Parse/ParseInstallation.php | 7 +- src/Parse/ParseMemoryStorage.php | 74 +- src/Parse/ParseObject.php | 977 ++++---- src/Parse/ParsePush.php | 41 +- src/Parse/ParseQuery.php | 476 ++-- src/Parse/ParseRelation.php | 79 +- src/Parse/ParseRole.php | 58 +- src/Parse/ParseSession.php | 46 +- src/Parse/ParseSessionStorage.php | 80 +- src/Parse/ParseStorageInterface.php | 5 +- src/Parse/ParseUser.php | 213 +- tests/IncrementTest.php | 423 ++-- tests/ParseACLTest.php | 711 +++--- tests/ParseAnalyticsTest.php | 100 +- tests/ParseBytesTest.php | 79 +- tests/ParseCloudTest.php | 54 +- tests/ParseConfigTest.php | 18 +- tests/ParseFileTest.php | 237 +- tests/ParseGeoBoxTest.php | 219 +- tests/ParseGeoPointTest.php | 241 +- tests/ParseMemoryStorageTest.php | 94 +- tests/ParseObjectTest.php | 1631 ++++++------ tests/ParsePushTest.php | 70 +- tests/ParseQueryTest.php | 2179 +++++++++-------- tests/ParseRelationTest.php | 180 +- tests/ParseRoleTest.php | 359 +-- tests/ParseSessionStorageTest.php | 104 +- tests/ParseSessionTest.php | 92 +- tests/ParseSubclassTest.php | 44 +- tests/ParseTestHelper.php | 31 +- tests/ParseUserTest.php | 733 +++--- tests/phpunit.xml | 2 +- 52 files changed, 5919 insertions(+), 5887 deletions(-) diff --git a/autoload.php b/autoload.php index a3ef6aa8..60e6cb69 100755 --- a/autoload.php +++ b/autoload.php @@ -3,12 +3,11 @@ /** * You only need this file if you are not using composer. */ - if (version_compare(PHP_VERSION, '5.4.0', '<')) { - throw new Exception('The Parse SDK requires PHP version 5.4 or higher.'); + throw new Exception('The Parse SDK requires PHP version 5.4 or higher.'); } -/** +/* * Register the autoloader for the Parse SDK * Based off the official PSR-4 autoloader example found here: * https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md @@ -16,33 +15,32 @@ * @param string $class The fully-qualified class name. * @return void */ -spl_autoload_register(function ($class) -{ +spl_autoload_register(function ($class) { // Parse class prefix $prefix = 'Parse\\'; // base directory for the namespace prefix - $base_dir = defined('PARSE_SDK_DIR') ? PARSE_SDK_DIR : __DIR__ . '/src/Parse/'; + $base_dir = defined('PARSE_SDK_DIR') ? PARSE_SDK_DIR : __DIR__.'/src/Parse/'; // does the class use the namespace prefix? - $len = strlen( $prefix ); - if ( strncmp($prefix, $class, $len) !== 0 ) { - // no, move to the next registered autoloader + $len = strlen($prefix); + if (strncmp($prefix, $class, $len) !== 0) { + // no, move to the next registered autoloader return; } // get the relative class name - $relative_class = substr( $class, $len ); + $relative_class = substr($class, $len); // replace the namespace prefix with the base directory, replace namespace // separators with directory separators in the relative class name, append // with .php - $file = $base_dir . str_replace( '\\', '/', $relative_class ) . '.php'; - + $file = $base_dir.str_replace('\\', '/', $relative_class).'.php'; + // echo $relative_class . '
'; // if the file exists, require it - if ( file_exists( $file ) ) { - require $file; + if (file_exists($file)) { + require $file; } -}); \ No newline at end of file +}); diff --git a/src/Parse/Internal/AddOperation.php b/src/Parse/Internal/AddOperation.php index 9584f500..b8d810ef 100755 --- a/src/Parse/Internal/AddOperation.php +++ b/src/Parse/Internal/AddOperation.php @@ -6,14 +6,12 @@ use Parse\ParseException; /** - * Class AddOperation - FieldOperation for adding object(s) to array fields + * Class AddOperation - FieldOperation for adding object(s) to array fields. * - * @package Parse * @author Fosco Marotto */ class AddOperation implements FieldOperation { - /** * @var - Array with objects to add. */ @@ -28,10 +26,10 @@ class AddOperation implements FieldOperation */ public function __construct($objects) { - if (!is_array($objects)) { - throw new ParseException("AddOperation requires an array."); - } - $this->objects = $objects; + if (!is_array($objects)) { + throw new ParseException("AddOperation requires an array."); + } + $this->objects = $objects; } /** @@ -41,7 +39,7 @@ public function __construct($objects) */ public function getValue() { - return $this->objects; + return $this->objects; } /** @@ -51,8 +49,8 @@ public function getValue() */ public function _encode() { - return array('__op' => 'Add', - 'objects' => ParseClient::_encode($this->objects, true)); + return ['__op' => 'Add', + 'objects' => ParseClient::_encode($this->objects, true), ]; } /** @@ -60,30 +58,33 @@ public function _encode() * * @param FieldOperation $previous Previous operation. * - * @return FieldOperation Merged operation. * @throws ParseException + * + * @return FieldOperation Merged operation. */ public function _mergeWithPrevious($previous) { - if (!$previous) { - return $this; - } - if ($previous instanceof DeleteOperation) { - return new SetOperation($this->objects); - } - if ($previous instanceof SetOperation) { - $oldList = $previous->getValue(); - return new SetOperation( - array_merge((array)$oldList, (array)$this->objects) + if (!$previous) { + return $this; + } + if ($previous instanceof DeleteOperation) { + return new SetOperation($this->objects); + } + if ($previous instanceof SetOperation) { + $oldList = $previous->getValue(); + + return new SetOperation( + array_merge((array) $oldList, (array) $this->objects) ); - } - if ($previous instanceof AddOperation) { - $oldList = $previous->getValue(); - return new SetOperation( - array_merge((array)$oldList, (array)$this->objects) + } + if ($previous instanceof AddOperation) { + $oldList = $previous->getValue(); + + return new SetOperation( + array_merge((array) $oldList, (array) $this->objects) ); - } - throw new ParseException( + } + throw new ParseException( 'Operation is invalid after previous operation.' ); } @@ -99,10 +100,10 @@ public function _mergeWithPrevious($previous) */ public function _apply($oldValue, $obj, $key) { - if (!$oldValue) { - return $this->objects; - } - return array_merge((array)$oldValue, (array)$this->objects); - } + if (!$oldValue) { + return $this->objects; + } -} \ No newline at end of file + return array_merge((array) $oldValue, (array) $this->objects); + } +} diff --git a/src/Parse/Internal/AddUniqueOperation.php b/src/Parse/Internal/AddUniqueOperation.php index c4666f31..959ab2e3 100755 --- a/src/Parse/Internal/AddUniqueOperation.php +++ b/src/Parse/Internal/AddUniqueOperation.php @@ -8,12 +8,10 @@ /** * Class AddUniqueOperation - Operation to add unique objects to an array key. * - * @package Parse * @author Fosco Marotto */ class AddUniqueOperation implements FieldOperation { - /** * @var - Array containing objects to add. */ @@ -28,10 +26,10 @@ class AddUniqueOperation implements FieldOperation */ public function __construct($objects) { - if (!is_array($objects)) { - throw new ParseException("AddUniqueOperation requires an array."); - } - $this->objects = $objects; + if (!is_array($objects)) { + throw new ParseException("AddUniqueOperation requires an array."); + } + $this->objects = $objects; } /** @@ -41,7 +39,7 @@ public function __construct($objects) */ public function getValue() { - return $this->objects; + return $this->objects; } /** @@ -51,8 +49,8 @@ public function getValue() */ public function _encode() { - return array('__op' => 'AddUnique', - 'objects' => ParseClient::_encode($this->objects, true)); + return ['__op' => 'AddUnique', + 'objects' => ParseClient::_encode($this->objects, true), ]; } /** @@ -60,28 +58,31 @@ public function _encode() * * @param FieldOperation $previous Previous Operation. * - * @return FieldOperation Merged Operation. * @throws ParseException + * + * @return FieldOperation Merged Operation. */ public function _mergeWithPrevious($previous) { - if (!$previous) { - return $this; - } - if ($previous instanceof DeleteOperation) { - return new SetOperation($this->objects); - } - if ($previous instanceof SetOperation) { - $oldValue = $previous->getValue(); - $result = $this->_apply($oldValue, null, null); - return new SetOperation($result); - } - if ($previous instanceof AddUniqueOperation) { - $oldList = $previous->getValue(); - $result = $this->_apply($oldList, null, null); - return new AddUniqueOperation($result); - } - throw new ParseException( + if (!$previous) { + return $this; + } + if ($previous instanceof DeleteOperation) { + return new SetOperation($this->objects); + } + if ($previous instanceof SetOperation) { + $oldValue = $previous->getValue(); + $result = $this->_apply($oldValue, null, null); + + return new SetOperation($result); + } + if ($previous instanceof AddUniqueOperation) { + $oldList = $previous->getValue(); + $result = $this->_apply($oldList, null, null); + + return new AddUniqueOperation($result); + } + throw new ParseException( 'Operation is invalid after previous operation.' ); } @@ -97,40 +98,41 @@ public function _mergeWithPrevious($previous) */ public function _apply($oldValue, $obj, $key) { - if (!$oldValue) { - return $this->objects; - } - if (!is_array($oldValue)) { - $oldValue = (array)$oldValue; - } - foreach ($this->objects as $object) { - if ($object instanceof ParseObject && $object->getObjectId()) { - if (!$this->isParseObjectInArray($object, $oldValue)) { - $oldValue[] = $object; - } - } else if (is_object($object)) { - if (!in_array($object, $oldValue, true)) { - $oldValue[] = $object; - } - } else { - if (!in_array($object, $oldValue, true)) { - $oldValue[] = $object; - } + if (!$oldValue) { + return $this->objects; } - } - return $oldValue; + if (!is_array($oldValue)) { + $oldValue = (array) $oldValue; + } + foreach ($this->objects as $object) { + if ($object instanceof ParseObject && $object->getObjectId()) { + if (!$this->isParseObjectInArray($object, $oldValue)) { + $oldValue[] = $object; + } + } elseif (is_object($object)) { + if (!in_array($object, $oldValue, true)) { + $oldValue[] = $object; + } + } else { + if (!in_array($object, $oldValue, true)) { + $oldValue[] = $object; + } + } + } + + return $oldValue; } - private function isParseObjectInArray($parseObject, $oldValue) - { - foreach ($oldValue as $object) { - if ($object instanceof ParseObject && $object->getObjectId() != null) { - if ($object->getObjectId() == $parseObject->getObjectId()) { - return true; + private function isParseObjectInArray($parseObject, $oldValue) + { + foreach ($oldValue as $object) { + if ($object instanceof ParseObject && $object->getObjectId() != null) { + if ($object->getObjectId() == $parseObject->getObjectId()) { + return true; + } + } } - } - } - return false; - } -} \ No newline at end of file + return false; + } +} diff --git a/src/Parse/Internal/DeleteOperation.php b/src/Parse/Internal/DeleteOperation.php index c55e0544..509c31cd 100755 --- a/src/Parse/Internal/DeleteOperation.php +++ b/src/Parse/Internal/DeleteOperation.php @@ -5,12 +5,10 @@ /** * Class DeleteOperation - FieldOperation to remove a key from an object. * - * @package Parse * @author Fosco Marotto */ class DeleteOperation implements FieldOperation { - /** * Returns an associative array encoding of the current operation. * @@ -18,7 +16,7 @@ class DeleteOperation implements FieldOperation */ public function _encode() { - return array('__op' => 'Delete'); + return ['__op' => 'Delete']; } /** @@ -32,7 +30,7 @@ public function _encode() */ public function _apply($oldValue, $object, $key) { - return null; + return; } /** @@ -44,7 +42,6 @@ public function _apply($oldValue, $object, $key) */ public function _mergeWithPrevious($previous) { - return $this; + return $this; } - -} \ No newline at end of file +} diff --git a/src/Parse/Internal/Encodable.php b/src/Parse/Internal/Encodable.php index 0236e8e3..91a0a007 100644 --- a/src/Parse/Internal/Encodable.php +++ b/src/Parse/Internal/Encodable.php @@ -6,17 +6,14 @@ * Class Encodable - Interface for Parse Classes which provide an encode * method. * - * @package Parse * @author Fosco Marotto */ interface Encodable { - /** * Returns an associate array encoding of the implementing class. * * @return mixed */ public function _encode(); - -} \ No newline at end of file +} diff --git a/src/Parse/Internal/FieldOperation.php b/src/Parse/Internal/FieldOperation.php index 5c3b8c94..d8b9b14e 100755 --- a/src/Parse/Internal/FieldOperation.php +++ b/src/Parse/Internal/FieldOperation.php @@ -5,12 +5,10 @@ /** * Class FieldOperation - Interface for all Parse Field Operations. * - * @package Parse * @author Fosco Marotto */ interface FieldOperation extends Encodable { - /** * Applies the current operation and returns the result. * @@ -31,5 +29,4 @@ public function _apply($oldValue, $object, $key); * @return FieldOperation Merged operation result. */ public function _mergeWithPrevious($previous); - -} \ No newline at end of file +} diff --git a/src/Parse/Internal/IncrementOperation.php b/src/Parse/Internal/IncrementOperation.php index d6fe3822..ab429c72 100755 --- a/src/Parse/Internal/IncrementOperation.php +++ b/src/Parse/Internal/IncrementOperation.php @@ -7,12 +7,10 @@ /** * Class IncrementOperation - Operation to increment numeric object key. * - * @package Parse * @author Fosco Marotto */ class IncrementOperation implements FieldOperation { - /** * @var int - Amount to increment by. */ @@ -25,7 +23,7 @@ class IncrementOperation implements FieldOperation */ public function __construct($value = 1) { - $this->value = $value; + $this->value = $value; } /** @@ -35,7 +33,7 @@ public function __construct($value = 1) */ public function getValue() { - return $this->value; + return $this->value; } /** @@ -45,7 +43,7 @@ public function getValue() */ public function _encode() { - return array('__op' => 'Increment', 'amount' => $this->value); + return ['__op' => 'Increment', 'amount' => $this->value]; } /** @@ -55,15 +53,17 @@ public function _encode() * @param mixed $object Value for this operation. * @param string $key Key to set Value on. * - * @return int New value after application. * @throws ParseException + * + * @return int New value after application. */ public function _apply($oldValue, $object, $key) { - if ($oldValue && !is_numeric($oldValue)) { - throw new ParseException('Cannot increment a non-number type.'); - } - return $oldValue + $this->value; + if ($oldValue && !is_numeric($oldValue)) { + throw new ParseException('Cannot increment a non-number type.'); + } + + return $oldValue + $this->value; } /** @@ -72,28 +72,28 @@ public function _apply($oldValue, $object, $key) * * @param FieldOperation $previous Previous Operation. * - * @return FieldOperation * @throws ParseException + * + * @return FieldOperation */ public function _mergeWithPrevious($previous) { - if (!$previous) { - return $this; - } - if ($previous instanceof DeleteOperation) { - return new SetOperation($this->value); - } - if ($previous instanceof SetOperation) { - return new SetOperation($previous->getValue() + $this->value); - } - if ($previous instanceof IncrementOperation) { - return new IncrementOperation( + if (!$previous) { + return $this; + } + if ($previous instanceof DeleteOperation) { + return new SetOperation($this->value); + } + if ($previous instanceof SetOperation) { + return new SetOperation($previous->getValue() + $this->value); + } + if ($previous instanceof IncrementOperation) { + return new IncrementOperation( $previous->getValue() + $this->value ); - } - throw new ParseException( + } + throw new ParseException( 'Operation is invalid after previous operation.' ); } - } diff --git a/src/Parse/Internal/ParseRelationOperation.php b/src/Parse/Internal/ParseRelationOperation.php index 7f92a157..e2c061eb 100644 --- a/src/Parse/Internal/ParseRelationOperation.php +++ b/src/Parse/Internal/ParseRelationOperation.php @@ -1,19 +1,18 @@ */ - -class ParseRelationOperation implements FieldOperation{ - +class ParseRelationOperation implements FieldOperation +{ /** * @var string - The className of the target objects. */ @@ -21,29 +20,29 @@ class ParseRelationOperation implements FieldOperation{ /** * @var array - Array of objects to add to this relation. */ - private $relationsToAdd = array(); + private $relationsToAdd = []; /** * @var array - Array of objects to remove from this relation. */ - private $relationsToRemove = array(); + private $relationsToRemove = []; - public function __construct($objectsToAdd, $objectsToRemove) - { - $this->targetClassName = null; - $this->relationsToAdd['null'] = array(); - $this->relationsToRemove['null'] = array(); - if ( $objectsToAdd !== null) { - $this->checkAndAssignClassName($objectsToAdd); - $this->addObjects($objectsToAdd, $this->relationsToAdd); - } - if ( $objectsToRemove !== null) { - $this->checkAndAssignClassName($objectsToRemove); - $this->addObjects($objectsToRemove, $this->relationsToRemove); - } - if ($this->targetClassName === null) { - throw new \Exception('Cannot create a ParseRelationOperation with no objects.'); + public function __construct($objectsToAdd, $objectsToRemove) + { + $this->targetClassName = null; + $this->relationsToAdd['null'] = []; + $this->relationsToRemove['null'] = []; + if ($objectsToAdd !== null) { + $this->checkAndAssignClassName($objectsToAdd); + $this->addObjects($objectsToAdd, $this->relationsToAdd); + } + if ($objectsToRemove !== null) { + $this->checkAndAssignClassName($objectsToRemove); + $this->addObjects($objectsToRemove, $this->relationsToRemove); + } + if ($this->targetClassName === null) { + throw new \Exception('Cannot create a ParseRelationOperation with no objects.'); + } } - } /** * Helper function to check that all passed ParseObjects have same class name @@ -55,14 +54,14 @@ public function __construct($objectsToAdd, $objectsToRemove) */ private function checkAndAssignClassName($objects) { - foreach ($objects as $object) { - if ($this->targetClassName === null) { - $this->targetClassName = $object->getClassName(); + foreach ($objects as $object) { + if ($this->targetClassName === null) { + $this->targetClassName = $object->getClassName(); + } + if ($this->targetClassName != $object->getClassName()) { + throw new \Exception('All objects in a relation must be of the same class.'); + } } - if ($this->targetClassName != $object->getClassName()) { - throw new \Exception('All objects in a relation must be of the same class.'); - } - } } /** @@ -74,16 +73,16 @@ private function checkAndAssignClassName($objects) */ private function addObjects($objects, &$container) { - if (!is_array($objects)) { - $objects = [$objects]; - } - foreach ($objects as $object) { - if ($object->getObjectId() == null) { - $container['null'][] = $object; - } else { - $container[$object->getObjectID()] = $object; + if (!is_array($objects)) { + $objects = [$objects]; + } + foreach ($objects as $object) { + if ($object->getObjectId() == null) { + $container['null'][] = $object; + } else { + $container[$object->getObjectID()] = $object; + } } - } } /** @@ -94,23 +93,22 @@ private function addObjects($objects, &$container) */ private function removeObjects($objects, &$container) { - if (!is_array($objects)) { - $objects = [$objects]; - } - $nullObjects = array(); - foreach ($objects as $object) { - if ($object->getObjectId() == null) { - $nullObjects[] = $object; - } else { - unset($container[$object->getObjectID()]); + if (!is_array($objects)) { + $objects = [$objects]; + } + $nullObjects = []; + foreach ($objects as $object) { + if ($object->getObjectId() == null) { + $nullObjects[] = $object; + } else { + unset($container[$object->getObjectID()]); + } + } + if (!empty($nullObjects)) { + self::removeElementsFromArray($nullObjects, $container['null']); } - } - if (!empty($nullObjects)) { - self::removeElementsFromArray($nullObjects, $container['null']); - } } - /** * Applies the current operation and returns the result. * @@ -118,25 +116,26 @@ private function removeObjects($objects, &$container) * @param mixed $object Value for this operation. * @param string $key Key to perform this operation on. * - * @return mixed Result of the operation. - * * @throws \Exception + * + * @return mixed Result of the operation. */ public function _apply($oldValue, $object, $key) { - if ($oldValue == null) { - return new ParseRelation($object, $key, $this->targetClassName); - } else if ($oldValue instanceof ParseRelation) { - if ($this->targetClassName != null + if ($oldValue == null) { + return new ParseRelation($object, $key, $this->targetClassName); + } elseif ($oldValue instanceof ParseRelation) { + if ($this->targetClassName != null && $oldValue->getTargetClass() !== $this->targetClassName) { - throw new \Exception('Related object object must be of class ' - . $this->targetClassName . ', but ' . $oldValue->getTargetClass() - . ' was passed in.'); + throw new \Exception('Related object object must be of class ' + .$this->targetClassName.', but '.$oldValue->getTargetClass() + .' was passed in.'); + } + + return $oldValue; + } else { + throw new \Exception("Operation is invalid after previous operation."); } - return $oldValue; - } else { - throw new \Exception("Operation is invalid after previous operation."); - } } /** @@ -145,92 +144,93 @@ public function _apply($oldValue, $object, $key) * * @param FieldOperation $previous Previous operation. * - * @return FieldOperation Merged operation result. - * * @throws \Exception + * + * @return FieldOperation Merged operation result. */ public function _mergeWithPrevious($previous) { - if ($previous == null) { - return $this; - } - if ($previous instanceof ParseRelationOperation) { - if ($previous->targetClassName != null + if ($previous == null) { + return $this; + } + if ($previous instanceof ParseRelationOperation) { + if ($previous->targetClassName != null && $previous->targetClassName != $this->targetClassName ) { - throw new \Exception('Related object object must be of class ' - . $this->targetClassName . ', but ' . $previous->targetClassName - . ' was passed in.'); - } - $newRelationToAdd = self::convertToOneDimensionalArray( + throw new \Exception('Related object object must be of class ' + .$this->targetClassName.', but '.$previous->targetClassName + .' was passed in.'); + } + $newRelationToAdd = self::convertToOneDimensionalArray( $this->relationsToAdd); - $newRelationToRemove = self::convertToOneDimensionalArray( + $newRelationToRemove = self::convertToOneDimensionalArray( $this->relationsToRemove); - $previous->addObjects($newRelationToAdd, + $previous->addObjects($newRelationToAdd, $previous->relationsToAdd); - $previous->removeObjects($newRelationToAdd, + $previous->removeObjects($newRelationToAdd, $previous->relationsToRemove); - $previous->removeObjects($newRelationToRemove, + $previous->removeObjects($newRelationToRemove, $previous->relationsToAdd); - $previous->addObjects($newRelationToRemove, + $previous->addObjects($newRelationToRemove, $previous->relationsToRemove); - $newRelationToAdd = self::convertToOneDimensionalArray( + $newRelationToAdd = self::convertToOneDimensionalArray( $previous->relationsToAdd); - $newRelationToRemove = self::convertToOneDimensionalArray( + $newRelationToRemove = self::convertToOneDimensionalArray( $previous->relationsToRemove); - return new ParseRelationOperation($newRelationToAdd, + return new ParseRelationOperation($newRelationToAdd, $newRelationToRemove); - } - throw new \Exception('Operation is invalid after previous operation.'); + } + throw new \Exception('Operation is invalid after previous operation.'); } /** * Returns an associative array encoding of the current operation. * - * @return mixed - * * @throws \Exception + * + * @return mixed */ public function _encode() { - $addRelation = array(); - $removeRelation = array(); - if (!empty($this->relationsToAdd)) { - $addRelation = array( - '__op' => 'AddRelation', + $addRelation = []; + $removeRelation = []; + if (!empty($this->relationsToAdd)) { + $addRelation = [ + '__op' => 'AddRelation', 'objects' => ParseClient::_encode( self::convertToOneDimensionalArray($this->relationsToAdd), true - ) - ); - } - if (!empty($this->relationsToRemove)) { - $removeRelation = array( - '__op' => 'RemoveRelation', + ), + ]; + } + if (!empty($this->relationsToRemove)) { + $removeRelation = [ + '__op' => 'RemoveRelation', 'objects' => ParseClient::_encode( self::convertToOneDimensionalArray($this->relationsToRemove), true - ) - ); - } - if (!empty($addRelation) && !empty($removeRelation)) { - return array( + ), + ]; + } + if (!empty($addRelation) && !empty($removeRelation)) { + return [ '__op' => 'Batch', - 'ops' => [$addRelation, $removeRelation] - ); - } - return empty($addRelation) ? $removeRelation : $addRelation; - } + 'ops' => [$addRelation, $removeRelation], + ]; + } - public function _getTargetClass() - { - return $this->targetClassName; + return empty($addRelation) ? $removeRelation : $addRelation; } + public function _getTargetClass() + { + return $this->targetClassName; + } + /** * Remove element or array of elements from one dimensional array. * @@ -239,23 +239,23 @@ public function _getTargetClass() */ public static function removeElementsFromArray($elements, &$array) { - if (!is_array($elements)) { - $elements = [$elements]; - } - $length = count($array); - for ($i = 0; $i < $length; $i++) { - $exist = false; - foreach ($elements as $element) { - if ($array[$i] == $element) { - $exist = true; - break; - } + if (!is_array($elements)) { + $elements = [$elements]; } - if ($exist) { - unset($array[$i]); + $length = count($array); + for ($i = 0; $i < $length; $i++) { + $exist = false; + foreach ($elements as $element) { + if ($array[$i] == $element) { + $exist = true; + break; + } + } + if ($exist) { + unset($array[$i]); + } } - } - $array = array_values($array); + $array = array_values($array); } /** @@ -267,14 +267,15 @@ public static function removeElementsFromArray($elements, &$array) */ public static function convertToOneDimensionalArray($array) { - $newArray = array(); - if (is_array($array)) { - foreach ($array as $value) { - $newArray = array_merge($newArray, self::convertToOneDimensionalArray($value)); + $newArray = []; + if (is_array($array)) { + foreach ($array as $value) { + $newArray = array_merge($newArray, self::convertToOneDimensionalArray($value)); + } + } else { + $newArray[] = $array; } - } else { - $newArray[] = $array; - } - return $newArray; + + return $newArray; } } diff --git a/src/Parse/Internal/RemoveOperation.php b/src/Parse/Internal/RemoveOperation.php index 0e44f11b..f3c180f5 100644 --- a/src/Parse/Internal/RemoveOperation.php +++ b/src/Parse/Internal/RemoveOperation.php @@ -8,14 +8,12 @@ /** * Class RemoveOperation - FieldOperation for removing object(s) from array - * fields + * fields. * - * @package Parse * @author Fosco Marotto */ class RemoveOperation implements FieldOperation { - /** * @var - Array with objects to remove. */ @@ -30,10 +28,10 @@ class RemoveOperation implements FieldOperation */ public function __construct($objects) { - if (!is_array($objects)) { - throw new ParseException("RemoveOperation requires an array."); - } - $this->objects = $objects; + if (!is_array($objects)) { + throw new ParseException("RemoveOperation requires an array."); + } + $this->objects = $objects; } /** @@ -43,7 +41,7 @@ public function __construct($objects) */ public function getValue() { - return $this->objects; + return $this->objects; } /** @@ -53,8 +51,8 @@ public function getValue() */ public function _encode() { - return array('__op' => 'Remove', - 'objects' => ParseClient::_encode($this->objects, true)); + return ['__op' => 'Remove', + 'objects' => ParseClient::_encode($this->objects, true), ]; } /** @@ -62,29 +60,31 @@ public function _encode() * * @param FieldOperation $previous Previous operation. * - * @return FieldOperation Merged operation. * @throws ParseException + * + * @return FieldOperation Merged operation. */ public function _mergeWithPrevious($previous) { - if (!$previous) { - return $this; - } - if ($previous instanceof DeleteOperation) { - return $previous; - } - if ($previous instanceof SetOperation) { - return new SetOperation( + if (!$previous) { + return $this; + } + if ($previous instanceof DeleteOperation) { + return $previous; + } + if ($previous instanceof SetOperation) { + return new SetOperation( $this->_apply($previous->getValue(), $this->objects, null) ); - } - if ($previous instanceof RemoveOperation) { - $oldList = $previous->getValue(); - return new RemoveOperation( - array_merge((array)$oldList, (array)$this->objects) + } + if ($previous instanceof RemoveOperation) { + $oldList = $previous->getValue(); + + return new RemoveOperation( + array_merge((array) $oldList, (array) $this->objects) ); - } - throw new ParseException( + } + throw new ParseException( 'Operation is invalid after previous operation.' ); } @@ -100,28 +100,28 @@ public function _mergeWithPrevious($previous) */ public function _apply($oldValue, $obj, $key) { - if (empty($oldValue)) { - return array(); - } - $newValue = array(); - foreach ($oldValue as $oldObject) { - foreach ($this->objects as $newObject) { - if ($oldObject instanceof ParseObject) { - if ($newObject instanceof ParseObject + if (empty($oldValue)) { + return []; + } + $newValue = []; + foreach ($oldValue as $oldObject) { + foreach ($this->objects as $newObject) { + if ($oldObject instanceof ParseObject) { + if ($newObject instanceof ParseObject && !$oldObject->isDirty() && $oldObject->getObjectId() == $newObject->getObjectId()) { - // found the object, won't add it. - } else { - $newValue[] = $oldObject; + // found the object, won't add it. + } else { + $newValue[] = $oldObject; + } + } else { + if ($oldObject !== $newObject) { + $newValue[] = $oldObject; + } + } } - } else { - if ($oldObject !== $newObject) { - $newValue[] = $oldObject; - } - } } - } - return $newValue; - } -} \ No newline at end of file + return $newValue; + } +} diff --git a/src/Parse/Internal/SetOperation.php b/src/Parse/Internal/SetOperation.php index df3b6099..aea27255 100755 --- a/src/Parse/Internal/SetOperation.php +++ b/src/Parse/Internal/SetOperation.php @@ -7,12 +7,10 @@ /** * Class SetOperation - Operation to set a value for an object key. * - * @package Parse * @author Fosco Marotto */ class SetOperation implements FieldOperation { - /** * @var - Value to set for this operation. */ @@ -31,8 +29,8 @@ class SetOperation implements FieldOperation */ public function __construct($value, $isAssociativeArray = false) { - $this->value = $value; - $this->isAssociativeArray = $isAssociativeArray; + $this->value = $value; + $this->isAssociativeArray = $isAssociativeArray; } /** @@ -42,7 +40,7 @@ public function __construct($value, $isAssociativeArray = false) */ public function getValue() { - return $this->value; + return $this->value; } /** @@ -52,14 +50,16 @@ public function getValue() */ public function _encode() { - if ($this->isAssociativeArray) { - $object = new \stdClass(); - foreach ($this->value as $key => $value) { - $object->$key = ParseClient::_encode($value, true); + if ($this->isAssociativeArray) { + $object = new \stdClass(); + foreach ($this->value as $key => $value) { + $object->$key = ParseClient::_encode($value, true); + } + + return ParseClient::_encode($object, true); } - return ParseClient::_encode($object, true); - } - return ParseClient::_encode($this->value, true); + + return ParseClient::_encode($this->value, true); } /** @@ -73,7 +73,7 @@ public function _encode() */ public function _apply($oldValue, $object, $key) { - return $this->value; + return $this->value; } /** @@ -86,7 +86,6 @@ public function _apply($oldValue, $object, $key) */ public function _mergeWithPrevious($previous) { - return $this; + return $this; } - -} \ No newline at end of file +} diff --git a/src/Parse/ParseACL.php b/src/Parse/ParseACL.php index d56fc56b..f216098d 100644 --- a/src/Parse/ParseACL.php +++ b/src/Parse/ParseACL.php @@ -12,11 +12,10 @@ * example, any user could read a particular object but only a particular set * of users could write to that object. * - * @package Parse * @author Mohamed Madbouli */ -class ParseACL implements Encodable{ - +class ParseACL implements Encodable +{ /* * @ignore */ @@ -24,7 +23,7 @@ class ParseACL implements Encodable{ /** * @var array - */ - private $permissionsById = array(); + private $permissionsById = []; /** * @var bool - */ @@ -55,10 +54,11 @@ class ParseACL implements Encodable{ */ public static function createACLWithUser($user) { - $acl = new ParseACL(); - $acl->setUserReadAccess($user, true); - $acl->setUserWriteAccess($user, true); - return $acl; + $acl = new ParseACL(); + $acl->setUserReadAccess($user, true); + $acl->setUserWriteAccess($user, true); + + return $acl; } /** @@ -66,30 +66,32 @@ public static function createACLWithUser($user) * * @param array $data represents permissions. * - * @return ParseACL * @throws \Exception + * + * @return ParseACL * @ignore */ public static function _createACLFromJSON($data) { - $acl = new ParseACL(); - foreach ($data as $id => $permissions) { - if (!is_string($id)) { - throw new \Exception('Tried to create an ACL with an invalid userId.'); - } - foreach ($permissions as $accessType => $value) { - if ($accessType !== 'read' && $accessType !== 'write') { - throw new \Exception( + $acl = new ParseACL(); + foreach ($data as $id => $permissions) { + if (!is_string($id)) { + throw new \Exception('Tried to create an ACL with an invalid userId.'); + } + foreach ($permissions as $accessType => $value) { + if ($accessType !== 'read' && $accessType !== 'write') { + throw new \Exception( 'Tried to create an ACL with an invalid permission type.'); - } - if (!is_bool($value)) { - throw new \Exception( + } + if (!is_bool($value)) { + throw new \Exception( 'Tried to create an ACL with an invalid permission value.'); - } - $acl->setAccess($accessType, $id, $value); + } + $acl->setAccess($accessType, $id, $value); + } } - } - return $acl; + + return $acl; } /** @@ -100,18 +102,18 @@ public static function _createACLFromJSON($data) */ public function _isShared() { - return $this->shared; + return $this->shared; } /** - * Set shared for ParseACL + * Set shared for ParseACL. * * @param bool $shared * @ignore */ public function _setShared($shared) { - $this->shared = $shared; + $this->shared = $shared; } /** @@ -119,10 +121,11 @@ public function _setShared($shared) */ public function _encode() { - if (empty($this->permissionsById)) { - return new \stdClass(); - } - return $this->permissionsById; + if (empty($this->permissionsById)) { + return new \stdClass(); + } + + return $this->permissionsById; } /** @@ -137,31 +140,31 @@ public function _encode() */ private function setAccess($accessType, $userId, $allowed) { - if ($userId instanceof ParseUser) { - $userId = $userId->getObjectId(); - } - if ($userId instanceof ParseRole) { - $userId = "role:" . $userId->getName(); - } - if (!is_string($userId)) { - throw new ParseException( + if ($userId instanceof ParseUser) { + $userId = $userId->getObjectId(); + } + if ($userId instanceof ParseRole) { + $userId = "role:".$userId->getName(); + } + if (!is_string($userId)) { + throw new ParseException( "Invalid target for access control." ); - } - if (!isset($this->permissionsById[$userId])) { - if (!$allowed) { - return; } - $this->permissionsById[$userId] = array(); - } - if ($allowed) { - $this->permissionsById[$userId][$accessType] = true; - } else { - unset($this->permissionsById[$userId][$accessType]); - if (empty($this->permissionsById[$userId])) { - unset($this->permissionsById[$userId]); + if (!isset($this->permissionsById[$userId])) { + if (!$allowed) { + return; + } + $this->permissionsById[$userId] = []; + } + if ($allowed) { + $this->permissionsById[$userId][$accessType] = true; + } else { + unset($this->permissionsById[$userId][$accessType]); + if (empty($this->permissionsById[$userId])) { + unset($this->permissionsById[$userId]); + } } - } } /** @@ -174,13 +177,14 @@ private function setAccess($accessType, $userId, $allowed) */ private function getAccess($accessType, $userId) { - if (!isset($this->permissionsById[$userId])) { - return false; - } - if (!isset($this->permissionsById[$userId][$accessType])) { - return false; - } - return $this->permissionsById[$userId][$accessType]; + if (!isset($this->permissionsById[$userId])) { + return false; + } + if (!isset($this->permissionsById[$userId][$accessType])) { + return false; + } + + return $this->permissionsById[$userId][$accessType]; } /** @@ -193,10 +197,10 @@ private function getAccess($accessType, $userId) */ public function setReadAccess($userId, $allowed) { - if (!$userId) { - throw new \Exception("cannot setReadAccess for null userId"); - } - $this->setAccess('read', $userId, $allowed); + if (!$userId) { + throw new \Exception("cannot setReadAccess for null userId"); + } + $this->setAccess('read', $userId, $allowed); } /** @@ -207,16 +211,17 @@ public function setReadAccess($userId, $allowed) * * @param string $userId User id. * - * @return bool - * * @throws \Exception + * + * @return bool */ public function getReadAccess($userId) { - if (!$userId) { - throw new \Exception("cannot getReadAccess for null userId"); - } - return $this->getAccess('read', $userId); + if (!$userId) { + throw new \Exception("cannot getReadAccess for null userId"); + } + + return $this->getAccess('read', $userId); } /** @@ -229,10 +234,10 @@ public function getReadAccess($userId) */ public function setWriteAccess($userId, $allowed) { - if (!$userId) { - throw new \Exception("cannot setWriteAccess for null userId"); - } - $this->setAccess('write', $userId, $allowed); + if (!$userId) { + throw new \Exception("cannot setWriteAccess for null userId"); + } + $this->setAccess('write', $userId, $allowed); } /** @@ -243,18 +248,18 @@ public function setWriteAccess($userId, $allowed) * * @param string $userId User id. * - * @return bool - * * @throws \Exception + * + * @return bool */ public function getWriteAccess($userId) { - if (!$userId) { - throw new \Exception("cannot getWriteAccess for null userId"); - } - return $this->getAccess('write', $userId); - } + if (!$userId) { + throw new \Exception("cannot getWriteAccess for null userId"); + } + return $this->getAccess('write', $userId); + } /** * Set whether the public is allowed to read this object. @@ -263,7 +268,7 @@ public function getWriteAccess($userId) */ public function setPublicReadAccess($allowed) { - $this->setReadAccess(self::PUBLIC_KEY, $allowed); + $this->setReadAccess(self::PUBLIC_KEY, $allowed); } /** @@ -273,7 +278,7 @@ public function setPublicReadAccess($allowed) */ public function getPublicReadAccess() { - return $this->getReadAccess(self::PUBLIC_KEY); + return $this->getReadAccess(self::PUBLIC_KEY); } /** @@ -283,7 +288,7 @@ public function getPublicReadAccess() */ public function setPublicWriteAccess($allowed) { - $this->setWriteAccess(self::PUBLIC_KEY, $allowed); + $this->setWriteAccess(self::PUBLIC_KEY, $allowed); } /** @@ -293,7 +298,7 @@ public function setPublicWriteAccess($allowed) */ public function getPublicWriteAccess() { - return $this->getWriteAccess(self::PUBLIC_KEY); + return $this->getWriteAccess(self::PUBLIC_KEY); } /** @@ -306,10 +311,10 @@ public function getPublicWriteAccess() */ public function setUserReadAccess($user, $allowed) { - if (!$user->getObjectId()) { - throw new \Exception("cannot setReadAccess for a user with null id"); - } - $this->setReadAccess($user->getObjectId(), $allowed); + if (!$user->getObjectId()) { + throw new \Exception("cannot setReadAccess for a user with null id"); + } + $this->setReadAccess($user->getObjectId(), $allowed); } /** @@ -320,16 +325,17 @@ public function setUserReadAccess($user, $allowed) * * @param ParseUser $user * - * @return bool - * * @throws \Exception + * + * @return bool */ public function getUserReadAccess($user) { - if (!$user->getObjectId()) { - throw new \Exception("cannot getReadAccess for a user with null id"); - } - return $this->getReadAccess($user->getObjectId()); + if (!$user->getObjectId()) { + throw new \Exception("cannot getReadAccess for a user with null id"); + } + + return $this->getReadAccess($user->getObjectId()); } /** @@ -342,10 +348,10 @@ public function getUserReadAccess($user) */ public function setUserWriteAccess($user, $allowed) { - if (!$user->getObjectId()) { - throw new \Exception("cannot setWriteAccess for a user with null id"); - } - $this->setWriteAccess($user->getObjectId(), $allowed); + if (!$user->getObjectId()) { + throw new \Exception("cannot setWriteAccess for a user with null id"); + } + $this->setWriteAccess($user->getObjectId(), $allowed); } /** @@ -356,16 +362,17 @@ public function setUserWriteAccess($user, $allowed) * * @param ParseUser $user * - * @return bool - * * @throws \Exception + * + * @return bool */ public function getUserWriteAccess($user) { - if (!$user->getObjectId()) { - throw new \Exception("cannot getWriteAccess for a user with null id"); - } - return $this->getWriteAccess($user->getObjectId()); + if (!$user->getObjectId()) { + throw new \Exception("cannot getWriteAccess for a user with null id"); + } + + return $this->getWriteAccess($user->getObjectId()); } /** @@ -379,7 +386,7 @@ public function getUserWriteAccess($user) */ public function getRoleReadAccessWithName($roleName) { - return $this->getReadAccess('role:' . $roleName); + return $this->getReadAccess('role:'.$roleName); } /** @@ -387,12 +394,11 @@ public function getRoleReadAccessWithName($roleName) * are allowed to read this object. * * @param string $roleName The name of the role. - * * @param bool $allowed Whether the given role can read this object. */ public function setRoleReadAccessWithName($roleName, $allowed) { - $this->setReadAccess('role:' . $roleName, $allowed); + $this->setReadAccess('role:'.$roleName, $allowed); } /** @@ -406,7 +412,7 @@ public function setRoleReadAccessWithName($roleName, $allowed) */ public function getRoleWriteAccessWithName($roleName) { - return $this->getWriteAccess('role:' . $roleName); + return $this->getWriteAccess('role:'.$roleName); } /** @@ -418,7 +424,7 @@ public function getRoleWriteAccessWithName($roleName) */ public function setRoleWriteAccessWithName($roleName, $allowed) { - $this->setWriteAccess('role:' . $roleName, $allowed); + $this->setWriteAccess('role:'.$roleName, $allowed); } /** @@ -430,10 +436,10 @@ public function setRoleWriteAccessWithName($roleName, $allowed) */ private static function validateRoleState($role) { - if (!$role->getObjectId()) { - throw new \Exception( + if (!$role->getObjectId()) { + throw new \Exception( "Roles must be saved to the server before they can be used in an ACL."); - } + } } /** @@ -448,8 +454,9 @@ private static function validateRoleState($role) */ public function getRoleReadAccess($role) { - $this->validateRoleState($role); - return $this->getRoleReadAccessWithName($role->getName()); + $this->validateRoleState($role); + + return $this->getRoleReadAccessWithName($role->getName()); } /** @@ -462,8 +469,8 @@ public function getRoleReadAccess($role) */ public function setRoleReadAccess($role, $allowed) { - $this->validateRoleState($role); - $this->setRoleReadAccessWithName($role->getName(), $allowed); + $this->validateRoleState($role); + $this->setRoleReadAccessWithName($role->getName(), $allowed); } /** @@ -478,8 +485,9 @@ public function setRoleReadAccess($role, $allowed) */ public function getRoleWriteAccess($role) { - $this->validateRoleState($role); - return $this->getRoleWriteAccessWithName($role->getName()); + $this->validateRoleState($role); + + return $this->getRoleWriteAccessWithName($role->getName()); } /** @@ -492,8 +500,8 @@ public function getRoleWriteAccess($role) */ public function setRoleWriteAccess($role, $allowed) { - $this->validateRoleState($role); - $this->setRoleWriteAccessWithName($role->getName(), $allowed); + $this->validateRoleState($role); + $this->setRoleWriteAccessWithName($role->getName(), $allowed); } /** @@ -515,15 +523,15 @@ public function setRoleWriteAccess($role, $allowed) */ public static function setDefaultACL($acl, $withAccessForCurrentUser) { - self::$defaultACLWithCurrentUser = null; - self::$lastCurrentUser = null; - if ($acl) { - self::$defaultACL = clone $acl; - self::$defaultACL->_setShared(true); - self::$defaultACLUsesCurrentUser = $withAccessForCurrentUser; - } else { - self::$defaultACL = null; - } + self::$defaultACLWithCurrentUser = null; + self::$lastCurrentUser = null; + if ($acl) { + self::$defaultACL = clone $acl; + self::$defaultACL->_setShared(true); + self::$defaultACLUsesCurrentUser = $withAccessForCurrentUser; + } else { + self::$defaultACL = null; + } } /** @@ -534,21 +542,22 @@ public static function setDefaultACL($acl, $withAccessForCurrentUser) */ public static function _getDefaultACL() { - if (self::$defaultACLUsesCurrentUser && self::$defaultACL) { - $last = self::$lastCurrentUser ? clone self::$lastCurrentUser : null; - if (!ParseUser::getCurrentUser()) { - return self::$defaultACL; + if (self::$defaultACLUsesCurrentUser && self::$defaultACL) { + $last = self::$lastCurrentUser ? clone self::$lastCurrentUser : null; + if (!ParseUser::getCurrentUser()) { + return self::$defaultACL; + } + if ($last != ParseUser::getCurrentUser()) { + self::$defaultACLWithCurrentUser = clone self::$defaultAC; + self::$defaultACLWithCurrentUser->_setShared(true); + self::$defaultACLWithCurrentUser->setUserReadAccess(ParseUser::getCurrentUser(), true); + self::$defaultACLWithCurrentUser->setUserWriteAccess(ParseUser::getCurrentUser(), true); + self::$lastCurrentUser = clone ParseUser::getCurrentUser(); + } + + return self::$defaultACLWithCurrentUser; } - if ($last != ParseUser::getCurrentUser()) { - self::$defaultACLWithCurrentUser = clone self::$defaultAC; - self::$defaultACLWithCurrentUser->_setShared(true); - self::$defaultACLWithCurrentUser->setUserReadAccess(ParseUser::getCurrentUser(), true); - self::$defaultACLWithCurrentUser->setUserWriteAccess(ParseUser::getCurrentUser(), true); - self::$lastCurrentUser = clone ParseUser::getCurrentUser(); - } - return self::$defaultACLWithCurrentUser; - } - return self::$defaultACL; - } + return self::$defaultACL; + } } diff --git a/src/Parse/ParseAggregateException.php b/src/Parse/ParseAggregateException.php index 58410118..caa16623 100644 --- a/src/Parse/ParseAggregateException.php +++ b/src/Parse/ParseAggregateException.php @@ -3,27 +3,25 @@ namespace Parse; /** - * ParseAggregateException - Multiple error condition + * ParseAggregateException - Multiple error condition. * - * @package Parse * @author Fosco Marotto */ class ParseAggregateException extends ParseException { - private $errors; /** - * Constructs a Parse\ParseAggregateException + * Constructs a Parse\ParseAggregateException. * * @param string $message Message for the Exception. * @param array $errors Collection of error values. * @param \Exception $previous Previous exception. */ - public function __construct($message, $errors = array(), $previous = null) + public function __construct($message, $errors = [], $previous = null) { - parent::__construct($message, 600, $previous); - $this->errors = $errors; + parent::__construct($message, 600, $previous); + $this->errors = $errors; } /** @@ -33,7 +31,6 @@ public function __construct($message, $errors = array(), $previous = null) */ public function getErrors() { - return $this->errors; + return $this->errors; } - -} \ No newline at end of file +} diff --git a/src/Parse/ParseAnalytics.php b/src/Parse/ParseAnalytics.php index 8f40b22a..40160958 100644 --- a/src/Parse/ParseAnalytics.php +++ b/src/Parse/ParseAnalytics.php @@ -2,17 +2,15 @@ namespace Parse; -use \Exception; +use Exception; /** - * ParseAnalytics - Handles sending app-open and custom analytics events + * ParseAnalytics - Handles sending app-open and custom analytics events. * - * @package Parse * @author Fosco Marotto */ class ParseAnalytics { - /** * Tracks the occurrence of a custom event with additional dimensions. * Parse will store a data point at the time of invocation with the given @@ -39,22 +37,24 @@ class ParseAnalytics * @param array $dimensions The dictionary of segment information * * @throws \Exception + * * @return mixed */ - public static function track($name, $dimensions = array()) + public static function track($name, $dimensions = []) { - $name = trim($name); - if (strlen($name) === 0) { - throw new Exception('A name for the custom event must be provided.'); - } - foreach ($dimensions as $key => $value) { - if (!is_string($key) || !is_string($value)) { - throw new Exception('Dimensions expected string keys and values.'); + $name = trim($name); + if (strlen($name) === 0) { + throw new Exception('A name for the custom event must be provided.'); + } + foreach ($dimensions as $key => $value) { + if (!is_string($key) || !is_string($value)) { + throw new Exception('Dimensions expected string keys and values.'); + } } - } - return ParseClient::_request( + + return ParseClient::_request( 'POST', - '/1/events/' . $name, + '/1/events/'.$name, null, static::_toSaveJSON($dimensions) ); @@ -65,12 +65,11 @@ public static function track($name, $dimensions = array()) */ public static function _toSaveJSON($data) { - return json_encode( - array( - 'dimensions' => $data - ), + return json_encode( + [ + 'dimensions' => $data, + ], JSON_FORCE_OBJECT ); } - -} \ No newline at end of file +} diff --git a/src/Parse/ParseBytes.php b/src/Parse/ParseBytes.php index 506f72a4..e2bd517b 100644 --- a/src/Parse/ParseBytes.php +++ b/src/Parse/ParseBytes.php @@ -5,12 +5,10 @@ /** * ParseBytes - Representation of a Byte array for storage on a Parse Object. * - * @package Parse * @author Fosco Marotto */ class ParseBytes implements Internal\Encodable { - /** * @var - byte array */ @@ -25,13 +23,14 @@ class ParseBytes implements Internal\Encodable */ public static function createFromByteArray(array $byteArray) { - $bytes = new ParseBytes(); - $bytes->setByteArray($byteArray); - return $bytes; + $bytes = new ParseBytes(); + $bytes->setByteArray($byteArray); + + return $bytes; } /** - * Create a ParseBytes object with a given base 64 encoded data string + * Create a ParseBytes object with a given base 64 encoded data string. * * @param string $base64Data * @@ -39,37 +38,39 @@ public static function createFromByteArray(array $byteArray) */ public static function createFromBase64Data($base64Data) { - $bytes = new ParseBytes(); - $bytes->setBase64Data($base64Data); - return $bytes; - } + $bytes = new ParseBytes(); + $bytes->setBase64Data($base64Data); - private function setBase64Data($base64Data) - { - $byteArray = unpack('C*', base64_decode($base64Data)); - $this->setByteArray($byteArray); + return $bytes; } - private function setByteArray(array $byteArray) - { - $this->byteArray = $byteArray; - } + private function setBase64Data($base64Data) + { + $byteArray = unpack('C*', base64_decode($base64Data)); + $this->setByteArray($byteArray); + } + + private function setByteArray(array $byteArray) + { + $this->byteArray = $byteArray; + } /** - * Encode to associative array representation + * Encode to associative array representation. * * @return array * @ignore */ public function _encode() { - $data = ""; - foreach ($this->byteArray as $byte) { - $data .= chr($byte); - } - return array( + $data = ""; + foreach ($this->byteArray as $byte) { + $data .= chr($byte); + } + + return [ '__type' => 'Bytes', - 'base64' => base64_encode($data) - ); + 'base64' => base64_encode($data), + ]; } } diff --git a/src/Parse/ParseClient.php b/src/Parse/ParseClient.php index d85742a1..5574c336 100755 --- a/src/Parse/ParseClient.php +++ b/src/Parse/ParseClient.php @@ -5,16 +5,15 @@ use Parse\Internal\Encodable; /** - * ParseClient - Main class for Parse initialization and communication + * ParseClient - Main class for Parse initialization and communication. * - * @package Parse * @author Fosco Marotto */ final class ParseClient { - /** * Constant for the API Server Host Address. + * * @ignore */ const HOST_NAME = 'https://api.parse.com'; @@ -51,6 +50,7 @@ final class ParseClient /** * Constant for version string to include with requests. + * * @ignore */ const VERSION_STRING = 'php1.1.0'; @@ -67,21 +67,21 @@ final class ParseClient */ public static function initialize($app_id, $rest_key, $master_key, $enableCurlExceptions = true) { - ParseUser::registerSubclass(); - ParseRole::registerSubclass(); - ParseInstallation::registerSubclass(); - ParseSession::registerSubclass(); - self::$applicationId = $app_id; - self::$restKey = $rest_key; - self::$masterKey = $master_key; - self::$enableCurlExceptions = $enableCurlExceptions; - if (!static::$storage) { - if (session_status() === PHP_SESSION_ACTIVE) { - self::setStorage(new ParseSessionStorage()); - } else { - self::setStorage(new ParseMemoryStorage()); + ParseUser::registerSubclass(); + ParseRole::registerSubclass(); + ParseInstallation::registerSubclass(); + ParseSession::registerSubclass(); + self::$applicationId = $app_id; + self::$restKey = $rest_key; + self::$masterKey = $master_key; + self::$enableCurlExceptions = $enableCurlExceptions; + if (!static::$storage) { + if (session_status() === PHP_SESSION_ACTIVE) { + self::setStorage(new ParseSessionStorage()); + } else { + self::setStorage(new ParseMemoryStorage()); + } } - } } /** @@ -90,42 +90,45 @@ public static function initialize($app_id, $rest_key, $master_key, $enableCurlEx * @param mixed $value Value to encode * @param bool $allowParseObjects Allow nested objects * + * @throws \Exception + * * @return mixed Encoded results. * - * @throws \Exception * @ignore */ public static function _encode($value, $allowParseObjects) { - if ($value instanceof \DateTime) { - return array( - '__type' => 'Date', 'iso' => self::getProperDateFormat($value) - ); - } + if ($value instanceof \DateTime) { + return [ + '__type' => 'Date', 'iso' => self::getProperDateFormat($value), + ]; + } - if ($value instanceof \stdClass) { - return $value; - } + if ($value instanceof \stdClass) { + return $value; + } + + if ($value instanceof ParseObject) { + if (!$allowParseObjects) { + throw new \Exception('ParseObjects not allowed here.'); + } - if ($value instanceof ParseObject) { - if (!$allowParseObjects) { - throw new \Exception('ParseObjects not allowed here.'); + return $value->_toPointer(); } - return $value->_toPointer(); - } - if ($value instanceof Encodable) { - return $value->_encode(); - } + if ($value instanceof Encodable) { + return $value->_encode(); + } - if (is_array($value)) { - return self::_encodeArray($value, $allowParseObjects); - } + if (is_array($value)) { + return self::_encodeArray($value, $allowParseObjects); + } - if (!is_scalar($value) && $value !== null) { - throw new \Exception('Invalid type encountered.'); - } - return $value; + if (!is_scalar($value) && $value !== null) { + throw new \Exception('Invalid type encountered.'); + } + + return $value; } /** @@ -138,61 +141,62 @@ public static function _encode($value, $allowParseObjects) */ public static function _decode($data) { - // The json decoded response from Parse will make JSONObjects into stdClass + // The json decoded response from Parse will make JSONObjects into stdClass // objects. We'll change it to an associative array here. if ($data instanceof \stdClass) { - $tmp = (array)$data; - if (!empty($tmp)) { - return self::_decode(get_object_vars($data)); - } + $tmp = (array) $data; + if (!empty($tmp)) { + return self::_decode(get_object_vars($data)); + } } - if (!$data && !is_array($data)) { - return null; - } + if (!$data && !is_array($data)) { + return; + } - if (is_array($data)) { - $typeString = (isset($data['__type']) ? $data['__type'] : null); + if (is_array($data)) { + $typeString = (isset($data['__type']) ? $data['__type'] : null); - if ($typeString === 'Date') { - return new \DateTime($data['iso']); - } + if ($typeString === 'Date') { + return new \DateTime($data['iso']); + } - if ($typeString === 'Bytes') { - return base64_decode($data['base64']); - } + if ($typeString === 'Bytes') { + return base64_decode($data['base64']); + } - if ($typeString === 'Pointer') { - return ParseObject::create($data['className'], $data['objectId']); - } + if ($typeString === 'Pointer') { + return ParseObject::create($data['className'], $data['objectId']); + } - if ($typeString === 'File') { - return ParseFile::_createFromServer($data['name'], $data['url']); - } + if ($typeString === 'File') { + return ParseFile::_createFromServer($data['name'], $data['url']); + } - if ($typeString === 'GeoPoint') { - return new ParseGeoPoint($data['latitude'], $data['longitude']); - } + if ($typeString === 'GeoPoint') { + return new ParseGeoPoint($data['latitude'], $data['longitude']); + } - if ($typeString === 'Object') { - $output = ParseObject::create($data['className']); - $output->_mergeAfterFetch($data); - return $output; - } + if ($typeString === 'Object') { + $output = ParseObject::create($data['className']); + $output->_mergeAfterFetch($data); - if ($typeString === 'Relation') { - return $data; - } + return $output; + } - $newDict = array(); - foreach ($data as $key => $value) { - $newDict[$key] = static::_decode($value); - } - return $newDict; + if ($typeString === 'Relation') { + return $data; + } - } + $newDict = []; + foreach ($data as $key => $value) { + $newDict[$key] = static::_decode($value); + } - return $data; + return $newDict; + } + + return $data; } /** @@ -206,11 +210,12 @@ public static function _decode($data) */ public static function _encodeArray($value, $allowParseObjects) { - $output = array(); - foreach ($value as $key => $item) { - $output[$key] = self::_encode($item, $allowParseObjects); - } - return $output; + $output = []; + foreach ($value as $key => $item) { + $output[$key] = self::_encode($item, $allowParseObjects); + } + + return $output; } /** @@ -222,63 +227,64 @@ public static function _encodeArray($value, $allowParseObjects) * @param null $data Data to provide with the request. * @param bool $useMasterKey Whether to use the Master Key. * - * @return mixed Result from Parse API Call. * @throws \Exception + * + * @return mixed Result from Parse API Call. * @ignore */ public static function _request($method, $relativeUrl, $sessionToken = null, $data = null, $useMasterKey = false) { - if ($data === '[]') { - $data = '{}'; - } - self::assertParseInitialized(); - $headers = self::_getRequestHeaders($sessionToken, $useMasterKey); + if ($data === '[]') { + $data = '{}'; + } + self::assertParseInitialized(); + $headers = self::_getRequestHeaders($sessionToken, $useMasterKey); - $url = self::HOST_NAME . $relativeUrl; - if ($method === 'GET' && !empty($data)) { - $url .= '?' . http_build_query($data); - } - $rest = curl_init(); - curl_setopt($rest, CURLOPT_URL, $url); - curl_setopt($rest, CURLOPT_RETURNTRANSFER, 1); - if ($method === 'POST') { - $headers[] = 'Content-Type: application/json'; - curl_setopt($rest, CURLOPT_POST, 1); - curl_setopt($rest, CURLOPT_POSTFIELDS, $data); - } - if ($method === 'PUT') { - $headers[] = 'Content-Type: application/json'; - curl_setopt($rest, CURLOPT_CUSTOMREQUEST, $method); - curl_setopt($rest, CURLOPT_POSTFIELDS, $data); - } - if ($method === 'DELETE') { - curl_setopt($rest, CURLOPT_CUSTOMREQUEST, $method); - } - curl_setopt($rest, CURLOPT_HTTPHEADER, $headers); - $response = curl_exec($rest); - $status = curl_getinfo($rest, CURLINFO_HTTP_CODE); - $contentType = curl_getinfo($rest, CURLINFO_CONTENT_TYPE); - if (curl_errno($rest)) { - if (self::$enableCurlExceptions) { - throw new ParseException(curl_error($rest), curl_errno($rest)); - } else { - return false; + $url = self::HOST_NAME.$relativeUrl; + if ($method === 'GET' && !empty($data)) { + $url .= '?'.http_build_query($data); + } + $rest = curl_init(); + curl_setopt($rest, CURLOPT_URL, $url); + curl_setopt($rest, CURLOPT_RETURNTRANSFER, 1); + if ($method === 'POST') { + $headers[] = 'Content-Type: application/json'; + curl_setopt($rest, CURLOPT_POST, 1); + curl_setopt($rest, CURLOPT_POSTFIELDS, $data); + } + if ($method === 'PUT') { + $headers[] = 'Content-Type: application/json'; + curl_setopt($rest, CURLOPT_CUSTOMREQUEST, $method); + curl_setopt($rest, CURLOPT_POSTFIELDS, $data); + } + if ($method === 'DELETE') { + curl_setopt($rest, CURLOPT_CUSTOMREQUEST, $method); + } + curl_setopt($rest, CURLOPT_HTTPHEADER, $headers); + $response = curl_exec($rest); + $status = curl_getinfo($rest, CURLINFO_HTTP_CODE); + $contentType = curl_getinfo($rest, CURLINFO_CONTENT_TYPE); + if (curl_errno($rest)) { + if (self::$enableCurlExceptions) { + throw new ParseException(curl_error($rest), curl_errno($rest)); + } else { + return false; + } + } + curl_close($rest); + if (strpos($contentType, 'text/html') !== false) { + throw new ParseException('Bad Request', -1); } - } - curl_close($rest); - if (strpos($contentType, 'text/html') !== false) { - throw new ParseException('Bad Request', -1); - } - $decoded = json_decode($response, true); - if (isset($decoded['error'])) { - throw new ParseException($decoded['error'], + $decoded = json_decode($response, true); + if (isset($decoded['error'])) { + throw new ParseException($decoded['error'], isset($decoded['code']) ? $decoded['code'] : 0 ); - } - return $decoded; + } + return $decoded; } /** @@ -291,7 +297,7 @@ public static function _request($method, $relativeUrl, $sessionToken = null, */ public static function setStorage(ParseStorageInterface $storageObject) { - self::$storage = $storageObject; + self::$storage = $storageObject; } /** @@ -302,7 +308,7 @@ public static function setStorage(ParseStorageInterface $storageObject) */ public static function getStorage() { - return self::$storage; + return self::$storage; } /** @@ -316,17 +322,17 @@ public static function getStorage() */ public static function _unsetStorage() { - self::$storage = null; + self::$storage = null; } - private static function assertParseInitialized() - { - if (self::$applicationId === null) { - throw new \Exception( + private static function assertParseInitialized() + { + if (self::$applicationId === null) { + throw new \Exception( 'You must call Parse::initialize() before making any requests.' ); + } } - } /** * @param $sessionToken @@ -337,26 +343,27 @@ private static function assertParseInitialized() */ public static function _getRequestHeaders($sessionToken, $useMasterKey) { - $headers = array('X-Parse-Application-Id: ' . self::$applicationId, - 'X-Parse-Client-Version: ' . self::VERSION_STRING); - if ($sessionToken) { - $headers[] = 'X-Parse-Session-Token: ' . $sessionToken; - } - if ($useMasterKey) { - $headers[] = 'X-Parse-Master-Key: ' . self::$masterKey; - } else { - $headers[] = 'X-Parse-REST-API-Key: ' . self::$restKey; - } - if (self::$forceRevocableSession) { - $headers[] = 'X-Parse-Revocable-Session: 1'; - } - /** + $headers = ['X-Parse-Application-Id: '.self::$applicationId, + 'X-Parse-Client-Version: '.self::VERSION_STRING, ]; + if ($sessionToken) { + $headers[] = 'X-Parse-Session-Token: '.$sessionToken; + } + if ($useMasterKey) { + $headers[] = 'X-Parse-Master-Key: '.self::$masterKey; + } else { + $headers[] = 'X-Parse-REST-API-Key: '.self::$restKey; + } + if (self::$forceRevocableSession) { + $headers[] = 'X-Parse-Revocable-Session: 1'; + } + /* * Set an empty Expect header to stop the 100-continue behavior for post * data greater than 1024 bytes. * http://pilif.github.io/2007/02/the-return-of-except-100-continue/ */ $headers[] = 'Expect: '; - return $headers; + + return $headers; } /** @@ -371,10 +378,11 @@ public static function _getRequestHeaders($sessionToken, $useMasterKey) */ public static function getProperDateFormat($value) { - $dateFormatString = 'Y-m-d\TH:i:s.u'; - $date = date_format($value, $dateFormatString); - $date = substr($date, 0, -3) . 'Z'; - return $date; + $dateFormatString = 'Y-m-d\TH:i:s.u'; + $date = date_format($value, $dateFormatString); + $date = substr($date, 0, -3).'Z'; + + return $date; } /** @@ -389,9 +397,10 @@ public static function getProperDateFormat($value) */ public static function getLocalPushDateFormat($value) { - $dateFormatString = 'Y-m-d\TH:i:s'; - $date = date_format($value, $dateFormatString); - return $date; + $dateFormatString = 'Y-m-d\TH:i:s'; + $date = date_format($value, $dateFormatString); + + return $date; } /** @@ -403,7 +412,6 @@ public static function getLocalPushDateFormat($value) */ public static function enableRevocableSessions() { - self::$forceRevocableSession = true; + self::$forceRevocableSession = true; } - } diff --git a/src/Parse/ParseCloud.php b/src/Parse/ParseCloud.php index 7891191b..61274fc3 100644 --- a/src/Parse/ParseCloud.php +++ b/src/Parse/ParseCloud.php @@ -3,16 +3,14 @@ namespace Parse; /** - * ParseCloud - Facilitates calling Parse Cloud functions + * ParseCloud - Facilitates calling Parse Cloud functions. * - * @package Parse * @author Fosco Marotto */ class ParseCloud { - /** - * Makes a call to a Cloud function + * Makes a call to a Cloud function. * * @param string $name Cloud function name * @param array $data Parameters to pass @@ -20,20 +18,20 @@ class ParseCloud * * @return mixed */ - public static function run($name, $data = array(), $useMasterKey = false) + public static function run($name, $data = [], $useMasterKey = false) { - $sessionToken = null; - if (ParseUser::getCurrentUser()) { - $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); - } - $response = ParseClient::_request( + $sessionToken = null; + if (ParseUser::getCurrentUser()) { + $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); + } + $response = ParseClient::_request( 'POST', - '/1/functions/' . $name, + '/1/functions/'.$name, $sessionToken, json_encode(ParseClient::_encode($data, null, false)), $useMasterKey ); - return ParseClient::_decode($response['result']); - } -} \ No newline at end of file + return ParseClient::_decode($response['result']); + } +} diff --git a/src/Parse/ParseConfig.php b/src/Parse/ParseConfig.php index 674d3461..963b0cc9 100644 --- a/src/Parse/ParseConfig.php +++ b/src/Parse/ParseConfig.php @@ -3,39 +3,43 @@ namespace Parse; /** - * ParseConfig - For accessing Parse Config settings + * ParseConfig - For accessing Parse Config settings. * - * @package Parse * @author Fosco Marotto */ -class ParseConfig { - +class ParseConfig +{ private $currentConfig; /** - * Creates + * Creates. */ - public function __construct() { - $result = ParseClient::_request("GET", "/1/config"); - $this->setConfig($result['params']); + public function __construct() + { + $result = ParseClient::_request("GET", "/1/config"); + $this->setConfig($result['params']); } - public function get($key) { - if (isset($this->currentConfig[$key])) { - return $this->currentConfig[$key]; - } - return null; - } + public function get($key) + { + if (isset($this->currentConfig[$key])) { + return $this->currentConfig[$key]; + } - public function escape($key) { - if (isset($this->currentConfig[$key])) { - return htmlentities($this->currentConfig[$key]); + return; } - return null; - } - protected function setConfig($config) { - $this->currentConfig = $config; - } + public function escape($key) + { + if (isset($this->currentConfig[$key])) { + return htmlentities($this->currentConfig[$key]); + } + + return; + } -} \ No newline at end of file + protected function setConfig($config) + { + $this->currentConfig = $config; + } +} diff --git a/src/Parse/ParseException.php b/src/Parse/ParseException.php index b10499a6..acca6526 100644 --- a/src/Parse/ParseException.php +++ b/src/Parse/ParseException.php @@ -3,16 +3,14 @@ namespace Parse; /** - * ParseException - Wrapper for \Exception class + * ParseException - Wrapper for \Exception class. * - * @package Parse * @author Fosco Marotto */ class ParseException extends \Exception { - /** - * Constructs a Parse\Exception + * Constructs a Parse\Exception. * * @param string $message Message for the Exception. * @param int $code Error code. @@ -21,7 +19,6 @@ class ParseException extends \Exception public function __construct($message, $code = 0, \Exception $previous = null) { - parent::__construct($message, $code, $previous); + parent::__construct($message, $code, $previous); } - -} \ No newline at end of file +} diff --git a/src/Parse/ParseFile.php b/src/Parse/ParseFile.php index a03c441f..9cf90920 100755 --- a/src/Parse/ParseFile.php +++ b/src/Parse/ParseFile.php @@ -5,12 +5,10 @@ /** * ParseFile - Representation of a Parse File object. * - * @package Parse * @author Fosco Marotto */ class ParseFile implements \Parse\Internal\Encodable { - /** * @var - Filename */ @@ -31,20 +29,21 @@ class ParseFile implements \Parse\Internal\Encodable /** * Return the data for the file, downloading it if not already present. * - * @return mixed - * * @throws ParseException + * + * @return mixed */ public function getData() { - if ($this->data) { + if ($this->data) { + return $this->data; + } + if (!$this->url) { + throw new ParseException("Cannot retrieve data for unsaved ParseFile."); + } + $this->data = $this->download(); + return $this->data; - } - if (!$this->url) { - throw new ParseException("Cannot retrieve data for unsaved ParseFile."); - } - $this->data = $this->download(); - return $this->data; } /** @@ -54,7 +53,7 @@ public function getData() */ public function getURL() { - return $this->url; + return $this->url; } /** @@ -65,33 +64,33 @@ public function getURL() */ public function getName() { - return $this->name; + return $this->name; } /** - * Send a REST request to delete the ParseFile + * Send a REST request to delete the ParseFile. * * @throws ParseException */ public function delete() { - if (!$this->url) { - throw new ParseException("Cannot delete file that has not been saved."); - } + if (!$this->url) { + throw new ParseException("Cannot delete file that has not been saved."); + } - $headers = ParseClient::_getRequestHeaders(null, true); - $url = ParseClient::HOST_NAME . '/1/files/' . $this->getName(); - $rest = curl_init(); - curl_setopt($rest, CURLOPT_URL, $url); - curl_setopt($rest, CURLOPT_CUSTOMREQUEST, "DELETE"); - curl_setopt($rest, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($rest, CURLOPT_HTTPHEADER, $headers); - $response = curl_exec($rest); - $contentType = curl_getinfo($rest, CURLINFO_CONTENT_TYPE); - if (curl_errno($rest)) { - throw new ParseException(curl_error($rest), curl_errno($rest)); - } - curl_close($rest); + $headers = ParseClient::_getRequestHeaders(null, true); + $url = ParseClient::HOST_NAME.'/1/files/'.$this->getName(); + $rest = curl_init(); + curl_setopt($rest, CURLOPT_URL, $url); + curl_setopt($rest, CURLOPT_CUSTOMREQUEST, "DELETE"); + curl_setopt($rest, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($rest, CURLOPT_HTTPHEADER, $headers); + $response = curl_exec($rest); + $contentType = curl_getinfo($rest, CURLINFO_CONTENT_TYPE); + if (curl_errno($rest)) { + throw new ParseException(curl_error($rest), curl_errno($rest)); + } + curl_close($rest); } /** @@ -101,12 +100,12 @@ public function delete() */ public function getMimeType() { - return $this->mimeType; + return $this->mimeType; } /** * Create a Parse File from data - * i.e. $file = ParseFile::createFromData("hello world!", "hi.txt"); + * i.e. $file = ParseFile::createFromData("hello world!", "hi.txt");. * * @param mixed $contents The file contents * @param string $name The file name on Parse, can be used to detect mimeType @@ -116,17 +115,18 @@ public function getMimeType() */ public static function createFromData($contents, $name, $mimeType = null) { - $file = new ParseFile(); - $file->name = $name; - $file->mimeType = $mimeType; - $file->data = $contents; - return $file; + $file = new ParseFile(); + $file->name = $name; + $file->mimeType = $mimeType; + $file->data = $contents; + + return $file; } /** * Create a Parse File from the contents of a local file * i.e. $file = ParseFile::createFromFile("/tmp/foo.bar", - * "foo.bar"); + * "foo.bar");. * * @param string $path Path to local file * @param string $name Filename to use on Parse, can be used to detect mimeType @@ -136,8 +136,9 @@ public static function createFromData($contents, $name, $mimeType = null) */ public static function createFromFile($path, $name, $mimeType = null) { - $contents = file_get_contents($path, "rb"); - return static::createFromData($contents, $name, $mimeType); + $contents = file_get_contents($path, "rb"); + + return static::createFromData($contents, $name, $mimeType); } /** @@ -151,10 +152,11 @@ public static function createFromFile($path, $name, $mimeType = null) */ public static function _createFromServer($name, $url) { - $file = new ParseFile(); - $file->name = $name; - $file->url = $url; - return $file; + $file = new ParseFile(); + $file->name = $name; + $file->url = $url; + + return $file; } /** @@ -165,11 +167,11 @@ public static function _createFromServer($name, $url) */ public function _encode() { - return array( + return [ '__type' => 'File', - 'url' => $this->url, - 'name' => $this->name - ); + 'url' => $this->url, + 'name' => $this->name, + ]; } /** @@ -179,267 +181,269 @@ public function _encode() */ public function save() { - if (!$this->url) { - $response = $this->upload(); - $this->url = $response['url']; - $this->name = $response['name']; - } - return true; + if (!$this->url) { + $response = $this->upload(); + $this->url = $response['url']; + $this->name = $response['name']; + } + + return true; } - private function upload() - { - $fileParts = explode('.', $this->getName()); - $extension = array_pop($fileParts); - $mimeType = $this->mimeType ?: $this->getMimeTypeForExtension($extension); + private function upload() + { + $fileParts = explode('.', $this->getName()); + $extension = array_pop($fileParts); + $mimeType = $this->mimeType ?: $this->getMimeTypeForExtension($extension); - $headers = ParseClient::_getRequestHeaders(null, false); - $url = ParseClient::HOST_NAME . '/1/files/' . $this->getName(); - $rest = curl_init(); - curl_setopt($rest, CURLOPT_URL, $url); - curl_setopt($rest, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($rest, CURLOPT_BINARYTRANSFER, 1); - $headers[] = 'Content-Type: ' . $mimeType; - curl_setopt($rest, CURLOPT_POST, 1); - curl_setopt($rest, CURLOPT_POSTFIELDS, $this->getData()); - curl_setopt($rest, CURLOPT_HTTPHEADER, $headers); - $response = curl_exec($rest); - $contentType = curl_getinfo($rest, CURLINFO_CONTENT_TYPE); - if (curl_errno($rest)) { - throw new ParseException(curl_error($rest), curl_errno($rest)); - } - curl_close($rest); - if (strpos($contentType, 'text/html') !== false) { - throw new ParseException('Bad Request', -1); - } + $headers = ParseClient::_getRequestHeaders(null, false); + $url = ParseClient::HOST_NAME.'/1/files/'.$this->getName(); + $rest = curl_init(); + curl_setopt($rest, CURLOPT_URL, $url); + curl_setopt($rest, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($rest, CURLOPT_BINARYTRANSFER, 1); + $headers[] = 'Content-Type: '.$mimeType; + curl_setopt($rest, CURLOPT_POST, 1); + curl_setopt($rest, CURLOPT_POSTFIELDS, $this->getData()); + curl_setopt($rest, CURLOPT_HTTPHEADER, $headers); + $response = curl_exec($rest); + $contentType = curl_getinfo($rest, CURLINFO_CONTENT_TYPE); + if (curl_errno($rest)) { + throw new ParseException(curl_error($rest), curl_errno($rest)); + } + curl_close($rest); + if (strpos($contentType, 'text/html') !== false) { + throw new ParseException('Bad Request', -1); + } - $decoded = json_decode($response, true); - if (isset($decoded['error'])) { - throw new ParseException($decoded['error'], + $decoded = json_decode($response, true); + if (isset($decoded['error'])) { + throw new ParseException($decoded['error'], isset($decoded['code']) ? $decoded['code'] : 0 ); + } + + return $decoded; } - return $decoded; - } + private function download() + { + $rest = curl_init(); + curl_setopt($rest, CURLOPT_URL, $this->url); + curl_setopt($rest, CURLOPT_RETURNTRANSFER, 1); + curl_setopt($rest, CURLOPT_BINARYTRANSFER, 1); + $response = curl_exec($rest); + if (curl_errno($rest)) { + throw new ParseException(curl_error($rest), curl_errno($rest)); + } + $httpStatus = curl_getinfo($rest, CURLINFO_HTTP_CODE); + if ($httpStatus > 399) { + throw new ParseException("Download failed, file may have been deleted.", $httpStatus); + } + $this->mimeType = curl_getinfo($rest, CURLINFO_CONTENT_TYPE); + $this->data = $response; + curl_close($rest); - private function download() - { - $rest = curl_init(); - curl_setopt($rest, CURLOPT_URL, $this->url); - curl_setopt($rest, CURLOPT_RETURNTRANSFER, 1); - curl_setopt($rest, CURLOPT_BINARYTRANSFER, 1); - $response = curl_exec($rest); - if (curl_errno($rest)) { - throw new ParseException(curl_error($rest), curl_errno($rest)); + return $response; } - $httpStatus = curl_getinfo($rest, CURLINFO_HTTP_CODE); - if ($httpStatus > 399) { - throw new ParseException("Download failed, file may have been deleted.", $httpStatus); - } - $this->mimeType = curl_getinfo($rest, CURLINFO_CONTENT_TYPE); - $this->data = $response; - curl_close($rest); - return $response; - } - private function getMimeTypeForExtension($extension) - { - $knownTypes = array( - "ai" => "application/postscript", - "aif" => "audio/x-aiff", - "aifc" => "audio/x-aiff", - "aiff" => "audio/x-aiff", - "asc" => "text/plain", - "atom" => "application/atom+xml", - "au" => "audio/basic", - "avi" => "video/x-msvideo", - "bcpio" => "application/x-bcpio", - "bin" => "application/octet-stream", - "bmp" => "image/bmp", - "cdf" => "application/x-netcdf", - "cgm" => "image/cgm", - "class" => "application/octet-stream", - "cpio" => "application/x-cpio", - "cpt" => "application/mac-compactpro", - "csh" => "application/x-csh", - "css" => "text/css", - "dcr" => "application/x-director", - "dif" => "video/x-dv", - "dir" => "application/x-director", - "djv" => "image/vnd.djvu", - "djvu" => "image/vnd.djvu", - "dll" => "application/octet-stream", - "dmg" => "application/octet-stream", - "dms" => "application/octet-stream", - "doc" => "application/msword", - "docx" =>"application/vnd.openxmlformats-officedocument.wordprocessingml.document", - "dotx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.template", - "docm" =>"application/vnd.ms-word.document.macroEnabled.12", - "dotm" =>"application/vnd.ms-word.template.macroEnabled.12", - "dtd" => "application/xml-dtd", - "dv" => "video/x-dv", - "dvi" => "application/x-dvi", - "dxr" => "application/x-director", - "eps" => "application/postscript", - "etx" => "text/x-setext", - "exe" => "application/octet-stream", - "ez" => "application/andrew-inset", - "gif" => "image/gif", - "gram" => "application/srgs", - "grxml" => "application/srgs+xml", - "gtar" => "application/x-gtar", - "hdf" => "application/x-hdf", - "hqx" => "application/mac-binhex40", - "htm" => "text/html", - "html" => "text/html", - "ice" => "x-conference/x-cooltalk", - "ico" => "image/x-icon", - "ics" => "text/calendar", - "ief" => "image/ief", - "ifb" => "text/calendar", - "iges" => "model/iges", - "igs" => "model/iges", - "jnlp" => "application/x-java-jnlp-file", - "jp2" => "image/jp2", - "jpe" => "image/jpeg", - "jpeg" => "image/jpeg", - "jpg" => "image/jpeg", - "js" => "application/x-javascript", - "kar" => "audio/midi", - "latex" => "application/x-latex", - "lha" => "application/octet-stream", - "lzh" => "application/octet-stream", - "m3u" => "audio/x-mpegurl", - "m4a" => "audio/mp4a-latm", - "m4b" => "audio/mp4a-latm", - "m4p" => "audio/mp4a-latm", - "m4u" => "video/vnd.mpegurl", - "m4v" => "video/x-m4v", - "mac" => "image/x-macpaint", - "man" => "application/x-troff-man", - "mathml" => "application/mathml+xml", - "me" => "application/x-troff-me", - "mesh" => "model/mesh", - "mid" => "audio/midi", - "midi" => "audio/midi", - "mif" => "application/vnd.mif", - "mov" => "video/quicktime", - "movie" => "video/x-sgi-movie", - "mp2" => "audio/mpeg", - "mp3" => "audio/mpeg", - "mp4" => "video/mp4", - "mpe" => "video/mpeg", - "mpeg" => "video/mpeg", - "mpg" => "video/mpeg", - "mpga" => "audio/mpeg", - "ms" => "application/x-troff-ms", - "msh" => "model/mesh", - "mxu" => "video/vnd.mpegurl", - "nc" => "application/x-netcdf", - "oda" => "application/oda", - "ogg" => "application/ogg", - "pbm" => "image/x-portable-bitmap", - "pct" => "image/pict", - "pdb" => "chemical/x-pdb", - "pdf" => "application/pdf", - "pgm" => "image/x-portable-graymap", - "pgn" => "application/x-chess-pgn", - "pic" => "image/pict", - "pict" => "image/pict", - "png" => "image/png", - "pnm" => "image/x-portable-anymap", - "pnt" => "image/x-macpaint", - "pntg" => "image/x-macpaint", - "ppm" => "image/x-portable-pixmap", - "ppt" => "application/vnd.ms-powerpoint", - "pptx" =>"application/vnd.openxmlformats-officedocument.presentationml.presentation", - "potx" =>"application/vnd.openxmlformats-officedocument.presentationml.template", - "ppsx" =>"application/vnd.openxmlformats-officedocument.presentationml.slideshow", - "ppam" =>"application/vnd.ms-powerpoint.addin.macroEnabled.12", - "pptm" =>"application/vnd.ms-powerpoint.presentation.macroEnabled.12", - "potm" =>"application/vnd.ms-powerpoint.template.macroEnabled.12", - "ppsm" =>"application/vnd.ms-powerpoint.slideshow.macroEnabled.12", - "ps" => "application/postscript", - "qt" => "video/quicktime", - "qti" => "image/x-quicktime", - "qtif" => "image/x-quicktime", - "ra" => "audio/x-pn-realaudio", - "ram" => "audio/x-pn-realaudio", - "ras" => "image/x-cmu-raster", - "rdf" => "application/rdf+xml", - "rgb" => "image/x-rgb", - "rm" => "application/vnd.rn-realmedia", - "roff" => "application/x-troff", - "rtf" => "text/rtf", - "rtx" => "text/richtext", - "sgm" => "text/sgml", - "sgml" => "text/sgml", - "sh" => "application/x-sh", - "shar" => "application/x-shar", - "silo" => "model/mesh", - "sit" => "application/x-stuffit", - "skd" => "application/x-koan", - "skm" => "application/x-koan", - "skp" => "application/x-koan", - "skt" => "application/x-koan", - "smi" => "application/smil", - "smil" => "application/smil", - "snd" => "audio/basic", - "so" => "application/octet-stream", - "spl" => "application/x-futuresplash", - "src" => "application/x-wais-source", + private function getMimeTypeForExtension($extension) + { + $knownTypes = [ + "ai" => "application/postscript", + "aif" => "audio/x-aiff", + "aifc" => "audio/x-aiff", + "aiff" => "audio/x-aiff", + "asc" => "text/plain", + "atom" => "application/atom+xml", + "au" => "audio/basic", + "avi" => "video/x-msvideo", + "bcpio" => "application/x-bcpio", + "bin" => "application/octet-stream", + "bmp" => "image/bmp", + "cdf" => "application/x-netcdf", + "cgm" => "image/cgm", + "class" => "application/octet-stream", + "cpio" => "application/x-cpio", + "cpt" => "application/mac-compactpro", + "csh" => "application/x-csh", + "css" => "text/css", + "dcr" => "application/x-director", + "dif" => "video/x-dv", + "dir" => "application/x-director", + "djv" => "image/vnd.djvu", + "djvu" => "image/vnd.djvu", + "dll" => "application/octet-stream", + "dmg" => "application/octet-stream", + "dms" => "application/octet-stream", + "doc" => "application/msword", + "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "dotx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.template", + "docm" => "application/vnd.ms-word.document.macroEnabled.12", + "dotm" => "application/vnd.ms-word.template.macroEnabled.12", + "dtd" => "application/xml-dtd", + "dv" => "video/x-dv", + "dvi" => "application/x-dvi", + "dxr" => "application/x-director", + "eps" => "application/postscript", + "etx" => "text/x-setext", + "exe" => "application/octet-stream", + "ez" => "application/andrew-inset", + "gif" => "image/gif", + "gram" => "application/srgs", + "grxml" => "application/srgs+xml", + "gtar" => "application/x-gtar", + "hdf" => "application/x-hdf", + "hqx" => "application/mac-binhex40", + "htm" => "text/html", + "html" => "text/html", + "ice" => "x-conference/x-cooltalk", + "ico" => "image/x-icon", + "ics" => "text/calendar", + "ief" => "image/ief", + "ifb" => "text/calendar", + "iges" => "model/iges", + "igs" => "model/iges", + "jnlp" => "application/x-java-jnlp-file", + "jp2" => "image/jp2", + "jpe" => "image/jpeg", + "jpeg" => "image/jpeg", + "jpg" => "image/jpeg", + "js" => "application/x-javascript", + "kar" => "audio/midi", + "latex" => "application/x-latex", + "lha" => "application/octet-stream", + "lzh" => "application/octet-stream", + "m3u" => "audio/x-mpegurl", + "m4a" => "audio/mp4a-latm", + "m4b" => "audio/mp4a-latm", + "m4p" => "audio/mp4a-latm", + "m4u" => "video/vnd.mpegurl", + "m4v" => "video/x-m4v", + "mac" => "image/x-macpaint", + "man" => "application/x-troff-man", + "mathml" => "application/mathml+xml", + "me" => "application/x-troff-me", + "mesh" => "model/mesh", + "mid" => "audio/midi", + "midi" => "audio/midi", + "mif" => "application/vnd.mif", + "mov" => "video/quicktime", + "movie" => "video/x-sgi-movie", + "mp2" => "audio/mpeg", + "mp3" => "audio/mpeg", + "mp4" => "video/mp4", + "mpe" => "video/mpeg", + "mpeg" => "video/mpeg", + "mpg" => "video/mpeg", + "mpga" => "audio/mpeg", + "ms" => "application/x-troff-ms", + "msh" => "model/mesh", + "mxu" => "video/vnd.mpegurl", + "nc" => "application/x-netcdf", + "oda" => "application/oda", + "ogg" => "application/ogg", + "pbm" => "image/x-portable-bitmap", + "pct" => "image/pict", + "pdb" => "chemical/x-pdb", + "pdf" => "application/pdf", + "pgm" => "image/x-portable-graymap", + "pgn" => "application/x-chess-pgn", + "pic" => "image/pict", + "pict" => "image/pict", + "png" => "image/png", + "pnm" => "image/x-portable-anymap", + "pnt" => "image/x-macpaint", + "pntg" => "image/x-macpaint", + "ppm" => "image/x-portable-pixmap", + "ppt" => "application/vnd.ms-powerpoint", + "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation", + "potx" => "application/vnd.openxmlformats-officedocument.presentationml.template", + "ppsx" => "application/vnd.openxmlformats-officedocument.presentationml.slideshow", + "ppam" => "application/vnd.ms-powerpoint.addin.macroEnabled.12", + "pptm" => "application/vnd.ms-powerpoint.presentation.macroEnabled.12", + "potm" => "application/vnd.ms-powerpoint.template.macroEnabled.12", + "ppsm" => "application/vnd.ms-powerpoint.slideshow.macroEnabled.12", + "ps" => "application/postscript", + "qt" => "video/quicktime", + "qti" => "image/x-quicktime", + "qtif" => "image/x-quicktime", + "ra" => "audio/x-pn-realaudio", + "ram" => "audio/x-pn-realaudio", + "ras" => "image/x-cmu-raster", + "rdf" => "application/rdf+xml", + "rgb" => "image/x-rgb", + "rm" => "application/vnd.rn-realmedia", + "roff" => "application/x-troff", + "rtf" => "text/rtf", + "rtx" => "text/richtext", + "sgm" => "text/sgml", + "sgml" => "text/sgml", + "sh" => "application/x-sh", + "shar" => "application/x-shar", + "silo" => "model/mesh", + "sit" => "application/x-stuffit", + "skd" => "application/x-koan", + "skm" => "application/x-koan", + "skp" => "application/x-koan", + "skt" => "application/x-koan", + "smi" => "application/smil", + "smil" => "application/smil", + "snd" => "audio/basic", + "so" => "application/octet-stream", + "spl" => "application/x-futuresplash", + "src" => "application/x-wais-source", "sv4cpio" => "application/x-sv4cpio", - "sv4crc" => "application/x-sv4crc", - "svg" => "image/svg+xml", - "swf" => "application/x-shockwave-flash", - "t" => "application/x-troff", - "tar" => "application/x-tar", - "tcl" => "application/x-tcl", - "tex" => "application/x-tex", - "texi" => "application/x-texinfo", + "sv4crc" => "application/x-sv4crc", + "svg" => "image/svg+xml", + "swf" => "application/x-shockwave-flash", + "t" => "application/x-troff", + "tar" => "application/x-tar", + "tcl" => "application/x-tcl", + "tex" => "application/x-tex", + "texi" => "application/x-texinfo", "texinfo" => "application/x-texinfo", - "tif" => "image/tiff", - "tiff" => "image/tiff", - "tr" => "application/x-troff", - "tsv" => "text/tab-separated-values", - "txt" => "text/plain", - "ustar" => "application/x-ustar", - "vcd" => "application/x-cdlink", - "vrml" => "model/vrml", - "vxml" => "application/voicexml+xml", - "wav" => "audio/x-wav", - "wbmp" => "image/vnd.wap.wbmp", - "wbmxl" => "application/vnd.wap.wbxml", - "wml" => "text/vnd.wap.wml", - "wmlc" => "application/vnd.wap.wmlc", - "wmls" => "text/vnd.wap.wmlscript", - "wmlsc" => "application/vnd.wap.wmlscriptc", - "wrl" => "model/vrml", - "xbm" => "image/x-xbitmap", - "xht" => "application/xhtml+xml", - "xhtml" => "application/xhtml+xml", - "xls" => "application/vnd.ms-excel", - "xml" => "application/xml", - "xpm" => "image/x-xpixmap", - "xsl" => "application/xml", - "xlsx" =>"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", - "xltx" =>"application/vnd.openxmlformats-officedocument.spreadsheetml.template", - "xlsm" =>"application/vnd.ms-excel.sheet.macroEnabled.12", - "xltm" =>"application/vnd.ms-excel.template.macroEnabled.12", - "xlam" =>"application/vnd.ms-excel.addin.macroEnabled.12", - "xlsb" =>"application/vnd.ms-excel.sheet.binary.macroEnabled.12", - "xslt" => "application/xslt+xml", - "xul" => "application/vnd.mozilla.xul+xml", - "xwd" => "image/x-xwindowdump", - "xyz" => "chemical/x-xyz", - "zip" => "application/zip" - ); + "tif" => "image/tiff", + "tiff" => "image/tiff", + "tr" => "application/x-troff", + "tsv" => "text/tab-separated-values", + "txt" => "text/plain", + "ustar" => "application/x-ustar", + "vcd" => "application/x-cdlink", + "vrml" => "model/vrml", + "vxml" => "application/voicexml+xml", + "wav" => "audio/x-wav", + "wbmp" => "image/vnd.wap.wbmp", + "wbmxl" => "application/vnd.wap.wbxml", + "wml" => "text/vnd.wap.wml", + "wmlc" => "application/vnd.wap.wmlc", + "wmls" => "text/vnd.wap.wmlscript", + "wmlsc" => "application/vnd.wap.wmlscriptc", + "wrl" => "model/vrml", + "xbm" => "image/x-xbitmap", + "xht" => "application/xhtml+xml", + "xhtml" => "application/xhtml+xml", + "xls" => "application/vnd.ms-excel", + "xml" => "application/xml", + "xpm" => "image/x-xpixmap", + "xsl" => "application/xml", + "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "xltx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.template", + "xlsm" => "application/vnd.ms-excel.sheet.macroEnabled.12", + "xltm" => "application/vnd.ms-excel.template.macroEnabled.12", + "xlam" => "application/vnd.ms-excel.addin.macroEnabled.12", + "xlsb" => "application/vnd.ms-excel.sheet.binary.macroEnabled.12", + "xslt" => "application/xslt+xml", + "xul" => "application/vnd.mozilla.xul+xml", + "xwd" => "image/x-xwindowdump", + "xyz" => "chemical/x-xyz", + "zip" => "application/zip", + ]; - if (isset($knownTypes[$extension])) { - return $knownTypes[$extension]; - } - return 'unknown/unknown'; - } + if (isset($knownTypes[$extension])) { + return $knownTypes[$extension]; + } + return 'unknown/unknown'; + } } diff --git a/src/Parse/ParseGeoPoint.php b/src/Parse/ParseGeoPoint.php index 11bef9f8..300a07e7 100755 --- a/src/Parse/ParseGeoPoint.php +++ b/src/Parse/ParseGeoPoint.php @@ -5,12 +5,10 @@ /** * ParseGeoPoint - Representation of a Parse GeoPoint object. * - * @package Parse * @author Fosco Marotto */ class ParseGeoPoint implements \Parse\Internal\Encodable { - /** * @var - Float value for latitude. */ @@ -28,8 +26,8 @@ class ParseGeoPoint implements \Parse\Internal\Encodable */ public function __construct($lat, $lon) { - $this->setLatitude($lat); - $this->setLongitude($lon); + $this->setLatitude($lat); + $this->setLongitude($lon); } /** @@ -39,7 +37,7 @@ public function __construct($lat, $lon) */ public function getLatitude() { - return $this->latitude; + return $this->latitude; } /** @@ -51,10 +49,10 @@ public function getLatitude() */ public function setLatitude($lat) { - if ($lat > 90.0 || $lat < -90.0) { - throw new ParseException("Latitude must be within range [-90.0, 90.0]"); - } - $this->latitude = $lat; + if ($lat > 90.0 || $lat < -90.0) { + throw new ParseException("Latitude must be within range [-90.0, 90.0]"); + } + $this->latitude = $lat; } /** @@ -64,7 +62,7 @@ public function setLatitude($lat) */ public function getLongitude() { - return $this->longitude; + return $this->longitude; } /** @@ -76,26 +74,26 @@ public function getLongitude() */ public function setLongitude($lon) { - if ($lon > 180.0 || $lon < -180.0) { - throw new ParseException( + if ($lon > 180.0 || $lon < -180.0) { + throw new ParseException( "Longitude must be within range [-180.0, 180.0]" ); - } - $this->longitude = $lon; + } + $this->longitude = $lon; } /** - * Encode to associative array representation + * Encode to associative array representation. * * @return array * @ignore */ public function _encode() { - return array( - '__type' => 'GeoPoint', - 'latitude' => $this->latitude, - 'longitude' => $this->longitude - ); + return [ + '__type' => 'GeoPoint', + 'latitude' => $this->latitude, + 'longitude' => $this->longitude, + ]; } } diff --git a/src/Parse/ParseInstallation.php b/src/Parse/ParseInstallation.php index 10c61cd0..0ba5a0d6 100644 --- a/src/Parse/ParseInstallation.php +++ b/src/Parse/ParseInstallation.php @@ -2,17 +2,12 @@ namespace Parse; -use Parse\ParseObject; - /** * ParseInstallation - Representation of an Installation stored on Parse. * - * @package Parse * @author Fosco Marotto */ class ParseInstallation extends ParseObject { - public static $parseClassName = "_Installation"; - -} \ No newline at end of file +} diff --git a/src/Parse/ParseMemoryStorage.php b/src/Parse/ParseMemoryStorage.php index 57b449fe..4c4983d6 100644 --- a/src/Parse/ParseMemoryStorage.php +++ b/src/Parse/ParseMemoryStorage.php @@ -6,54 +6,52 @@ * ParseMemoryStorage - Uses non-persisted memory for storage. * This is used by default if a PHP Session is not active. * - * @package Parse * @author Fosco Marotto */ class ParseMemoryStorage implements ParseStorageInterface { - /** * @var array */ - private $storage = array(); - - public function set($key, $value) - { - $this->storage[$key] = $value; - } - - public function remove($key) - { - unset($this->storage[$key]); - } - - public function get($key) - { - if (isset($this->storage[$key])) { - return $this->storage[$key]; + private $storage = []; + + public function set($key, $value) + { + $this->storage[$key] = $value; + } + + public function remove($key) + { + unset($this->storage[$key]); } - return null; - } - public function clear() - { - $this->storage = array(); - } + public function get($key) + { + if (isset($this->storage[$key])) { + return $this->storage[$key]; + } - public function save() - { - // No action required. - return; - } + return; + } - public function getKeys() - { - return array_keys($this->storage); - } + public function clear() + { + $this->storage = []; + } + + public function save() + { + // No action required. + return; + } - public function getAll() - { - return $this->storage; - } + public function getKeys() + { + return array_keys($this->storage); + } -} \ No newline at end of file + public function getAll() + { + return $this->storage; + } +} diff --git a/src/Parse/ParseObject.php b/src/Parse/ParseObject.php index d701eeb9..2eca2467 100755 --- a/src/Parse/ParseObject.php +++ b/src/Parse/ParseObject.php @@ -2,26 +2,23 @@ namespace Parse; -use Parse\Internal\Encodable; -use Parse\Internal\RemoveOperation; -use Parse\Internal\FieldOperation; -use Parse\Internal\SetOperation; +use Exception; use Parse\Internal\AddOperation; use Parse\Internal\AddUniqueOperation; -use Parse\Internal\IncrementOperation; use Parse\Internal\DeleteOperation; - -use \Exception; +use Parse\Internal\Encodable; +use Parse\Internal\FieldOperation; +use Parse\Internal\IncrementOperation; +use Parse\Internal\RemoveOperation; +use Parse\Internal\SetOperation; /** * ParseObject - Representation of an object stored on Parse. * - * @package Parse * @author Fosco Marotto */ class ParseObject implements Encodable { - /** * @var array - Data as it exists on the server. */ @@ -62,10 +59,10 @@ class ParseObject implements Encodable /** * @var array - Holds the registered subclasses and Parse class names. */ - private static $registeredSubclasses = array(); + private static $registeredSubclasses = []; /** - * Create a Parse Object + * Create a Parse Object. * * Creates a pointer object if an objectId is provided, * otherwise creates a new object. @@ -79,36 +76,36 @@ class ParseObject implements Encodable public function __construct($className = null, $objectId = null, $isPointer = false) { - if (empty(self::$registeredSubclasses)) { - throw new Exception( - 'You must initialize the ParseClient using ParseClient::initialize ' . + if (empty(self::$registeredSubclasses)) { + throw new Exception( + 'You must initialize the ParseClient using ParseClient::initialize '. 'and your Parse API keys before you can begin working with Objects.' ); - } - $subclass = static::getSubclass(); - $class = get_called_class(); - if (!$className && $subclass !== false) { - $className = $subclass; - } - if ($class !== __CLASS__ && $className !== $subclass) { - throw new Exception( - 'You must specify a Parse class name or register the appropriate ' . - 'subclass when creating a new Object. Use ParseObject::create to ' . + } + $subclass = static::getSubclass(); + $class = get_called_class(); + if (!$className && $subclass !== false) { + $className = $subclass; + } + if ($class !== __CLASS__ && $className !== $subclass) { + throw new Exception( + 'You must specify a Parse class name or register the appropriate '. + 'subclass when creating a new Object. Use ParseObject::create to '. 'create a subclass object.' ); - } + } - $this->className = $className; - $this->serverData = array(); - $this->operationSet = array(); - $this->estimatedData = array(); - $this->dataAvailability = array(); - if ($objectId || $isPointer) { - $this->objectId = $objectId; - $this->hasBeenFetched = false; - } else { - $this->hasBeenFetched = true; - } + $this->className = $className; + $this->serverData = []; + $this->operationSet = []; + $this->estimatedData = []; + $this->dataAvailability = []; + if ($objectId || $isPointer) { + $this->objectId = $objectId; + $this->hasBeenFetched = false; + } else { + $this->hasBeenFetched = true; + } } /** @@ -116,7 +113,7 @@ public function __construct($className = null, $objectId = null, */ private static function getSubclass() { - return array_search(get_called_class(), self::$registeredSubclasses); + return array_search(get_called_class(), self::$registeredSubclasses); } /** @@ -125,21 +122,22 @@ private static function getSubclass() * @param string $key Key to set a value on. * @param mixed $value Value to assign. * - * @return null * @throws Exception + * + * @return null * @ignore */ public function __set($key, $value) { - if ($key != 'objectId' + if ($key != 'objectId' && $key != 'createdAt' && $key != 'updatedAt' && $key != 'className' ) { - $this->set($key, $value); - } else { - throw new Exception('Protected field could not be set.'); - } + $this->set($key, $value); + } else { + throw new Exception('Protected field could not be set.'); + } } /** @@ -152,7 +150,7 @@ public function __set($key, $value) */ public function __get($key) { - return $this->get($key); + return $this->get($key); } /** @@ -160,24 +158,25 @@ public function __get($key) * * @param string $key Key to retrieve from the estimatedData array. * - * @return mixed - * * @throws \Exception + * + * @return mixed */ public function get($key) { - if (!$this->_isDataAvailable($key)) { - throw new \Exception( + if (!$this->_isDataAvailable($key)) { + throw new \Exception( 'ParseObject has no data for this key. Call fetch() to get the data.'); - } - if (isset($this->estimatedData[$key])) { - return $this->estimatedData[$key]; - } - return null; + } + if (isset($this->estimatedData[$key])) { + return $this->estimatedData[$key]; + } + + return; } /** - * Check if the object has a given key + * Check if the object has a given key. * * @param string $key Key to check * @@ -185,7 +184,7 @@ public function get($key) */ public function has($key) { - return isset($this->estimatedData[$key]); + return isset($this->estimatedData[$key]); } /** @@ -193,11 +192,12 @@ public function has($key) * added/updated/removed and not saved yet. * * @param string $key + * * @return bool */ public function isKeyDirty($key) { - return isset($this->operationSet[$key]); + return isset($this->operationSet[$key]); } /** @@ -207,7 +207,7 @@ public function isKeyDirty($key) */ public function isDirty() { - return $this->_isDirty(true); + return $this->_isDirty(true); } /** @@ -221,23 +221,24 @@ public function isDirty() */ protected function _isDirty($considerChildren) { - return + return (count($this->operationSet) || $this->objectId === null) || ($considerChildren && $this->hasDirtyChildren()); } - private function hasDirtyChildren() - { - $result = false; - self::traverse(true, $this->estimatedData, function ($object) use (&$result) { + private function hasDirtyChildren() + { + $result = false; + self::traverse(true, $this->estimatedData, function ($object) use (&$result) { if ($object instanceof ParseObject) { - if ($object->isDirty()) { - $result = true; - } + if ($object->isDirty()) { + $result = true; + } } }); - return $result; - } + + return $result; + } /** * Validate and set a value for an object key. @@ -245,42 +246,44 @@ private function hasDirtyChildren() * @param string $key Key to set a value for on the object. * @param mixed $value Value to set on the key. * - * @return null * @throws Exception + * + * @return null */ public function set($key, $value) { - if (!$key) { - throw new Exception('key may not be null.'); - } - if (is_array($value)) { - throw new Exception( + if (!$key) { + throw new Exception('key may not be null.'); + } + if (is_array($value)) { + throw new Exception( 'Must use setArray() or setAssociativeArray() for this value.' - ); - } - $this->_performOperation($key, new SetOperation($value)); + ); + } + $this->_performOperation($key, new SetOperation($value)); } /** * Set an array value for an object key. - * + * * @param string $key Key to set the value for on the object. * @param array $value Value to set on the key. - * - * @return null + * * @throws Exception + * + * @return null */ public function setArray($key, $value) { - if (!$key) { - throw new Exception('key may not be null.'); - } - if (!is_array($value)) { - throw new Exception( + if (!$key) { + throw new Exception('key may not be null.'); + } + if (!is_array($value)) { + throw new Exception( 'Must use set() for non-array values.' ); - } - $this->_performOperation($key, new SetOperation($value)); + } + $this->_performOperation($key, new SetOperation($value)); } /** @@ -289,20 +292,21 @@ public function setArray($key, $value) * @param string $key Key to set the value for on the object. * @param array $value Value to set on the key. * - * @return null * @throws Exception + * + * @return null */ public function setAssociativeArray($key, $value) { - if (!$key) { - throw new Exception('key may not be null.'); - } - if (!is_array($value)) { - throw new Exception( + if (!$key) { + throw new Exception('key may not be null.'); + } + if (!is_array($value)) { + throw new Exception( 'Must use set() for non-array values.' ); - } - $this->_performOperation($key, new SetOperation($value, true)); + } + $this->_performOperation($key, new SetOperation($value, true)); } /** @@ -311,18 +315,19 @@ public function setAssociativeArray($key, $value) * @param string $key Key to remove the value from on the object. * @param mixed $value Value to remove from the array. * - * @return null * @throws Exception + * + * @return null */ public function remove($key, $value) { - if (!$key) { - throw new Exception('key may not be null.'); - } - if (!is_array($value)) { - $value = [$value]; - } - $this->_performOperation($key, new RemoveOperation($value)); + if (!$key) { + throw new Exception('key may not be null.'); + } + if (!is_array($value)) { + $value = [$value]; + } + $this->_performOperation($key, new RemoveOperation($value)); } /** @@ -332,8 +337,8 @@ public function remove($key, $value) */ public function revert() { - $this->operationSet = array(); - $this->rebuildEstimatedData(); + $this->operationSet = []; + $this->rebuildEstimatedData(); } /** @@ -344,9 +349,9 @@ public function revert() */ public function clear() { - foreach ($this->estimatedData as $key => $value) { - $this->delete($key); - } + foreach ($this->estimatedData as $key => $value) { + $this->delete($key); + } } /** @@ -360,25 +365,25 @@ public function clear() */ public function _performOperation($key, FieldOperation $operation) { - $oldValue = null; - if (isset($this->estimatedData[$key])) { - $oldValue = $this->estimatedData[$key]; - } - $newValue = $operation->_apply($oldValue, $this, $key); - if ($newValue !== null) { - $this->estimatedData[$key] = $newValue; - } else if (isset($this->estimatedData[$key])) { - unset($this->estimatedData[$key]); - } + $oldValue = null; + if (isset($this->estimatedData[$key])) { + $oldValue = $this->estimatedData[$key]; + } + $newValue = $operation->_apply($oldValue, $this, $key); + if ($newValue !== null) { + $this->estimatedData[$key] = $newValue; + } elseif (isset($this->estimatedData[$key])) { + unset($this->estimatedData[$key]); + } - if (isset($this->operationSet[$key])) { - $oldOperations = $this->operationSet[$key]; - $newOperations = $operation->_mergeWithPrevious($oldOperations); - $this->operationSet[$key] = $newOperations; - } else { - $this->operationSet[$key] = $operation; - } - $this->dataAvailability[$key] = true; + if (isset($this->operationSet[$key])) { + $oldOperations = $this->operationSet[$key]; + $newOperations = $operation->_mergeWithPrevious($oldOperations); + $this->operationSet[$key] = $newOperations; + } else { + $this->operationSet[$key] = $operation; + } + $this->dataAvailability[$key] = true; } /** @@ -388,7 +393,7 @@ public function _performOperation($key, FieldOperation $operation) */ public function getClassName() { - return $this->className; + return $this->className; } /** @@ -398,7 +403,7 @@ public function getClassName() */ public function getObjectId() { - return $this->objectId; + return $this->objectId; } /** @@ -408,7 +413,7 @@ public function getObjectId() */ public function getCreatedAt() { - return $this->createdAt; + return $this->createdAt; } /** @@ -418,14 +423,13 @@ public function getCreatedAt() */ public function isDataAvailable() { - return $this->hasBeenFetched; + return $this->hasBeenFetched; } - private function _isDataAvailable($key) - { - return $this->isDataAvailable() || isset($this->dataAvailability[$key]); - - } + private function _isDataAvailable($key) + { + return $this->isDataAvailable() || isset($this->dataAvailability[$key]); + } /** * Get the updatedAt for the object, or null if unsaved. @@ -434,7 +438,7 @@ private function _isDataAvailable($key) */ public function getUpdatedAt() { - return $this->updatedAt; + return $this->updatedAt; } /** @@ -450,13 +454,13 @@ public function getUpdatedAt() public static function create($className, $objectId = null, $isPointer = false) { - if (isset(self::$registeredSubclasses[$className])) { - return new self::$registeredSubclasses[$className]( + if (isset(self::$registeredSubclasses[$className])) { + return new self::$registeredSubclasses[$className]( $className, $objectId, $isPointer ); - } else { - return new ParseObject($className, $objectId, $isPointer); - } + } else { + return new ParseObject($className, $objectId, $isPointer); + } } /** @@ -468,16 +472,16 @@ public static function create($className, $objectId = null, */ public function fetch($useMasterKey = false) { - $sessionToken = null; - if (ParseUser::getCurrentUser()) { - $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); - } - $response = ParseClient::_request( + $sessionToken = null; + if (ParseUser::getCurrentUser()) { + $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); + } + $response = ParseClient::_request( 'GET', - '/1/classes/' . $this->className . '/' . $this->objectId, + '/1/classes/'.$this->className.'/'.$this->objectId, $sessionToken, null, $useMasterKey ); - $this->_mergeAfterFetch($response); + $this->_mergeAfterFetch($response); } /** @@ -491,17 +495,17 @@ public function fetch($useMasterKey = false) */ public function _mergeAfterFetch($result, $completeData = true) { - // This loop will clear operations for keys provided by the server + // This loop will clear operations for keys provided by the server // It will not clear operations for new keys the server doesn't have. foreach ($result as $key => $value) { - if (isset($this->operationSet[$key])) { - unset($this->operationSet[$key]); - } + if (isset($this->operationSet[$key])) { + unset($this->operationSet[$key]); + } } - $this->serverData = array(); - $this->dataAvailability = array(); - $this->mergeFromServer($result, $completeData); - $this->rebuildEstimatedData(); + $this->serverData = []; + $this->dataAvailability = []; + $this->mergeFromServer($result, $completeData); + $this->rebuildEstimatedData(); } /** @@ -510,15 +514,16 @@ public function _mergeAfterFetch($result, $completeData = true) * @param array $result Data retrieved from the server. * @param array $selectedKeys Keys to be fetched. Null or empty means all * data will be fetched. + * * @return null * @ignore */ public function _mergeAfterFetchWithSelectedKeys($result, $selectedKeys) { - $this->_mergeAfterFetch($result, $selectedKeys ? empty($selectedKeys) : true); - foreach ($selectedKeys as $key) { - $this->dataAvailability[$key] = true; - } + $this->_mergeAfterFetch($result, $selectedKeys ? empty($selectedKeys) : true); + foreach ($selectedKeys as $key) { + $this->dataAvailability[$key] = true; + } } /** @@ -531,33 +536,32 @@ public function _mergeAfterFetchWithSelectedKeys($result, $selectedKeys) */ private function mergeFromServer($data, $completeData = true) { - $this->hasBeenFetched = ($this->hasBeenFetched || $completeData) ? true : false; - $this->_mergeMagicFields($data); - foreach ($data as $key => $value) { - if ($key === '__type' && $value === 'className') { - continue; - } - - $decodedValue = ParseClient::_decode($value); + $this->hasBeenFetched = ($this->hasBeenFetched || $completeData) ? true : false; + $this->_mergeMagicFields($data); + foreach ($data as $key => $value) { + if ($key === '__type' && $value === 'className') { + continue; + } - if (is_array($decodedValue)) { - if (isset($decodedValue['__type'])) { - if ($decodedValue['__type'] === 'Relation') { - $className = $decodedValue['className']; - $decodedValue = new ParseRelation($this, $key, $className); + $decodedValue = ParseClient::_decode($value); + + if (is_array($decodedValue)) { + if (isset($decodedValue['__type'])) { + if ($decodedValue['__type'] === 'Relation') { + $className = $decodedValue['className']; + $decodedValue = new ParseRelation($this, $key, $className); + } + } + if ($key == 'ACL') { + $decodedValue = ParseACL::_createACLFromJSON($decodedValue); + } } - } - if ($key == 'ACL') { - $decodedValue = ParseACL::_createACLFromJSON($decodedValue); - } + $this->serverData[$key] = $decodedValue; + $this->dataAvailability[$key] = true; + } + if (!$this->updatedAt && $this->createdAt) { + $this->updatedAt = $this->createdAt; } - $this->serverData[$key] = $decodedValue; - $this->dataAvailability[$key] = true; - - } - if (!$this->updatedAt && $this->createdAt) { - $this->updatedAt = $this->createdAt; - } } /** @@ -569,24 +573,23 @@ private function mergeFromServer($data, $completeData = true) */ public function _mergeMagicFields(&$data) { - if (isset($data['objectId'])) { - $this->objectId = $data['objectId']; - unset($data['objectId']); - } - if (isset($data['createdAt'])) { - $this->createdAt = new \DateTime($data['createdAt']); - unset($data['createdAt']); - } - if (isset($data['updatedAt'])) { - $this->updatedAt = new \DateTime($data['updatedAt']); - unset($data['updatedAt']); - } - if (isset($data['ACL'])) { - $acl = ParseACL::_createACLFromJSON($data['ACL']); - $this->serverData['ACL'] = $acl; - unset($data['ACL']); - } - + if (isset($data['objectId'])) { + $this->objectId = $data['objectId']; + unset($data['objectId']); + } + if (isset($data['createdAt'])) { + $this->createdAt = new \DateTime($data['createdAt']); + unset($data['createdAt']); + } + if (isset($data['updatedAt'])) { + $this->updatedAt = new \DateTime($data['updatedAt']); + unset($data['updatedAt']); + } + if (isset($data['ACL'])) { + $acl = ParseACL::_createACLFromJSON($data['ACL']); + $this->serverData['ACL'] = $acl; + unset($data['ACL']); + } } /** @@ -597,15 +600,15 @@ public function _mergeMagicFields(&$data) */ protected function rebuildEstimatedData() { - $this->estimatedData = array(); - foreach ($this->serverData as $key => $value) { - $this->estimatedData[$key] = $value; - } - $this->applyOperations($this->operationSet, $this->estimatedData); + $this->estimatedData = []; + foreach ($this->serverData as $key => $value) { + $this->estimatedData[$key] = $value; + } + $this->applyOperations($this->operationSet, $this->estimatedData); } /** - * Apply operations to a target object + * Apply operations to a target object. * * @param array $operations Operations set to apply. * @param array &$target Target data to affect. @@ -614,19 +617,19 @@ protected function rebuildEstimatedData() */ private function applyOperations($operations, &$target) { - foreach ($operations as $key => $operation) { - $oldValue = (isset($target[$key]) ? $target[$key] : null); - $newValue = $operation->_apply($oldValue, $this, $key); - if (empty($newValue) && !is_array($newValue) + foreach ($operations as $key => $operation) { + $oldValue = (isset($target[$key]) ? $target[$key] : null); + $newValue = $operation->_apply($oldValue, $this, $key); + if (empty($newValue) && !is_array($newValue) && $newValue !== null && !is_scalar($newValue) ) { - unset($target[$key]); - unset($this->dataAvailability[$key]); - } else { - $target[$key] = $newValue; - $this->dataAvailability[$key] = true; + unset($target[$key]); + unset($this->dataAvailability[$key]); + } else { + $target[$key] = $newValue; + $this->dataAvailability[$key] = true; + } } - } } /** @@ -638,16 +641,16 @@ private function applyOperations($operations, &$target) */ public function destroy($useMasterKey = false) { - if (!$this->objectId) { - return; - } - $sessionToken = null; - if (ParseUser::getCurrentUser()) { - $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); - } - ParseClient::_request( - 'DELETE', '/1/classes/' . $this->className . - '/' . $this->objectId, $sessionToken, null, $useMasterKey + if (!$this->objectId) { + return; + } + $sessionToken = null; + if (ParseUser::getCurrentUser()) { + $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); + } + ParseClient::_request( + 'DELETE', '/1/classes/'.$this->className. + '/'.$this->objectId, $sessionToken, null, $useMasterKey ); } @@ -658,69 +661,72 @@ public function destroy($useMasterKey = false) * @param boolean $useMasterKey Whether to use the master key or not. * * @throws ParseAggregateException + * * @return null */ public static function destroyAll(array $objects, $useMasterKey = false) { - $errors = []; - $count = count($objects); - if ($count) { - $batchSize = 40; - $processed = 0; - $currentBatch = []; - $currentcount = 0; - while ($processed < $count) { - $currentcount++; - $currentBatch[] = $objects[$processed++]; - if ($currentcount == $batchSize || $processed == $count) { - $results = static::destroyBatch($currentBatch); - $errors = array_merge($errors, $results); + $errors = []; + $count = count($objects); + if ($count) { + $batchSize = 40; + $processed = 0; $currentBatch = []; $currentcount = 0; - } - } - if (count($errors)) { - throw new ParseAggregateException( + while ($processed < $count) { + $currentcount++; + $currentBatch[] = $objects[$processed++]; + if ($currentcount == $batchSize || $processed == $count) { + $results = static::destroyBatch($currentBatch); + $errors = array_merge($errors, $results); + $currentBatch = []; + $currentcount = 0; + } + } + if (count($errors)) { + throw new ParseAggregateException( "Errors during batch destroy.", $errors ); + } } - } - return null; + + return; } - private static function destroyBatch(array $objects, $useMasterKey = false) - { - $data = []; - $errors = []; - foreach ($objects as $object) { - $data[] = array( + private static function destroyBatch(array $objects, $useMasterKey = false) + { + $data = []; + $errors = []; + foreach ($objects as $object) { + $data[] = [ "method" => "DELETE", - "path" => "/1/classes/" . $object->getClassName() . - "/" . $object->getObjectId() - ); - } - $sessionToken = null; - if (ParseUser::getCurrentUser()) { - $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); - } - $result = ParseClient::_request( + "path" => "/1/classes/".$object->getClassName(). + "/".$object->getObjectId(), + ]; + } + $sessionToken = null; + if (ParseUser::getCurrentUser()) { + $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); + } + $result = ParseClient::_request( "POST", "/1/batch", $sessionToken, - json_encode(array("requests" => $data)), + json_encode(["requests" => $data]), $useMasterKey ); - foreach ($objects as $key => $object) { - if (isset($result[$key]['error'])) { - $error = $result[$key]['error']['error']; - $code = isset($result[$key]['error']['code']) ? + foreach ($objects as $key => $object) { + if (isset($result[$key]['error'])) { + $error = $result[$key]['error']['error']; + $code = isset($result[$key]['error']['code']) ? $result[$key]['error']['code'] : -1; - $errors[] = array( + $errors[] = [ 'error' => $error, - 'code' => $code - ); - } + 'code' => $code, + ]; + } + } + + return $errors; } - return $errors; - } /** * Increment a numeric key by a certain value. @@ -732,7 +738,7 @@ private static function destroyBatch(array $objects, $useMasterKey = false) */ public function increment($key, $value = 1) { - $this->_performOperation($key, new IncrementOperation($value)); + $this->_performOperation($key, new IncrementOperation($value)); } /** @@ -745,7 +751,7 @@ public function increment($key, $value = 1) */ public function add($key, $value) { - $this->_performOperation($key, new AddOperation($value)); + $this->_performOperation($key, new AddOperation($value)); } /** @@ -758,7 +764,7 @@ public function add($key, $value) */ public function addUnique($key, $value) { - $this->_performOperation($key, new AddUniqueOperation($value)); + $this->_performOperation($key, new AddUniqueOperation($value)); } /** @@ -770,7 +776,7 @@ public function addUnique($key, $value) */ public function delete($key) { - $this->_performOperation($key, new DeleteOperation()); + $this->_performOperation($key, new DeleteOperation()); } /** @@ -781,36 +787,37 @@ public function delete($key) */ public function _encode() { - $out = array(); - if ($this->objectId) { - $out['objectId'] = $this->objectId; - } - if ($this->createdAt) { - $out['createdAt'] = $this->createdAt; - } - if ($this->updatedAt) { - $out['updatedAt'] = $this->updatedAt; - } - foreach ($this->serverData as $key => $value) { - $out[$key] = $value; - } - foreach ($this->estimatedData as $key => $value) { - if (is_object($value) && $value instanceof \Parse\Internal\Encodable) { - $out[$key] = $value->_encode(); - } else if (is_array($value)) { - $out[$key] = array(); - foreach ($value as $item) { - if (is_object($item) && $item instanceof \Parse\Internal\Encodable) { - $out[$key][] = $item->_encode(); + $out = []; + if ($this->objectId) { + $out['objectId'] = $this->objectId; + } + if ($this->createdAt) { + $out['createdAt'] = $this->createdAt; + } + if ($this->updatedAt) { + $out['updatedAt'] = $this->updatedAt; + } + foreach ($this->serverData as $key => $value) { + $out[$key] = $value; + } + foreach ($this->estimatedData as $key => $value) { + if (is_object($value) && $value instanceof \Parse\Internal\Encodable) { + $out[$key] = $value->_encode(); + } elseif (is_array($value)) { + $out[$key] = []; + foreach ($value as $item) { + if (is_object($item) && $item instanceof \Parse\Internal\Encodable) { + $out[$key][] = $item->_encode(); + } else { + $out[$key][] = $item; + } + } } else { - $out[$key][] = $item; + $out[$key] = $value; } - } - } else { - $out[$key] = $value; } - } - return json_encode($out); + + return json_encode($out); } /** @@ -820,11 +827,11 @@ public function _encode() */ private function getSaveJSON() { - return ParseClient::_encode($this->operationSet, true); + return ParseClient::_encode($this->operationSet, true); } /** - * Save Object to Parse + * Save Object to Parse. * * @param bool $useMasterKey Whether to use the Master Key. * @@ -832,14 +839,14 @@ private function getSaveJSON() */ public function save($useMasterKey = false) { - if (!$this->isDirty()) { - return; - } - static::deepSave($this, $useMasterKey); + if (!$this->isDirty()) { + return; + } + static::deepSave($this, $useMasterKey); } /** - * Save all the objects in the provided array + * Save all the objects in the provided array. * * @param array $list * @param bool $useMasterKey Whether to use the Master Key. @@ -848,7 +855,7 @@ public function save($useMasterKey = false) */ public static function saveAll($list, $useMasterKey = false) { - static::deepSave($list, $useMasterKey); + static::deepSave($list, $useMasterKey); } /** @@ -857,109 +864,108 @@ public static function saveAll($list, $useMasterKey = false) * @param $target * @param bool $useMasterKey Whether to use the Master Key. * - * @return null - * * @throws ParseException + * + * @return null */ private static function deepSave($target, $useMasterKey = false) { - $unsavedChildren = array(); - $unsavedFiles = array(); - static::findUnsavedChildren($target, $unsavedChildren, $unsavedFiles); - $sessionToken = null; - if (ParseUser::getCurrentUser()) { - $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); - } + $unsavedChildren = []; + $unsavedFiles = []; + static::findUnsavedChildren($target, $unsavedChildren, $unsavedFiles); + $sessionToken = null; + if (ParseUser::getCurrentUser()) { + $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); + } - foreach ($unsavedFiles as &$file) { - $file->save(); - } + foreach ($unsavedFiles as &$file) { + $file->save(); + } - $objects = array(); + $objects = []; // Get the set of unique objects among the children. foreach ($unsavedChildren as &$obj) { - if (!in_array($obj, $objects, true)) { - $objects[] = $obj; - } - } - $remaining = $objects; - - while (count($remaining) > 0) { - - $batch = array(); - $newRemaining = array(); - - foreach ($remaining as $key => &$object) { - if (count($batch) > 40) { - $newRemaining[] = $object; - continue; - } - if ($object->canBeSerialized()) { - $batch[] = $object; - } else { - $newRemaining[] = $object; + if (!in_array($obj, $objects, true)) { + $objects[] = $obj; } - } - $remaining = $newRemaining; + } + $remaining = $objects; + + while (count($remaining) > 0) { + $batch = []; + $newRemaining = []; + + foreach ($remaining as $key => &$object) { + if (count($batch) > 40) { + $newRemaining[] = $object; + continue; + } + if ($object->canBeSerialized()) { + $batch[] = $object; + } else { + $newRemaining[] = $object; + } + } + $remaining = $newRemaining; - if (count($batch) === 0) { - throw new Exception("Tried to save a batch with a cycle."); - } + if (count($batch) === 0) { + throw new Exception("Tried to save a batch with a cycle."); + } - $requests = array(); - foreach ($batch as $obj) { - $json = $obj->getSaveJSON(); - $method = 'POST'; - $path = '/1/classes/' . $obj->getClassName(); - if ($obj->getObjectId()) { - $path .= '/' . $obj->getObjectId(); - $method = 'PUT'; - } - $requests[] = array('method' => $method, - 'path' => $path, - 'body' => $json - ); - } + $requests = []; + foreach ($batch as $obj) { + $json = $obj->getSaveJSON(); + $method = 'POST'; + $path = '/1/classes/'.$obj->getClassName(); + if ($obj->getObjectId()) { + $path .= '/'.$obj->getObjectId(); + $method = 'PUT'; + } + $requests[] = ['method' => $method, + 'path' => $path, + 'body' => $json, + ]; + } - if (count($requests) === 1) { - $req = $requests[0]; - $result = ParseClient::_request($req['method'], + if (count($requests) === 1) { + $req = $requests[0]; + $result = ParseClient::_request($req['method'], $req['path'], $sessionToken, json_encode($req['body']), $useMasterKey); - $batch[0]->mergeAfterSave($result); - } else { - $result = ParseClient::_request('POST', '/1/batch', $sessionToken, - json_encode(array("requests" => $requests)), $useMasterKey); - - $errorCollection = array(); - - foreach ($batch as $key => &$obj) { - if (isset($result[$key]['success'])) { - $obj->mergeAfterSave($result[$key]['success']); - } else if (isset($result[$key]['error'])) { - $response = $result[$key]; - $error = $response['error']['error']; - $code = isset($response['error']['code']) ? - $response['error']['code'] : -1; - $errorCollection[] = array( - 'error' => $error, - 'code' => $code, - 'object' => $obj - ); + $batch[0]->mergeAfterSave($result); } else { - $errorCollection[] = array( - 'error' => 'Unknown error in batch save.', - 'code' => -1, - 'object' => $obj - ); - } - } - if (count($errorCollection)) { - throw new ParseAggregateException( + $result = ParseClient::_request('POST', '/1/batch', $sessionToken, + json_encode(["requests" => $requests]), $useMasterKey); + + $errorCollection = []; + + foreach ($batch as $key => &$obj) { + if (isset($result[$key]['success'])) { + $obj->mergeAfterSave($result[$key]['success']); + } elseif (isset($result[$key]['error'])) { + $response = $result[$key]; + $error = $response['error']['error']; + $code = isset($response['error']['code']) ? + $response['error']['code'] : -1; + $errorCollection[] = [ + 'error' => $error, + 'code' => $code, + 'object' => $obj, + ]; + } else { + $errorCollection[] = [ + 'error' => 'Unknown error in batch save.', + 'code' => -1, + 'object' => $obj, + ]; + } + } + if (count($errorCollection)) { + throw new ParseAggregateException( "Errors during batch save.", $errorCollection ); - } + } + } } - } } /** @@ -972,18 +978,18 @@ private static function deepSave($target, $useMasterKey = false) private static function findUnsavedChildren($object, &$unsavedChildren, &$unsavedFiles) { - static::traverse(true, $object, function ($obj) use ( + static::traverse(true, $object, function ($obj) use ( &$unsavedChildren, &$unsavedFiles ) { if ($obj instanceof ParseObject) { - if ($obj->_isDirty(false)) { - $unsavedChildren[] = $obj; - } - } else if ($obj instanceof ParseFile) { - if (!$obj->getURL()) { - $unsavedFiles[] = $obj; - } + if ($obj->_isDirty(false)) { + $unsavedChildren[] = $obj; + } + } elseif ($obj instanceof ParseFile) { + if (!$obj->getURL()) { + $unsavedFiles[] = $obj; + } } }); @@ -1000,30 +1006,33 @@ private static function findUnsavedChildren($object, * @return mixed The result of calling mapFunction on the root object. */ private static function traverse($deep, &$object, $mapFunction, - $seen = array()) + $seen = []) { - if ($object instanceof ParseObject) { - if (in_array($object, $seen, true)) { - return null; - } - $seen[] = $object; - if ($deep) { - self::traverse( + if ($object instanceof ParseObject) { + if (in_array($object, $seen, true)) { + return; + } + $seen[] = $object; + if ($deep) { + self::traverse( $deep, $object->estimatedData, $mapFunction, $seen ); + } + + return $mapFunction($object); } - return $mapFunction($object); - } - if ($object instanceof ParseRelation || $object instanceof ParseFile) { - return $mapFunction($object); - } - if (is_array($object)) { - foreach ($object as $key => $value) { - self::traverse($deep, $value, $mapFunction, $seen); + if ($object instanceof ParseRelation || $object instanceof ParseFile) { + return $mapFunction($object); + } + if (is_array($object)) { + foreach ($object as $key => $value) { + self::traverse($deep, $value, $mapFunction, $seen); + } + + return $mapFunction($object); } + return $mapFunction($object); - } - return $mapFunction($object); } /** @@ -1033,7 +1042,7 @@ private static function traverse($deep, &$object, $mapFunction, */ private function canBeSerialized() { - return self::canBeSerializedAsValue($this->estimatedData); + return self::canBeSerializedAsValue($this->estimatedData); } /** @@ -1046,21 +1055,23 @@ private function canBeSerialized() */ private static function canBeSerializedAsValue($object) { - $result = true; - self::traverse(false, $object, function ($obj) use (&$result) { + $result = true; + self::traverse(false, $object, function ($obj) use (&$result) { // short circuit as soon as possible. if ($result === false) { - return; + return; } // cannot make a pointer to an unsaved object. if ($obj instanceof ParseObject) { - if (!$obj->getObjectId()) { - $result = false; - return; - } + if (!$obj->getObjectId()) { + $result = false; + + return; + } } }); - return $result; + + return $result; } /** @@ -1072,48 +1083,52 @@ private static function canBeSerializedAsValue($object) */ private function mergeAfterSave($result) { - $this->applyOperations($this->operationSet, $this->serverData); - $this->mergeFromServer($result); - $this->operationSet = array(); - $this->rebuildEstimatedData(); + $this->applyOperations($this->operationSet, $this->serverData); + $this->mergeFromServer($result); + $this->operationSet = []; + $this->rebuildEstimatedData(); } /** * Access or create a Relation value for a key. * * @param string $key The key to access the relation for. + * * @return ParseRelation The ParseRelation object if the relation already * exists for the key or can be created for this key. */ public function getRelation($key) { - $relation = new ParseRelation($this, $key); - if (isset($this->estimatedData[$key])) { - $object = $this->estimatedData[$key]; - if ($object instanceof ParseRelation) { - $relation->setTargetClass($object->getTargetClass()); + $relation = new ParseRelation($this, $key); + if (isset($this->estimatedData[$key])) { + $object = $this->estimatedData[$key]; + if ($object instanceof ParseRelation) { + $relation->setTargetClass($object->getTargetClass()); + } } - } - return $relation; + + return $relation; } /** * Gets a Pointer referencing this Object. * + * @throws \Exception + * * @return array * - * @throws \Exception * @ignore */ public function _toPointer() { - if (!$this->objectId) { - throw new \Exception("Can't serialize an unsaved Parse.Object"); - } - return array( - '__type' => "Pointer", + if (!$this->objectId) { + throw new \Exception("Can't serialize an unsaved Parse.Object"); + } + + return [ + '__type' => "Pointer", 'className' => $this->className, - 'objectId' => $this->objectId); + 'objectId' => $this->objectId, ]; } /** @@ -1123,7 +1138,7 @@ public function _toPointer() */ public function setACL($acl) { - $this->_performOperation('ACL', new SetOperation($acl)); + $this->_performOperation('ACL', new SetOperation($acl)); } /** @@ -1133,69 +1148,71 @@ public function setACL($acl) */ public function getACL() { - return $this->getACLWithCopy(true); + return $this->getACLWithCopy(true); } - private function getACLWithCopy($mayCopy) - { - if (!isset($this->estimatedData['ACL'])) { - return null; - } - $acl = $this->estimatedData['ACL']; - if ($mayCopy && $acl->_isShared()) { - return clone $acl; + private function getACLWithCopy($mayCopy) + { + if (!isset($this->estimatedData['ACL'])) { + return; + } + $acl = $this->estimatedData['ACL']; + if ($mayCopy && $acl->_isShared()) { + return clone $acl; + } + + return $acl; } - return $acl; - } /** * Register a subclass. Should be called before any other Parse functions. * Cannot be called on the base class ParseObject. + * * @throws \Exception */ public static function registerSubclass() { - if (isset(static::$parseClassName)) { - if (!in_array(static::$parseClassName, self::$registeredSubclasses)) { - self::$registeredSubclasses[static::$parseClassName] = + if (isset(static::$parseClassName)) { + if (!in_array(static::$parseClassName, self::$registeredSubclasses)) { + self::$registeredSubclasses[static::$parseClassName] = get_called_class(); - } - } else { - throw new \Exception( + } + } else { + throw new \Exception( "Cannot register a subclass that does not have a parseClassName" ); - } + } } /** * Un-register a subclass. * Cannot be called on the base class ParseObject. + * * @ignore */ public static function _unregisterSubclass() { - $subclass = static::getSubclass(); - unset(self::$registeredSubclasses[$subclass]); + $subclass = static::getSubclass(); + unset(self::$registeredSubclasses[$subclass]); } /** * Creates a ParseQuery for the subclass of ParseObject. * Cannot be called on the base class ParseObject. * - * @return ParseQuery - * * @throws \Exception + * + * @return ParseQuery */ public static function query() { - $subclass = static::getSubclass(); - if ($subclass === false) { - throw new Exception( + $subclass = static::getSubclass(); + if ($subclass === false) { + throw new Exception( 'Cannot create a query for an unregistered subclass.' ); - } else { - return new ParseQuery($subclass); - } + } else { + return new ParseQuery($subclass); + } } - } diff --git a/src/Parse/ParsePush.php b/src/Parse/ParsePush.php index 59638d1c..43c9c385 100644 --- a/src/Parse/ParsePush.php +++ b/src/Parse/ParsePush.php @@ -3,14 +3,12 @@ namespace Parse; /** - * ParsePush - Handles sending push notifications with Parse + * ParsePush - Handles sending push notifications with Parse. * - * @package Parse * @author Fosco Marotto */ class ParsePush { - /** * Sends a push notification. * @@ -27,36 +25,38 @@ class ParsePush * @param boolean $useMasterKey Whether to use the Master Key for the request * * @throws \Exception, ParseException + * * @return mixed */ public static function send($data, $useMasterKey = false) { - if (isset($data['expiration_time']) + if (isset($data['expiration_time']) && isset($data['expiration_interval'])) { - throw new \Exception( + throw new \Exception( 'Both expiration_time and expiration_interval can\'t be set.' ); - } - if (isset($data['where'])) { - if ($data['where'] instanceof ParseQuery) { - $data['where'] = $data['where']->_getOptions()['where']; - } else { - throw new \Exception( + } + if (isset($data['where'])) { + if ($data['where'] instanceof ParseQuery) { + $data['where'] = $data['where']->_getOptions()['where']; + } else { + throw new \Exception( 'Where parameter for Parse Push must be of type ParseQuery' ); + } } - } - if (isset($data['push_time'])) { - //Local push date format is different from iso format generally used in Parse + if (isset($data['push_time'])) { + //Local push date format is different from iso format generally used in Parse //Schedule does not work if date format not correct $data['push_time'] = ParseClient::getLocalPushDateFormat($data['push_time']); - } - if (isset($data['expiration_time'])) { - $data['expiration_time'] = ParseClient::_encode( + } + if (isset($data['expiration_time'])) { + $data['expiration_time'] = ParseClient::_encode( $data['expiration_time'], false )['iso']; - } - return ParseClient::_request( + } + + return ParseClient::_request( 'POST', '/1/push', null, @@ -64,5 +64,4 @@ public static function send($data, $useMasterKey = false) $useMasterKey ); } - -} \ No newline at end of file +} diff --git a/src/Parse/ParseQuery.php b/src/Parse/ParseQuery.php index 2e080685..d8c824fd 100755 --- a/src/Parse/ParseQuery.php +++ b/src/Parse/ParseQuery.php @@ -3,14 +3,12 @@ namespace Parse; /** - * ParseQuery - Handles querying data from Parse + * ParseQuery - Handles querying data from Parse. * - * @package Parse * @author Fosco Marotto */ class ParseQuery { - /** * @var - Class Name for data stored on Parse. */ @@ -18,19 +16,19 @@ class ParseQuery /** * @var array - Where constraints. */ - private $where = array(); + private $where = []; /** * @var array - Order By keys. */ - private $orderBy = array(); + private $orderBy = []; /** * @var array - Include nested objects. */ - private $includes = array(); + private $includes = []; /** * @var array - Include certain keys only. */ - private $selectedKeys = array(); + private $selectedKeys = []; /** * @var int - Skip from the beginning of the search results. */ @@ -51,27 +49,28 @@ class ParseQuery */ public function __construct($className) { - $this->className = $className; + $this->className = $className; } /** - * Execute a query to retrieve a specific object + * Execute a query to retrieve a specific object. * * @param string $objectId Unique object id to retrieve. * @param bool $useMasterKey If the query should use the master key * - * @return array - * * @throws ParseException + * + * @return array */ public function get($objectId, $useMasterKey = false) { - $this->equalTo('objectId', $objectId); - $result = $this->first($useMasterKey); - if (empty($result)) { - throw new ParseException("Object not found.", 101); - } - return $result; + $this->equalTo('objectId', $objectId); + $result = $this->first($useMasterKey); + if (empty($result)) { + throw new ParseException("Object not found.", 101); + } + + return $result; } /** @@ -84,12 +83,13 @@ public function get($objectId, $useMasterKey = false) */ public function equalTo($key, $value) { - if ($value === null) { - $this->doesNotExist($key); - } else { - $this->where[$key] = $value; - } - return $this; + if ($value === null) { + $this->doesNotExist($key); + } else { + $this->where[$key] = $value; + } + + return $this; } /** @@ -97,10 +97,10 @@ public function equalTo($key, $value) */ private function addCondition($key, $condition, $value) { - if (!isset($this->where[$key])) { - $this->where[$key] = array(); - } - $this->where[$key][$condition] = ParseClient::_encode($value, true); + if (!isset($this->where[$key])) { + $this->where[$key] = []; + } + $this->where[$key][$condition] = ParseClient::_encode($value, true); } /** @@ -114,8 +114,9 @@ private function addCondition($key, $condition, $value) */ public function notEqualTo($key, $value) { - $this->addCondition($key, '$ne', $value); - return $this; + $this->addCondition($key, '$ne', $value); + + return $this; } /** @@ -129,8 +130,9 @@ public function notEqualTo($key, $value) */ public function lessThan($key, $value) { - $this->addCondition($key, '$lt', $value); - return $this; + $this->addCondition($key, '$lt', $value); + + return $this; } /** @@ -144,8 +146,9 @@ public function lessThan($key, $value) */ public function greaterThan($key, $value) { - $this->addCondition($key, '$gt', $value); - return $this; + $this->addCondition($key, '$gt', $value); + + return $this; } /** @@ -159,8 +162,9 @@ public function greaterThan($key, $value) */ public function greaterThanOrEqualTo($key, $value) { - $this->addCondition($key, '$gte', $value); - return $this; + $this->addCondition($key, '$gte', $value); + + return $this; } /** @@ -174,17 +178,19 @@ public function greaterThanOrEqualTo($key, $value) */ public function lessThanOrEqualTo($key, $value) { - $this->addCondition($key, '$lte', $value); - return $this; + $this->addCondition($key, '$lte', $value); + + return $this; } /** - * Converts a string into a regex that matches it. - * Surrounding with \Q .. \E does this, we just need to escape \E's in - * the text separately. - */ - private function quote($s) { - return "\\Q" . str_replace("\\E", "\\E\\\\E\\Q", $s) . "\\E"; + * Converts a string into a regex that matches it. + * Surrounding with \Q .. \E does this, we just need to escape \E's in + * the text separately. + */ + private function quote($s) + { + return "\\Q".str_replace("\\E", "\\E\\\\E\\Q", $s)."\\E"; } /** @@ -198,8 +204,9 @@ private function quote($s) { */ public function startsWith($key, $value) { - $this->addCondition($key, '$regex', "^".$this->quote($value)); - return $this; + $this->addCondition($key, '$regex', "^".$this->quote($value)); + + return $this; } /** @@ -210,29 +217,30 @@ public function startsWith($key, $value) */ public function _getOptions() { - $opts = array(); - if (!empty($this->where)) { - $opts['where'] = $this->where; - } - if (count($this->includes)) { - $opts['include'] = join(',', $this->includes); - } - if (count($this->selectedKeys)) { - $opts['keys'] = join(',', $this->selectedKeys); - } - if ($this->limit >= 0) { - $opts['limit'] = $this->limit; - } - if ($this->skip > 0) { - $opts['skip'] = $this->skip; - } - if ($this->orderBy) { - $opts['order'] = join(',', $this->orderBy); - } - if ($this->count) { - $opts['count'] = $this->count; - } - return $opts; + $opts = []; + if (!empty($this->where)) { + $opts['where'] = $this->where; + } + if (count($this->includes)) { + $opts['include'] = implode(',', $this->includes); + } + if (count($this->selectedKeys)) { + $opts['keys'] = implode(',', $this->selectedKeys); + } + if ($this->limit >= 0) { + $opts['limit'] = $this->limit; + } + if ($this->skip > 0) { + $opts['skip'] = $this->skip; + } + if ($this->orderBy) { + $opts['order'] = implode(',', $this->orderBy); + } + if ($this->count) { + $opts['count'] = $this->count; + } + + return $opts; } /** @@ -244,28 +252,30 @@ public function _getOptions() */ public function first($useMasterKey = false) { - $this->limit = 1; - $result = $this->find($useMasterKey); - if (count($result)) { - return $result[0]; - } else { - return array(); - } + $this->limit = 1; + $result = $this->find($useMasterKey); + if (count($result)) { + return $result[0]; + } else { + return []; + } } /** * Build query string from query constraints. + * * @param array $queryOptions Associative array of the query constraints. * * @return string Query string. */ private function buildQueryString($queryOptions) { - if (isset($queryOptions["where"])) { - $queryOptions["where"] = ParseClient::_encode($queryOptions["where"], true); - $queryOptions["where"] = json_encode($queryOptions["where"]); - } - return http_build_query($queryOptions); + if (isset($queryOptions["where"])) { + $queryOptions["where"] = ParseClient::_encode($queryOptions["where"], true); + $queryOptions["where"] = json_encode($queryOptions["where"]); + } + + return http_build_query($queryOptions); } /** @@ -277,13 +287,14 @@ private function buildQueryString($queryOptions) */ public function count($useMasterKey = false) { - $this->limit = 0; - $this->count = 1; - $queryString = $this->buildQueryString($this->_getOptions()); - $result = ParseClient::_request('GET', - '/1/classes/' . $this->className . - '?' . $queryString, null, null, $useMasterKey); - return $result['count']; + $this->limit = 0; + $this->count = 1; + $queryString = $this->buildQueryString($this->_getOptions()); + $result = ParseClient::_request('GET', + '/1/classes/'.$this->className. + '?'.$queryString, null, null, $useMasterKey); + + return $result['count']; } /** @@ -295,21 +306,22 @@ public function count($useMasterKey = false) */ public function find($useMasterKey = false) { - $sessionToken = null; - if (ParseUser::getCurrentUser()) { - $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); - } - $queryString = $this->buildQueryString($this->_getOptions()); - $result = ParseClient::_request('GET', - '/1/classes/' . $this->className . - '?' . $queryString, $sessionToken, null, $useMasterKey); - $output = array(); - foreach ($result['results'] as $row) { - $obj = ParseObject::create($this->className, $row['objectId']); - $obj->_mergeAfterFetchWithSelectedKeys($row, $this->selectedKeys); - $output[] = $obj; - } - return $output; + $sessionToken = null; + if (ParseUser::getCurrentUser()) { + $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); + } + $queryString = $this->buildQueryString($this->_getOptions()); + $result = ParseClient::_request('GET', + '/1/classes/'.$this->className. + '?'.$queryString, $sessionToken, null, $useMasterKey); + $output = []; + foreach ($result['results'] as $row) { + $obj = ParseObject::create($this->className, $row['objectId']); + $obj->_mergeAfterFetchWithSelectedKeys($row, $this->selectedKeys); + $output[] = $obj; + } + + return $output; } /** @@ -321,12 +333,13 @@ public function find($useMasterKey = false) */ public function skip($n) { - $this->skip = $n; - return $this; + $this->skip = $n; + + return $this; } /** - * Set the limit parameter as a query constraint + * Set the limit parameter as a query constraint. * * @param int $n Number of objects to return from the query. * @@ -334,21 +347,24 @@ public function skip($n) */ public function limit($n) { - $this->limit = $n; - return $this; + $this->limit = $n; + + return $this; } /** * Set the query orderBy to ascending for the given key(s). It overwrites the * existing order criteria. + * * @param mixed $key Key(s) to sort by, which is a string or an array of strings. * * @return ParseQuery Returns this query, so you can chain this call. */ public function ascending($key) { - $this->orderBy = array(); - return $this->addAscending($key); + $this->orderBy = []; + + return $this->addAscending($key); } /** @@ -361,25 +377,28 @@ public function ascending($key) */ public function addAscending($key) { - if (is_array($key)) { - $this->orderBy = array_merge($this->orderBy, $key); - } else { - $this->orderBy[] = $key; - } - return $this; + if (is_array($key)) { + $this->orderBy = array_merge($this->orderBy, $key); + } else { + $this->orderBy[] = $key; + } + + return $this; } /** * Set the query orderBy to descending for a given key(s). It overwrites the * existing order criteria. + * * @param mixed $key Key(s) to sort by, which is a string or an array of strings. * * @return ParseQuery Returns this query, so you can chain this call. */ public function descending($key) { - $this->orderBy = array(); - return $this->addDescending($key); + $this->orderBy = []; + + return $this->addDescending($key); } /** @@ -392,15 +411,16 @@ public function descending($key) */ public function addDescending($key) { - if (is_array($key)) { - $key = array_map(function ($element) { - return '-' . $element; + if (is_array($key)) { + $key = array_map(function ($element) { + return '-'.$element; }, $key); - $this->orderBy = array_merge($this->orderBy, $key); - } else { - $this->orderBy[] = "-" . $key; - } - return $this; + $this->orderBy = array_merge($this->orderBy, $key); + } else { + $this->orderBy[] = "-".$key; + } + + return $this; } /** @@ -414,8 +434,9 @@ public function addDescending($key) */ public function near($key, $point) { - $this->addCondition($key, '$nearSphere', $point); - return $this; + $this->addCondition($key, '$nearSphere', $point); + + return $this; } /** @@ -430,9 +451,10 @@ public function near($key, $point) */ public function withinRadians($key, $point, $maxDistance) { - $this->near($key, $point); - $this->addCondition($key, '$maxDistance', $maxDistance); - return $this; + $this->near($key, $point); + $this->addCondition($key, '$maxDistance', $maxDistance); + + return $this; } /** @@ -448,9 +470,10 @@ public function withinRadians($key, $point, $maxDistance) */ public function withinMiles($key, $point, $maxDistance) { - $this->near($key, $point); - $this->addCondition($key, '$maxDistance', $maxDistance / 3958.8); - return $this; + $this->near($key, $point); + $this->addCondition($key, '$maxDistance', $maxDistance / 3958.8); + + return $this; } /** @@ -466,9 +489,10 @@ public function withinMiles($key, $point, $maxDistance) */ public function withinKilometers($key, $point, $maxDistance) { - $this->near($key, $point); - $this->addCondition($key, '$maxDistance', $maxDistance / 6371.0); - return $this; + $this->near($key, $point); + $this->addCondition($key, '$maxDistance', $maxDistance / 6371.0); + + return $this; } /** @@ -484,9 +508,10 @@ public function withinKilometers($key, $point, $maxDistance) */ public function withinGeoBox($key, $southwest, $northeast) { - $this->addCondition($key, '$within', + $this->addCondition($key, '$within', ['$box' => [$southwest, $northeast]]); - return $this; + + return $this; } /** @@ -500,8 +525,9 @@ public function withinGeoBox($key, $southwest, $northeast) */ public function containedIn($key, $values) { - $this->addCondition($key, '$in', $values); - return $this; + $this->addCondition($key, '$in', $values); + + return $this; } /** @@ -518,29 +544,29 @@ public function containedIn($key, $values) */ public function each($callback, $useMasterKey = false, $batchSize = 100) { - if ($this->orderBy || $this->skip || ($this->limit >= 0)) { - throw new \Exception( + if ($this->orderBy || $this->skip || ($this->limit >= 0)) { + throw new \Exception( "Cannot iterate on a query with sort, skip, or limit."); - } - $query = new ParseQuery($this->className); - $query->where = $this->where; - $query->includes = $this->includes; - $query->limit = $batchSize; - $query->ascending("objectId"); - - $finished = false; - while (!$finished) { - $results = $query->find($useMasterKey); - $length = count($results); - for ($i = 0; $i < $length; $i++) { - $callback($results[$i]); } - if ($length == $query->limit) { - $query->greaterThan("objectId", $results[$length - 1]->getObjectId()); - } else { - $finished = true; + $query = new ParseQuery($this->className); + $query->where = $this->where; + $query->includes = $this->includes; + $query->limit = $batchSize; + $query->ascending("objectId"); + + $finished = false; + while (!$finished) { + $results = $query->find($useMasterKey); + $length = count($results); + for ($i = 0; $i < $length; $i++) { + $callback($results[$i]); + } + if ($length == $query->limit) { + $query->greaterThan("objectId", $results[$length - 1]->getObjectId()); + } else { + $finished = true; + } } - } } /** @@ -554,8 +580,9 @@ public function each($callback, $useMasterKey = false, $batchSize = 100) */ public function notContainedIn($key, $values) { - $this->addCondition($key, '$nin', $values); - return $this; + $this->addCondition($key, '$nin', $values); + + return $this; } /** @@ -570,10 +597,11 @@ public function notContainedIn($key, $values) */ public function matchesQuery($key, $query) { - $queryParam = $query->_getOptions(); - $queryParam["className"] = $query->className; - $this->addCondition($key, '$inQuery', $queryParam); - return $this; + $queryParam = $query->_getOptions(); + $queryParam["className"] = $query->className; + $this->addCondition($key, '$inQuery', $queryParam); + + return $this; } /** @@ -588,10 +616,11 @@ public function matchesQuery($key, $query) */ public function doesNotMatchQuery($key, $query) { - $queryParam = $query->_getOptions(); - $queryParam["className"] = $query->className; - $this->addCondition($key, '$notInQuery', $queryParam); - return $this; + $queryParam = $query->_getOptions(); + $queryParam["className"] = $query->className; + $this->addCondition($key, '$notInQuery', $queryParam); + + return $this; } /** @@ -608,11 +637,12 @@ public function doesNotMatchQuery($key, $query) */ public function matchesKeyInQuery($key, $queryKey, $query) { - $queryParam = $query->_getOptions(); - $queryParam["className"] = $query->className; - $this->addCondition($key, '$select', + $queryParam = $query->_getOptions(); + $queryParam["className"] = $query->className; + $this->addCondition($key, '$select', ['key' => $queryKey, 'query' => $queryParam]); - return $this; + + return $this; } /** @@ -629,11 +659,12 @@ public function matchesKeyInQuery($key, $queryKey, $query) */ public function doesNotMatchKeyInQuery($key, $queryKey, $query) { - $queryParam = $query->_getOptions(); - $queryParam["className"] = $query->className; - $this->addCondition($key, '$dontSelect', + $queryParam = $query->_getOptions(); + $queryParam["className"] = $query->className; + $this->addCondition($key, '$dontSelect', ['key' => $queryKey, 'query' => $queryParam]); - return $this; + + return $this; } /** @@ -642,25 +673,26 @@ public function doesNotMatchKeyInQuery($key, $queryKey, $query) * * @param array $queryObjects Array of ParseQuery objects to OR. * - * @return ParseQuery The query that is the OR of the passed in queries. - * * @throws \Exception If all queries don't have same class. + * + * @return ParseQuery The query that is the OR of the passed in queries. */ public static function orQueries($queryObjects) { - $className = null; - $length = count($queryObjects); - for ($i = 0; $i < $length; $i++) { - if (is_null($className)) { - $className = $queryObjects[$i]->className; - } - if ($className != $queryObjects[$i]->className) { - throw new \Exception("All queries must be for the same class"); + $className = null; + $length = count($queryObjects); + for ($i = 0; $i < $length; $i++) { + if (is_null($className)) { + $className = $queryObjects[$i]->className; + } + if ($className != $queryObjects[$i]->className) { + throw new \Exception("All queries must be for the same class"); + } } - } - $query = new ParseQuery($className); - $query->_or($queryObjects); - return $query; + $query = new ParseQuery($className); + $query->_or($queryObjects); + + return $query; } /** @@ -673,12 +705,13 @@ public static function orQueries($queryObjects) */ private function _or($queries) { - $this->where['$or'] = array(); - $length = count($queries); - for ($i = 0; $i < $length; $i++) { - $this->where['$or'][] = $queries[$i]->where; - } - return $this; + $this->where['$or'] = []; + $length = count($queries); + for ($i = 0; $i < $length; $i++) { + $this->where['$or'][] = $queries[$i]->where; + } + + return $this; } /** @@ -692,8 +725,9 @@ private function _or($queries) */ public function containsAll($key, $values) { - $this->addCondition($key, '$all', $values); - return $this; + $this->addCondition($key, '$all', $values); + + return $this; } /** @@ -705,8 +739,9 @@ public function containsAll($key, $values) */ public function exists($key) { - $this->addCondition($key, '$exists', true); - return $this; + $this->addCondition($key, '$exists', true); + + return $this; } /** @@ -718,8 +753,9 @@ public function exists($key) */ public function doesNotExist($key) { - $this->addCondition($key, '$exists', false); - return $this; + $this->addCondition($key, '$exists', false); + + return $this; } /** @@ -734,12 +770,13 @@ public function doesNotExist($key) */ public function select($key) { - if (is_array($key)) { - $this->selectedKeys = array_merge($this->selectedKeys, $key); - } else { - $this->selectedKeys[] = $key; - } - return $this; + if (is_array($key)) { + $this->selectedKeys = array_merge($this->selectedKeys, $key); + } else { + $this->selectedKeys[] = $key; + } + + return $this; } /** @@ -753,16 +790,18 @@ public function select($key) */ public function includeKey($key) { - if (is_array($key)) { - $this->includes = array_merge($this->includes, $key); - } else { - $this->includes[] = $key; - } - return $this; + if (is_array($key)) { + $this->includes = array_merge($this->includes, $key); + } else { + $this->includes[] = $key; + } + + return $this; } /** * Add constraint for parse relation. + * * @param string $key * @param mixed $value * @@ -770,7 +809,8 @@ public function includeKey($key) */ public function relatedTo($key, $value) { - $this->addCondition('$relatedTo', $key, $value); - return $this; + $this->addCondition('$relatedTo', $key, $value); + + return $this; } } diff --git a/src/Parse/ParseRelation.php b/src/Parse/ParseRelation.php index e3a00210..31df589e 100644 --- a/src/Parse/ParseRelation.php +++ b/src/Parse/ParseRelation.php @@ -1,18 +1,17 @@ */ - -class ParseRelation { - +class ParseRelation +{ /** * @var ParseObject - The parent of this relation. */ @@ -35,9 +34,9 @@ class ParseRelation { */ public function __construct($parent, $key, $targetClassName = null) { - $this->parent = $parent; - $this->key = $key; - $this->targetClassName = $targetClassName; + $this->parent = $parent; + $this->key = $key; + $this->targetClassName = $targetClassName; } /** @@ -50,18 +49,18 @@ public function __construct($parent, $key, $targetClassName = null) */ private function ensureParentAndKey($parent, $key) { - if (!$this->parent) { - $this->parent = $parent; - } - if (!$this->key) { - $this->key = $key; - } - if ($this->parent != $parent) { - throw new \Exception('Internal Error. Relation retrieved from two different Objects.'); - } - if ($this->key != $key) { - throw new \Exception('Internal Error. Relation retrieved from two different keys.'); - } + if (!$this->parent) { + $this->parent = $parent; + } + if (!$this->key) { + $this->key = $key; + } + if ($this->parent != $parent) { + throw new \Exception('Internal Error. Relation retrieved from two different Objects.'); + } + if ($this->key != $key) { + throw new \Exception('Internal Error. Relation retrieved from two different keys.'); + } } /** @@ -71,12 +70,12 @@ private function ensureParentAndKey($parent, $key) */ public function add($objects) { - if (!is_array($objects)) { - $objects = [$objects]; - } - $operation = new ParseRelationOperation($objects, null); - $this->targetClassName = $operation->_getTargetClass(); - $this->parent->_performOperation($this->key, $operation); + if (!is_array($objects)) { + $objects = [$objects]; + } + $operation = new ParseRelationOperation($objects, null); + $this->targetClassName = $operation->_getTargetClass(); + $this->parent->_performOperation($this->key, $operation); } /** @@ -86,12 +85,12 @@ public function add($objects) */ public function remove($objects) { - if (!is_array($objects)) { - $objects = [$objects]; - } - $operation = new ParseRelationOperation(null, $objects); - $this->targetClassName = $operation->_getTargetClass(); - $this->parent->_performOperation($this->key, $operation); + if (!is_array($objects)) { + $objects = [$objects]; + } + $operation = new ParseRelationOperation(null, $objects); + $this->targetClassName = $operation->_getTargetClass(); + $this->parent->_performOperation($this->key, $operation); } /** @@ -101,7 +100,7 @@ public function remove($objects) */ public function getTargetClass() { - return $this->targetClassName; + return $this->targetClassName; } /** @@ -111,7 +110,7 @@ public function getTargetClass() */ public function setTargetClass($className) { - $this->targetClassName = $className; + $this->targetClassName = $className; } /** @@ -119,8 +118,9 @@ public function setTargetClass($className) * * @param $parent */ - public function setParent($parent) { - $this->parent = $parent; + public function setParent($parent) + { + $this->parent = $parent; } /** @@ -130,9 +130,10 @@ public function setParent($parent) { */ public function getQuery() { - $query = new ParseQuery($this->targetClassName); - $query->relatedTo('object', $this->parent->_toPointer()); - $query->relatedTo('key', $this->key); - return $query; + $query = new ParseQuery($this->targetClassName); + $query->relatedTo('object', $this->parent->_toPointer()); + $query->relatedTo('key', $this->key); + + return $query; } } diff --git a/src/Parse/ParseRole.php b/src/Parse/ParseRole.php index dd780195..97dbdbc6 100644 --- a/src/Parse/ParseRole.php +++ b/src/Parse/ParseRole.php @@ -2,17 +2,13 @@ namespace Parse; -use Parse\ParseObject; - /** * ParseRole - Representation of an access Role. * - * @package Parse * @author Fosco Marotto */ class ParseRole extends ParseObject { - public static $parseClassName = "_Role"; /** @@ -25,10 +21,11 @@ class ParseRole extends ParseObject */ public static function createRole($name, ParseACL $acl) { - $role = ParseObject::create(static::$parseClassName); - $role->setName($name); - $role->setACL($acl); - return $role; + $role = ParseObject::create(static::$parseClassName); + $role->setName($name); + $role->setACL($acl); + + return $role; } /** @@ -38,7 +35,7 @@ public static function createRole($name, ParseACL $acl) */ public function getName() { - return $this->get("name"); + return $this->get("name"); } /** @@ -50,17 +47,18 @@ public function getName() */ public function setName($name) { - if ($this->getObjectId()) { - throw new ParseException( + if ($this->getObjectId()) { + throw new ParseException( "A role's name can only be set before it has been saved." ); - } - if (!is_string($name)) { - throw new ParseException( + } + if (!is_string($name)) { + throw new ParseException( "A role's name must be a string." ); - } - return $this->set("name", $name); + } + + return $this->set("name", $name); } /** @@ -72,7 +70,7 @@ public function setName($name) */ public function getUsers() { - return $this->getRelation("users"); + return $this->getRelation("users"); } /** @@ -84,24 +82,22 @@ public function getUsers() */ public function getRoles() { - return $this->getRelation("roles"); + return $this->getRelation("roles"); } - public function save($useMasterKey = false) - { - if (!$this->getACL()) { - throw new ParseException( + public function save($useMasterKey = false) + { + if (!$this->getACL()) { + throw new ParseException( "Roles must have an ACL." ); - } - if (!$this->getName() || !is_string($this->getName())) { - throw new ParseException( + } + if (!$this->getName() || !is_string($this->getName())) { + throw new ParseException( "Roles must have a name." ); - } - return parent::save($useMasterKey); - } + } - - -} \ No newline at end of file + return parent::save($useMasterKey); + } +} diff --git a/src/Parse/ParseSession.php b/src/Parse/ParseSession.php index 2c93f8c2..8fa8f41f 100644 --- a/src/Parse/ParseSession.php +++ b/src/Parse/ParseSession.php @@ -2,21 +2,16 @@ namespace Parse; -use Parse\ParseObject; -use Parse\ParseUser; - /** * ParseSession - Representation of an expiring user session. * - * @package Parse * @author Fosco Marotto */ class ParseSession extends ParseObject { - public static $parseClassName = "_Session"; - private $_sessionToken = null; + private $_sessionToken = null; /** * Returns the session token string. @@ -25,7 +20,7 @@ class ParseSession extends ParseObject */ public function getSessionToken() { - return $this->_sessionToken; + return $this->_sessionToken; } /** @@ -37,14 +32,14 @@ public function getSessionToken() */ public static function getCurrentSession($useMasterKey = false) { - $token = ParseUser::getCurrentUser()->getSessionToken(); - $response = ParseClient::_request('GET', '/1/sessions/me', $token, null, $useMasterKey); - $session = new ParseSession(); - $session->_mergeAfterFetch($response); - $session->handleSaveResult(); - return $session; - } + $token = ParseUser::getCurrentUser()->getSessionToken(); + $response = ParseClient::_request('GET', '/1/sessions/me', $token, null, $useMasterKey); + $session = new ParseSession(); + $session->_mergeAfterFetch($response); + $session->handleSaveResult(); + return $session; + } /** * Determines whether the current session token is revocable. @@ -55,10 +50,10 @@ public static function getCurrentSession($useMasterKey = false) */ public static function isCurrentSessionRevocable() { - $user = ParseUser::getCurrentUser(); - if ($user) { - return self::_isRevocable($user->getSessionToken()); - } + $user = ParseUser::getCurrentUser(); + if ($user) { + return self::_isRevocable($user->getSessionToken()); + } } /** @@ -70,7 +65,7 @@ public static function isCurrentSessionRevocable() */ public static function _isRevocable($token) { - return strpos($token, "r:") === 0; + return strpos($token, "r:") === 0; } /** @@ -80,11 +75,10 @@ public static function _isRevocable($token) */ private function handleSaveResult() { - if (isset($this->serverData['sessionToken'])) { - $this->_sessionToken = $this->serverData['sessionToken']; - unset($this->serverData['sessionToken']); - } - $this->rebuildEstimatedData(); + if (isset($this->serverData['sessionToken'])) { + $this->_sessionToken = $this->serverData['sessionToken']; + unset($this->serverData['sessionToken']); + } + $this->rebuildEstimatedData(); } - -} \ No newline at end of file +} diff --git a/src/Parse/ParseSessionStorage.php b/src/Parse/ParseSessionStorage.php index 2d38ee11..7aec9c1a 100644 --- a/src/Parse/ParseSessionStorage.php +++ b/src/Parse/ParseSessionStorage.php @@ -5,66 +5,64 @@ /** * ParseSessionStorage - Uses PHP session support for persistent storage. * - * @package Parse * @author Fosco Marotto */ class ParseSessionStorage implements ParseStorageInterface { - /** * @var string Parse will store its values in a specific key. */ private $storageKey = 'parseData'; - public function __construct() - { - if (session_status() !== PHP_SESSION_ACTIVE) { - throw new ParseException( + public function __construct() + { + if (session_status() !== PHP_SESSION_ACTIVE) { + throw new ParseException( 'PHP session_start() must be called first.' ); + } + if (!isset($_SESSION[$this->storageKey])) { + $_SESSION[$this->storageKey] = []; + } } - if (!isset($_SESSION[$this->storageKey])) { - $_SESSION[$this->storageKey] = array(); + + public function set($key, $value) + { + $_SESSION[$this->storageKey][$key] = $value; } - } - public function set($key, $value) - { - $_SESSION[$this->storageKey][$key] = $value; - } + public function remove($key) + { + unset($_SESSION[$this->storageKey][$key]); + } - public function remove($key) - { - unset($_SESSION[$this->storageKey][$key]); - } + public function get($key) + { + if (isset($_SESSION[$this->storageKey][$key])) { + return $_SESSION[$this->storageKey][$key]; + } - public function get($key) - { - if (isset($_SESSION[$this->storageKey][$key])) { - return $_SESSION[$this->storageKey][$key]; + return; } - return null; - } - public function clear() - { - $_SESSION[$this->storageKey] = array(); - } + public function clear() + { + $_SESSION[$this->storageKey] = []; + } - public function save() - { - // No action required. PHP handles persistence for $_SESSION. + public function save() + { + // No action required. PHP handles persistence for $_SESSION. return; - } - - public function getKeys() - { - return array_keys($_SESSION[$this->storageKey]); - } + } - public function getAll() - { - return $_SESSION[$this->storageKey]; - } + public function getKeys() + { + return array_keys($_SESSION[$this->storageKey]); + } -} \ No newline at end of file + public function getAll() + { + return $_SESSION[$this->storageKey]; + } +} diff --git a/src/Parse/ParseStorageInterface.php b/src/Parse/ParseStorageInterface.php index c3700048..0f24c178 100644 --- a/src/Parse/ParseStorageInterface.php +++ b/src/Parse/ParseStorageInterface.php @@ -5,12 +5,10 @@ /** * ParseStorageInterface - Specifies an interface for implementing persistence. * - * @package Parse * @author Fosco Marotto */ interface ParseStorageInterface { - /** * Sets a key-value pair in storage. * @@ -68,5 +66,4 @@ public function getKeys(); * @return array */ public function getAll(); - -} \ No newline at end of file +} diff --git a/src/Parse/ParseUser.php b/src/Parse/ParseUser.php index f2f4d72c..5dfb6b5e 100644 --- a/src/Parse/ParseUser.php +++ b/src/Parse/ParseUser.php @@ -5,12 +5,10 @@ /** * ParseUser - Representation of a user object stored on Parse. * - * @package Parse * @author Fosco Marotto */ class ParseUser extends ParseObject { - public static $parseClassName = "_User"; /** @@ -30,7 +28,7 @@ class ParseUser extends ParseObject */ public function getUsername() { - return $this->get("username"); + return $this->get("username"); } /** @@ -42,7 +40,7 @@ public function getUsername() */ public function setUsername($username) { - return $this->set("username", $username); + return $this->set("username", $username); } /** @@ -54,7 +52,7 @@ public function setUsername($username) */ public function setPassword($password) { - return $this->set("password", $password); + return $this->set("password", $password); } /** @@ -64,7 +62,7 @@ public function setPassword($password) */ public function getEmail() { - return $this->get("email"); + return $this->get("email"); } /** @@ -76,7 +74,7 @@ public function getEmail() */ public function setEmail($email) { - return $this->set("email", $email); + return $this->set("email", $email); } /** @@ -86,31 +84,31 @@ public function setEmail($email) */ public function isAuthenticated() { - return $this->_sessionToken !== null; + return $this->_sessionToken !== null; } /** * Signs up the current user, or throw if invalid. * This will create a new ParseUser on the server, and also persist the - * session so that you can access the user using ParseUser::getCurrentUser(); + * session so that you can access the user using ParseUser::getCurrentUser();. */ public function signUp() { - if (!$this->get('username')) { - throw new ParseException("Cannot sign up user with an empty name"); - } - if (!$this->get('password')) { - throw new ParseException( + if (!$this->get('username')) { + throw new ParseException("Cannot sign up user with an empty name"); + } + if (!$this->get('password')) { + throw new ParseException( "Cannot sign up user with an empty password." ); - } - if ($this->getObjectId()) { - throw new ParseException( + } + if ($this->getObjectId()) { + throw new ParseException( "Cannot sign up an already existing user." ); - } - parent::save(); - $this->handleSaveResult(true); + } + parent::save(); + $this->handleSaveResult(true); } /** @@ -119,27 +117,28 @@ public function signUp() * @param string $username * @param string $password * - * @return ParseUser - * * @throws ParseException + * + * @return ParseUser */ public static function logIn($username, $password) { - if (!$username) { - throw new ParseException("Cannot log in user with an empty name"); - } - if (!$password) { - throw new ParseException( + if (!$username) { + throw new ParseException("Cannot log in user with an empty name"); + } + if (!$password) { + throw new ParseException( "Cannot log in user with an empty password." ); - } - $data = array("username" => $username, "password" => $password); - $result = ParseClient::_request("GET", "/1/login", "", $data); - $user = new ParseUser(); - $user->_mergeAfterFetch($result); - $user->handleSaveResult(true); - ParseClient::getStorage()->set("user", $user); - return $user; + } + $data = ["username" => $username, "password" => $password]; + $result = ParseClient::_request("GET", "/1/login", "", $data); + $user = new ParseUser(); + $user->_mergeAfterFetch($result); + $user->handleSaveResult(true); + ParseClient::getStorage()->set("user", $user); + + return $user; } /** @@ -152,33 +151,34 @@ public static function logIn($username, $password) */ public static function become($sessionToken) { - $result = ParseClient::_request('GET', '/1/users/me', $sessionToken); - $user = new ParseUser(); - $user->_mergeAfterFetch($result); - $user->handleSaveResult(true); - ParseClient::getStorage()->set("user", $user); - return $user; + $result = ParseClient::_request('GET', '/1/users/me', $sessionToken); + $user = new ParseUser(); + $user->_mergeAfterFetch($result); + $user->handleSaveResult(true); + ParseClient::getStorage()->set("user", $user); + + return $user; } /** * Log out the current user. This will clear the storage and future calls * to current will return null. - * This will make a network request to /1/logout to invalidate the session + * This will make a network request to /1/logout to invalidate the session. * * @return null */ public static function logOut() { - $user = ParseUser::getCurrentUser(); - if ($user) { - try { - ParseClient::_request('POST', '/1/logout', $user->getSessionToken()); - } catch (ParseException $ex) { - // If this fails, we're going to ignore it. + $user = ParseUser::getCurrentUser(); + if ($user) { + try { + ParseClient::_request('POST', '/1/logout', $user->getSessionToken()); + } catch (ParseException $ex) { + // If this fails, we're going to ignore it. + } + static::$currentUser = null; } - static::$currentUser = null; - } - ParseClient::getStorage()->remove('user'); + ParseClient::getStorage()->remove('user'); } /** @@ -190,18 +190,18 @@ public static function logOut() */ private function handleSaveResult($makeCurrent = false) { - if (isset($this->serverData['password'])) { - unset($this->serverData['password']); - } - if (isset($this->serverData['sessionToken'])) { - $this->_sessionToken = $this->serverData['sessionToken']; - unset($this->serverData['sessionToken']); - } - if ($makeCurrent) { - static::$currentUser = $this; - static::saveCurrentUser(); - } - $this->rebuildEstimatedData(); + if (isset($this->serverData['password'])) { + unset($this->serverData['password']); + } + if (isset($this->serverData['sessionToken'])) { + $this->_sessionToken = $this->serverData['sessionToken']; + unset($this->serverData['sessionToken']); + } + if ($makeCurrent) { + static::$currentUser = $this; + static::saveCurrentUser(); + } + $this->rebuildEstimatedData(); } /** @@ -212,28 +212,31 @@ private function handleSaveResult($makeCurrent = false) */ public static function getCurrentUser() { - if (static::$currentUser instanceof ParseUser) { - return static::$currentUser; - } - $storage = ParseClient::getStorage(); - $userData = $storage->get("user"); - if ($userData instanceof ParseUser) { - static::$currentUser = $userData; - return $userData; - } - if (isset($userData["id"]) && isset($userData["_sessionToken"])) { - $user = ParseUser::create("_User", $userData["id"]); - unset($userData["id"]); - $user->_sessionToken = $userData["_sessionToken"]; - unset($userData["_sessionToken"]); - foreach ($userData as $key => $value) { - $user->set($key, $value); + if (static::$currentUser instanceof ParseUser) { + return static::$currentUser; } - $user->_opSetQueue = array(); - static::$currentUser = $user; - return $user; - } - return null; + $storage = ParseClient::getStorage(); + $userData = $storage->get("user"); + if ($userData instanceof ParseUser) { + static::$currentUser = $userData; + + return $userData; + } + if (isset($userData["id"]) && isset($userData["_sessionToken"])) { + $user = ParseUser::create("_User", $userData["id"]); + unset($userData["id"]); + $user->_sessionToken = $userData["_sessionToken"]; + unset($userData["_sessionToken"]); + foreach ($userData as $key => $value) { + $user->set($key, $value); + } + $user->_opSetQueue = []; + static::$currentUser = $user; + + return $user; + } + + return; } /** @@ -243,18 +246,18 @@ public static function getCurrentUser() */ protected static function saveCurrentUser() { - $storage = ParseClient::getStorage(); - $storage->set('user', ParseUser::getCurrentUser()); + $storage = ParseClient::getStorage(); + $storage->set('user', ParseUser::getCurrentUser()); } /** - * Returns the session token, if available + * Returns the session token, if available. * * @return string|null */ public function getSessionToken() { - return $this->_sessionToken; + return $this->_sessionToken; } /** @@ -264,30 +267,31 @@ public function getSessionToken() */ public function isCurrent() { - if (ParseUser::getCurrentUser() && $this->getObjectId()) { - if ($this->getObjectId() == ParseUser::getCurrentUser()->getObjectId()) { - return true; + if (ParseUser::getCurrentUser() && $this->getObjectId()) { + if ($this->getObjectId() == ParseUser::getCurrentUser()->getObjectId()) { + return true; + } } - } - return false; + + return false; } /** * Save the current user object, unless it is not signed up. * - * @return null - * * @throws ParseException + * + * @return null */ public function save($useMasterKey = false) { - if ($this->getObjectId()) { - parent::save($useMasterKey); - } else { - throw new ParseException( + if ($this->getObjectId()) { + parent::save($useMasterKey); + } else { + throw new ParseException( "You must call signUp to create a new User." ); - } + } } /** @@ -301,8 +305,8 @@ public function save($useMasterKey = false) */ public static function requestPasswordReset($email) { - $json = json_encode(array('email' => $email)); - ParseClient::_request('POST', '/1/requestPasswordReset', null, $json); + $json = json_encode(['email' => $email]); + ParseClient::_request('POST', '/1/requestPasswordReset', null, $json); } /** @@ -310,7 +314,6 @@ public static function requestPasswordReset($email) */ public static function _clearCurrentUserVariable() { - static::$currentUser = null; + static::$currentUser = null; } - -} \ No newline at end of file +} diff --git a/tests/IncrementTest.php b/tests/IncrementTest.php index 5f5650db..c1ef34f8 100644 --- a/tests/IncrementTest.php +++ b/tests/IncrementTest.php @@ -1,8 +1,7 @@ set('yo', 1); - $obj->increment('yo'); - $obj->save(); - $query = new ParseQuery('TestObject'); - $query->equalTo('objectId', $obj->getObjectId()); - $result = $query->first(); - $this->assertEquals($result->get('yo'), 2, 'Increment did not work'); - } - - public function testIncrement() - { - $obj = ParseObject::create('TestObject'); - $obj->set('yo', 1); - $obj->save(); - $obj->increment('yo', 1); - $obj->save(); - $query = new ParseQuery('TestObject'); - $query->equalTo('objectId', $obj->getObjectId()); - $result = $query->first(); - $this->assertEquals($result->get('yo'), 2, 'Increment did not work'); - } - - public function testIncrementByValue() - { - $obj = ParseObject::create('TestObject'); - $obj->set('yo', 1); - $obj->save(); - $obj->increment('yo', 5); - $obj->save(); - $query = new ParseQuery('TestObject'); - $query->equalTo('objectId', $obj->getObjectId()); - $result = $query->first(); - $this->assertEquals($result->get('yo'), 6, 'Increment did not work'); - } - - public function testIncrementNegative() - { - $obj = ParseObject::create('TestObject'); - $obj->set('yo', 1); - $obj->save(); - $obj->increment('yo', -1); - $obj->save(); - $query = new ParseQuery('TestObject'); - $query->equalTo('objectId', $obj->getObjectId()); - $result = $query->first(); - $this->assertEquals($result->get('yo'), 0, 'Increment did not work'); - } - - public function testIncrementFloat() - { - $obj = ParseObject::create('TestObject'); - $obj->set('yo', 1); - $obj->save(); - $obj->increment('yo', 1.5); - $obj->save(); - $query = new ParseQuery('TestObject'); - $query->equalTo('objectId', $obj->getObjectId()); - $result = $query->first(); - $this->assertEquals($result->get('yo'), 2.5, 'Increment did not work'); - } - - public function testIncrementAtomic() - { - $obj = ParseObject::create('TestObject'); - $obj->set('yo', 1); - $obj->save(); - $query = new ParseQuery('TestObject'); - $query->equalTo('objectId', $obj->getObjectId()); - $objAgainOne = $query->first(); - $queryAgain = new ParseQuery('TestObject'); - $queryAgain->equalTo('objectId', $objAgainOne->getObjectId()); - $objAgainTwo = $queryAgain->first(); - $objAgainOne->increment('yo'); - $objAgainTwo->increment('yo'); - $objAgainOne->save(); - $objAgainOne->increment('yo'); - $objAgainOne->save(); - $objAgainTwo->save(); - $queryAgainTwo = new ParseQuery('TestObject'); - $queryAgainTwo->equalTo('objectId', $objAgainTwo->getObjectId()); - $objAgainThree = $query->first(); - $this->assertEquals($objAgainThree->get('yo'), 4); - } - - public function testIncrementGetsValueBack() - { - $obj = ParseObject::create('TestObject'); - $obj->set('yo', 1); - $obj->save(); - $query = new ParseQuery('TestObject'); - $query->equalTo('objectId', $obj->getObjectId()); - $objAgainOne = $query->first(); - $obj->increment('yo'); - $obj->save(); - $objAgainOne->increment('yo'); - $objAgainOne->save(); - $this->assertEquals($objAgainOne->get('yo'), 3); - } - - public function testIncrementWithOtherUpdates() - { - $obj = ParseObject::create('TestObject'); - $obj->set('yo', 1); - $obj->set('foo', 'bar'); - $obj->save(); - $query = new ParseQuery('TestObject'); - $query->equalTo('objectId', $obj->getObjectId()); - $objAgainOne = $query->first(); - $objAgainOne->increment('yo'); - $objAgainOne->set('foo', 'parse'); - $objAgainOne->save(); - $queryAgain = new ParseQuery('TestObject'); - $queryAgain->equalTo('objectId', $objAgainOne->getObjectId()); - $objAgainTwo = $queryAgain->first(); - $this->assertEquals($objAgainOne->get('foo'), 'parse'); - $this->assertEquals($objAgainOne->get('yo'), 2); - } - - public function testIncrementNonNumber() - { - $obj = ParseObject::create('TestObject'); - $obj->set('foo', 'bar'); - $obj->save(); - $this->setExpectedException( + ParseTestHelper::setUp(); + } + + public function tearDown() + { + ParseTestHelper::clearClass("TestObject"); + ParseTestHelper::tearDown(); + } + + public function testIncrementOnFreshObject() + { + $obj = ParseObject::create('TestObject'); + $obj->set('yo', 1); + $obj->increment('yo'); + $obj->save(); + $query = new ParseQuery('TestObject'); + $query->equalTo('objectId', $obj->getObjectId()); + $result = $query->first(); + $this->assertEquals($result->get('yo'), 2, 'Increment did not work'); + } + + public function testIncrement() + { + $obj = ParseObject::create('TestObject'); + $obj->set('yo', 1); + $obj->save(); + $obj->increment('yo', 1); + $obj->save(); + $query = new ParseQuery('TestObject'); + $query->equalTo('objectId', $obj->getObjectId()); + $result = $query->first(); + $this->assertEquals($result->get('yo'), 2, 'Increment did not work'); + } + + public function testIncrementByValue() + { + $obj = ParseObject::create('TestObject'); + $obj->set('yo', 1); + $obj->save(); + $obj->increment('yo', 5); + $obj->save(); + $query = new ParseQuery('TestObject'); + $query->equalTo('objectId', $obj->getObjectId()); + $result = $query->first(); + $this->assertEquals($result->get('yo'), 6, 'Increment did not work'); + } + + public function testIncrementNegative() + { + $obj = ParseObject::create('TestObject'); + $obj->set('yo', 1); + $obj->save(); + $obj->increment('yo', -1); + $obj->save(); + $query = new ParseQuery('TestObject'); + $query->equalTo('objectId', $obj->getObjectId()); + $result = $query->first(); + $this->assertEquals($result->get('yo'), 0, 'Increment did not work'); + } + + public function testIncrementFloat() + { + $obj = ParseObject::create('TestObject'); + $obj->set('yo', 1); + $obj->save(); + $obj->increment('yo', 1.5); + $obj->save(); + $query = new ParseQuery('TestObject'); + $query->equalTo('objectId', $obj->getObjectId()); + $result = $query->first(); + $this->assertEquals($result->get('yo'), 2.5, 'Increment did not work'); + } + + public function testIncrementAtomic() + { + $obj = ParseObject::create('TestObject'); + $obj->set('yo', 1); + $obj->save(); + $query = new ParseQuery('TestObject'); + $query->equalTo('objectId', $obj->getObjectId()); + $objAgainOne = $query->first(); + $queryAgain = new ParseQuery('TestObject'); + $queryAgain->equalTo('objectId', $objAgainOne->getObjectId()); + $objAgainTwo = $queryAgain->first(); + $objAgainOne->increment('yo'); + $objAgainTwo->increment('yo'); + $objAgainOne->save(); + $objAgainOne->increment('yo'); + $objAgainOne->save(); + $objAgainTwo->save(); + $queryAgainTwo = new ParseQuery('TestObject'); + $queryAgainTwo->equalTo('objectId', $objAgainTwo->getObjectId()); + $objAgainThree = $query->first(); + $this->assertEquals($objAgainThree->get('yo'), 4); + } + + public function testIncrementGetsValueBack() + { + $obj = ParseObject::create('TestObject'); + $obj->set('yo', 1); + $obj->save(); + $query = new ParseQuery('TestObject'); + $query->equalTo('objectId', $obj->getObjectId()); + $objAgainOne = $query->first(); + $obj->increment('yo'); + $obj->save(); + $objAgainOne->increment('yo'); + $objAgainOne->save(); + $this->assertEquals($objAgainOne->get('yo'), 3); + } + + public function testIncrementWithOtherUpdates() + { + $obj = ParseObject::create('TestObject'); + $obj->set('yo', 1); + $obj->set('foo', 'bar'); + $obj->save(); + $query = new ParseQuery('TestObject'); + $query->equalTo('objectId', $obj->getObjectId()); + $objAgainOne = $query->first(); + $objAgainOne->increment('yo'); + $objAgainOne->set('foo', 'parse'); + $objAgainOne->save(); + $queryAgain = new ParseQuery('TestObject'); + $queryAgain->equalTo('objectId', $objAgainOne->getObjectId()); + $objAgainTwo = $queryAgain->first(); + $this->assertEquals($objAgainOne->get('foo'), 'parse'); + $this->assertEquals($objAgainOne->get('yo'), 2); + } + + public function testIncrementNonNumber() + { + $obj = ParseObject::create('TestObject'); + $obj->set('foo', 'bar'); + $obj->save(); + $this->setExpectedException( 'Parse\ParseException', 'Cannot increment a non-number type' ); - $obj->increment('foo'); - $obj->save(); - } - - public function testIncrementOnDeletedField() - { - $obj = ParseObject::create('TestObject'); - $obj->set('yo', 1); - $obj->save(); - $obj->delete('yo'); - $obj->increment('yo'); - $query = new ParseQuery('TestObject'); - $query->equalTo('objectId', $obj->getObjectId()); - $result = $query->first(); - $this->assertEquals( + $obj->increment('foo'); + $obj->save(); + } + + public function testIncrementOnDeletedField() + { + $obj = ParseObject::create('TestObject'); + $obj->set('yo', 1); + $obj->save(); + $obj->delete('yo'); + $obj->increment('yo'); + $query = new ParseQuery('TestObject'); + $query->equalTo('objectId', $obj->getObjectId()); + $result = $query->first(); + $this->assertEquals( $result->get('yo'), 1, 'Error in increment on deleted field' ); - } - - public function testIncrementEmptyFieldOnFreshObject() - { - $obj = ParseObject::create('TestObject'); - $obj->increment('yo'); - $obj->save(); - $query = new ParseQuery('TestObject'); - $query->equalTo('objectId', $obj->getObjectId()); - $result = $query->first(); - $this->assertEquals($result->get('yo'), 1, + } + + public function testIncrementEmptyFieldOnFreshObject() + { + $obj = ParseObject::create('TestObject'); + $obj->increment('yo'); + $obj->save(); + $query = new ParseQuery('TestObject'); + $query->equalTo('objectId', $obj->getObjectId()); + $result = $query->first(); + $this->assertEquals($result->get('yo'), 1, 'Error in increment on empty field of fresh object' ); - } - - public function testIncrementEmptyField() - { - $obj = ParseObject::create('TestObject'); - $obj->save(); - $query = new ParseQuery('TestObject'); - $query->equalTo('objectId', $obj->getObjectId()); - $objAgain = $query->first(); - $obj->increment('yo'); - $objAgain->increment('yo'); - $obj->save(); - $objAgain->save(); - $queryAgain = new ParseQuery('TestObject'); - $queryAgain->equalTo('objectId', $objAgain->getObjectId()); - $objectAgainTwo = $queryAgain->first(); - $this->assertEquals($objectAgainTwo->get('yo'), 2, + } + + public function testIncrementEmptyField() + { + $obj = ParseObject::create('TestObject'); + $obj->save(); + $query = new ParseQuery('TestObject'); + $query->equalTo('objectId', $obj->getObjectId()); + $objAgain = $query->first(); + $obj->increment('yo'); + $objAgain->increment('yo'); + $obj->save(); + $objAgain->save(); + $queryAgain = new ParseQuery('TestObject'); + $queryAgain->equalTo('objectId', $objAgain->getObjectId()); + $objectAgainTwo = $queryAgain->first(); + $this->assertEquals($objectAgainTwo->get('yo'), 2, 'Error in increment on empty field' ); - } - - public function testIncrementEmptyFieldAndTypeConflict() - { - $obj = ParseObject::create('TestObject'); - $obj->save(); - $query = new ParseQuery('TestObject'); - $query->equalTo('objectId', $obj->getObjectId()); - $objAgain = $query->first(); - $obj->set('randomkey', 'bar'); - $obj->save(); - $objAgain->increment('randomkey'); - $this->setExpectedException('Parse\ParseException', + } + + public function testIncrementEmptyFieldAndTypeConflict() + { + $obj = ParseObject::create('TestObject'); + $obj->save(); + $query = new ParseQuery('TestObject'); + $query->equalTo('objectId', $obj->getObjectId()); + $objAgain = $query->first(); + $obj->set('randomkey', 'bar'); + $obj->save(); + $objAgain->increment('randomkey'); + $this->setExpectedException('Parse\ParseException', "invalid type for key" ); - $objAgain->save(); - } - - public function testIncrementEmptyFieldSolidifiesType() - { - $obj = ParseObject::create('TestObject'); - $obj->save(); - $query = new ParseQuery('TestObject'); - $query->equalTo('objectId', $obj->getObjectId()); - $objAgain = $query->first(); - $objAgain->set('randomkeyagain', 'bar'); - $obj->increment('randomkeyagain'); - $obj->save(); - $this->setExpectedException('Parse\ParseException', - 'invalid type for key randomkeyagain, ' . + $objAgain->save(); + } + + public function testIncrementEmptyFieldSolidifiesType() + { + $obj = ParseObject::create('TestObject'); + $obj->save(); + $query = new ParseQuery('TestObject'); + $query->equalTo('objectId', $obj->getObjectId()); + $objAgain = $query->first(); + $objAgain->set('randomkeyagain', 'bar'); + $obj->increment('randomkeyagain'); + $obj->save(); + $this->setExpectedException('Parse\ParseException', + 'invalid type for key randomkeyagain, '. 'expected number, but got string' ); - $objAgain->save(); - } -} \ No newline at end of file + $objAgain->save(); + } +} diff --git a/tests/ParseACLTest.php b/tests/ParseACLTest.php index 683e77f3..ae3425b6 100644 --- a/tests/ParseACLTest.php +++ b/tests/ParseACLTest.php @@ -1,391 +1,384 @@ setUsername('alice'); - $user->setPassword('wonderland'); - $user->signUp(); - $object = ParseObject::create('Object'); - $acl = ParseACL::createACLWithUser($user); - $object->setACL($acl); - $object->save(); - $this->assertTrue($object->getACL()->getUserReadAccess($user)); - $this->assertTrue($object->getACL()->getUserWriteAccess($user)); - $this->assertFalse($object->getACL()->getPublicReadAccess()); - $this->assertFalse($object->getACL()->getPublicWriteAccess()); - - $user->logOut(); - $query = new ParseQuery('Object'); - try { - $query->get($object->getObjectId()); - $this->fail('public should be unable to get'); - } catch (\Parse\ParseException $e) { + public function setUp() + { + ParseTestHelper::clearClass("_User"); + ParseTestHelper::clearClass("Object"); } - $this->assertEquals(0, count($query->find())); - $object->set('foo', 'bar'); - try { - $object->save(); - $this->fail('update should fail with object not found'); - } catch (\Parse\ParseException $e) { + public function tearDown() + { + ParseTestHelper::tearDown(); } - try { - $object->destroy(); - $this->fail('delete should fail with object not found'); - } catch (\Parse\ParseException $e) { + public function testACLAnObjectOwnedByOneUser() + { + $user = new ParseUser(); + $user->setUsername('alice'); + $user->setPassword('wonderland'); + $user->signUp(); + $object = ParseObject::create('Object'); + $acl = ParseACL::createACLWithUser($user); + $object->setACL($acl); + $object->save(); + $this->assertTrue($object->getACL()->getUserReadAccess($user)); + $this->assertTrue($object->getACL()->getUserWriteAccess($user)); + $this->assertFalse($object->getACL()->getPublicReadAccess()); + $this->assertFalse($object->getACL()->getPublicWriteAccess()); + + $user->logOut(); + $query = new ParseQuery('Object'); + try { + $query->get($object->getObjectId()); + $this->fail('public should be unable to get'); + } catch (\Parse\ParseException $e) { + } + + $this->assertEquals(0, count($query->find())); + $object->set('foo', 'bar'); + try { + $object->save(); + $this->fail('update should fail with object not found'); + } catch (\Parse\ParseException $e) { + } + + try { + $object->destroy(); + $this->fail('delete should fail with object not found'); + } catch (\Parse\ParseException $e) { + } + + ParseUser::logIn('alice', 'wonderland'); + + $result = $query->get($object->getObjectId()); + $this->assertNotNull($result); + $this->assertTrue($result->getACL()->getUserReadAccess($user)); + $this->assertTrue($result->getACL()->getUserWriteAccess($user)); + $this->assertFalse($result->getACL()->getPublicReadAccess()); + $this->assertFalse($result->getACL()->getPublicWriteAccess()); + + $this->assertEquals(1, count($query->find())); + $object->save(); + $object->destroy(); } - ParseUser::logIn('alice', 'wonderland'); - - $result = $query->get($object->getObjectId()); - $this->assertNotNull($result); - $this->assertTrue($result->getACL()->getUserReadAccess($user)); - $this->assertTrue($result->getACL()->getUserWriteAccess($user)); - $this->assertFalse($result->getACL()->getPublicReadAccess()); - $this->assertFalse($result->getACL()->getPublicWriteAccess()); - - $this->assertEquals(1, count($query->find())); - $object->save(); - $object->destroy(); - - } - - public function testACLMakingAnObjectPubliclyReadable() - { - $user = new ParseUser(); - $user->setUsername('alice'); - $user->setPassword('wonderland'); - $user->signUp(); - $object = ParseObject::create('Object'); - $acl = ParseACL::createACLWithUser($user); - $object->setACL($acl); - $object->save(); - $this->assertTrue($object->getACL()->getUserReadAccess($user)); - $this->assertTrue($object->getACL()->getUserWriteAccess($user)); - $this->assertFalse($object->getACL()->getPublicReadAccess()); - $this->assertFalse($object->getACL()->getPublicWriteAccess()); - - $acl->setPublicReadAccess(true); - $object->setACL($acl); - $object->save(); - - $this->assertTrue($object->getACL()->getUserReadAccess($user)); - $this->assertTrue($object->getACL()->getUserWriteAccess($user)); - $this->assertTrue($object->getACL()->getPublicReadAccess()); - $this->assertFalse($object->getACL()->getPublicWriteAccess()); - - $user->logOut(); - $query = new ParseQuery('Object'); - $result = $query->get($object->getObjectId()); - $this->assertNotNull($result); - - $this->assertTrue($result->getACL()->getUserReadAccess($user)); - $this->assertTrue($result->getACL()->getUserWriteAccess($user)); - $this->assertTrue($result->getACL()->getPublicReadAccess()); - $this->assertFalse($result->getACL()->getPublicWriteAccess()); - $this->assertEquals(1, count($query->find())); - $object->set('foo', 'bar'); - try { - $object->save(); - $this->fail('update should fail with object not found'); - } catch (\Parse\ParseException $e) { + public function testACLMakingAnObjectPubliclyReadable() + { + $user = new ParseUser(); + $user->setUsername('alice'); + $user->setPassword('wonderland'); + $user->signUp(); + $object = ParseObject::create('Object'); + $acl = ParseACL::createACLWithUser($user); + $object->setACL($acl); + $object->save(); + $this->assertTrue($object->getACL()->getUserReadAccess($user)); + $this->assertTrue($object->getACL()->getUserWriteAccess($user)); + $this->assertFalse($object->getACL()->getPublicReadAccess()); + $this->assertFalse($object->getACL()->getPublicWriteAccess()); + + $acl->setPublicReadAccess(true); + $object->setACL($acl); + $object->save(); + + $this->assertTrue($object->getACL()->getUserReadAccess($user)); + $this->assertTrue($object->getACL()->getUserWriteAccess($user)); + $this->assertTrue($object->getACL()->getPublicReadAccess()); + $this->assertFalse($object->getACL()->getPublicWriteAccess()); + + $user->logOut(); + $query = new ParseQuery('Object'); + $result = $query->get($object->getObjectId()); + $this->assertNotNull($result); + + $this->assertTrue($result->getACL()->getUserReadAccess($user)); + $this->assertTrue($result->getACL()->getUserWriteAccess($user)); + $this->assertTrue($result->getACL()->getPublicReadAccess()); + $this->assertFalse($result->getACL()->getPublicWriteAccess()); + $this->assertEquals(1, count($query->find())); + $object->set('foo', 'bar'); + try { + $object->save(); + $this->fail('update should fail with object not found'); + } catch (\Parse\ParseException $e) { + } + + try { + $object->destroy(); + $this->fail('delete should fail with object not found'); + } catch (\Parse\ParseException $e) { + } } - try { - $object->destroy(); - $this->fail('delete should fail with object not found'); - } catch (\Parse\ParseException $e) { + public function testACLMakingAnObjectPubliclyWritable() + { + $user = new ParseUser(); + $user->setUsername('alice'); + $user->setPassword('wonderland'); + $user->signUp(); + $object = ParseObject::create('Object'); + $acl = ParseACL::createACLWithUser($user); + $object->setACL($acl); + $object->save(); + $this->assertTrue($object->getACL()->getUserReadAccess($user)); + $this->assertTrue($object->getACL()->getUserWriteAccess($user)); + $this->assertFalse($object->getACL()->getPublicReadAccess()); + $this->assertFalse($object->getACL()->getPublicWriteAccess()); + + $acl->setPublicWriteAccess(true); + $object->setACL($acl); + $object->save(); + + $this->assertTrue($object->getACL()->getUserReadAccess($user)); + $this->assertTrue($object->getACL()->getUserWriteAccess($user)); + $this->assertFalse($object->getACL()->getPublicReadAccess()); + $this->assertTrue($object->getACL()->getPublicWriteAccess()); + + $user->logOut(); + + $query = new ParseQuery('Object'); + try { + $query->get($object->getObjectId()); + $this->fail('public should be unable to get'); + } catch (\Parse\ParseException $e) { + } + + $this->assertEquals(0, count($query->find())); + $object->set('foo', 'bar'); + + $object->save(); + $object->destroy(); } - } - public function testACLMakingAnObjectPubliclyWritable() - { - $user = new ParseUser(); - $user->setUsername('alice'); - $user->setPassword('wonderland'); - $user->signUp(); - $object = ParseObject::create('Object'); - $acl = ParseACL::createACLWithUser($user); - $object->setACL($acl); - $object->save(); - $this->assertTrue($object->getACL()->getUserReadAccess($user)); - $this->assertTrue($object->getACL()->getUserWriteAccess($user)); - $this->assertFalse($object->getACL()->getPublicReadAccess()); - $this->assertFalse($object->getACL()->getPublicWriteAccess()); - - $acl->setPublicWriteAccess(true); - $object->setACL($acl); - $object->save(); - - $this->assertTrue($object->getACL()->getUserReadAccess($user)); - $this->assertTrue($object->getACL()->getUserWriteAccess($user)); - $this->assertFalse($object->getACL()->getPublicReadAccess()); - $this->assertTrue($object->getACL()->getPublicWriteAccess()); - - $user->logOut(); - - $query = new ParseQuery('Object'); - try { - $query->get($object->getObjectId()); - $this->fail('public should be unable to get'); - } catch (\Parse\ParseException $e) { + public function testACLSharingWithAnotherUser() + { + $bob = new ParseUser(); + $bob->setUsername('bob'); + $bob->setPassword('pass'); + $bob->signUp(); + $bob->logOut(); + + $alice = new ParseUser(); + $alice->setUsername('alice'); + $alice->setPassword('wonderland'); + $alice->signUp(); + $object = ParseObject::create('Object'); + $acl = ParseACL::createACLWithUser($alice); + $acl->setUserReadAccess($bob, true); + $acl->setUserWriteAccess($bob, true); + $object->setACL($acl); + $object->save(); + $this->assertTrue($object->getACL()->getUserReadAccess($alice)); + $this->assertTrue($object->getACL()->getUserWriteAccess($alice)); + $this->assertTrue($object->getACL()->getUserReadAccess($bob)); + $this->assertTrue($object->getACL()->getUserWriteAccess($bob)); + $this->assertFalse($object->getACL()->getPublicReadAccess()); + $this->assertFalse($object->getACL()->getPublicWriteAccess()); + + ParseUser::logOut(); + + $query = new ParseQuery('Object'); + try { + $query->get($object->getObjectId()); + $this->fail('public should be unable to get'); + } catch (\Parse\ParseException $e) { + } + + $this->assertEquals(0, count($query->find())); + $object->set('foo', 'bar'); + try { + $object->save(); + $this->fail('update should fail with object not found'); + } catch (\Parse\ParseException $e) { + } + + try { + $object->destroy(); + $this->fail('delete should fail with object not found'); + } catch (\Parse\ParseException $e) { + } + + ParseUser::logIn('bob', 'pass'); + + $query = new ParseQuery('Object'); + $result = $query->get($object->getObjectId()); + $this->assertNotNull($result); + $this->assertTrue($result->getACL()->getUserReadAccess($alice)); + $this->assertTrue($result->getACL()->getUserWriteAccess($alice)); + $this->assertTrue($result->getACL()->getUserReadAccess($bob)); + $this->assertTrue($result->getACL()->getUserWriteAccess($bob)); + $this->assertFalse($result->getACL()->getPublicReadAccess()); + $this->assertFalse($result->getACL()->getPublicWriteAccess()); + $this->assertEquals(1, count($query->find())); + $object->set('foo', 'bar'); + $object->save(); + $object->destroy(); } - $this->assertEquals(0, count($query->find())); - $object->set('foo', 'bar'); - - $object->save(); - $object->destroy(); - } - - public function testACLSharingWithAnotherUser() - { - $bob = new ParseUser(); - $bob->setUsername('bob'); - $bob->setPassword('pass'); - $bob->signUp(); - $bob->logOut(); - - $alice = new ParseUser(); - $alice->setUsername('alice'); - $alice->setPassword('wonderland'); - $alice->signUp(); - $object = ParseObject::create('Object'); - $acl = ParseACL::createACLWithUser($alice); - $acl->setUserReadAccess($bob, true); - $acl->setUserWriteAccess($bob, true); - $object->setACL($acl); - $object->save(); - $this->assertTrue($object->getACL()->getUserReadAccess($alice)); - $this->assertTrue($object->getACL()->getUserWriteAccess($alice)); - $this->assertTrue($object->getACL()->getUserReadAccess($bob)); - $this->assertTrue($object->getACL()->getUserWriteAccess($bob)); - $this->assertFalse($object->getACL()->getPublicReadAccess()); - $this->assertFalse($object->getACL()->getPublicWriteAccess()); - - ParseUser::logOut(); - - $query = new ParseQuery('Object'); - try { - $query->get($object->getObjectId()); - $this->fail('public should be unable to get'); - } catch (\Parse\ParseException $e) { + public function testACLSaveAllWithPermissions() + { + $alice = new ParseUser(); + $alice->setUsername('alice'); + $alice->setPassword('wonderland'); + $alice->signUp(); + $acl = ParseACL::createACLWithUser($alice); + $object1 = ParseObject::create('Object'); + $object1->setACL($acl); + $object1->save(); + $object2 = ParseObject::create('Object'); + $object2->setACL($acl); + $object2->save(); + + $this->assertTrue($object1->getACL()->getUserReadAccess($alice)); + $this->assertTrue($object1->getACL()->getUserWriteAccess($alice)); + $this->assertFalse($object1->getACL()->getPublicReadAccess()); + $this->assertFalse($object1->getACL()->getPublicWriteAccess()); + $this->assertTrue($object2->getACL()->getUserReadAccess($alice)); + $this->assertTrue($object2->getACL()->getUserWriteAccess($alice)); + $this->assertFalse($object2->getACL()->getPublicReadAccess()); + $this->assertFalse($object2->getACL()->getPublicWriteAccess()); + + $object1->set('foo', 'bar'); + $object2->set('foo', 'bar'); + ParseObject::saveAll([$object1, $object2]); + + $query = new ParseQuery('Object'); + $query->equalTo('foo', 'bar'); + $this->assertEquals(2, count($query->find())); } - $this->assertEquals(0, count($query->find())); - $object->set('foo', 'bar'); - try { - $object->save(); - $this->fail('update should fail with object not found'); - } catch (\Parse\ParseException $e) { + public function testACLModifyingAfterLoad() + { + $user = new ParseUser(); + $user->setUsername('alice'); + $user->setPassword('wonderland'); + $user->signUp(); + $object = ParseObject::create('Object'); + $acl = ParseACL::createACLWithUser($user); + $object->setACL($acl); + $object->save(); + $this->assertTrue($object->getACL()->getUserReadAccess($user)); + $this->assertTrue($object->getACL()->getUserWriteAccess($user)); + $this->assertFalse($object->getACL()->getPublicReadAccess()); + $this->assertFalse($object->getACL()->getPublicWriteAccess()); + $query = new ParseQuery('Object'); + $objectAgain = $query->get($object->getObjectId()); + $objectAgain->getACL()->setPublicReadAccess(true); + + $this->assertTrue($objectAgain->getACL()->getUserReadAccess($user)); + $this->assertTrue($objectAgain->getACL()->getUserWriteAccess($user)); + $this->assertTrue($objectAgain->getACL()->getPublicReadAccess()); + $this->assertFalse($objectAgain->getACL()->getPublicWriteAccess()); } - try { - $object->destroy(); - $this->fail('delete should fail with object not found'); - } catch (\Parse\ParseException $e) { + public function testACLRequiresObjectId() + { + $acl = new ParseACL(); + try { + $acl->setReadAccess(null, true); + $this->fail('Exception should have thrown'); + } catch (Exception $e) { + } + try { + $acl->getReadAccess(null); + $this->fail('Exception should have thrown'); + } catch (Exception $e) { + } + try { + $acl->setWriteAccess(null, true); + $this->fail('Exception should have thrown'); + } catch (Exception $e) { + } + try { + $acl->getWriteAccess(null); + $this->fail('Exception should have thrown'); + } catch (Exception $e) { + } + + $user = new ParseUser(); + try { + $acl->setReadAccess($user, true); + $this->fail('Exception should have thrown'); + } catch (Exception $e) { + } + try { + $acl->getReadAccess($user); + $this->fail('Exception should have thrown'); + } catch (Exception $e) { + } + try { + $acl->setWriteAccess($user, true); + $this->fail('Exception should have thrown'); + } catch (Exception $e) { + } + try { + $acl->getWriteAccess($user); + $this->fail('Exception should have thrown'); + } catch (Exception $e) { + } } - ParseUser::logIn('bob', 'pass'); - - $query = new ParseQuery('Object'); - $result = $query->get($object->getObjectId()); - $this->assertNotNull($result); - $this->assertTrue($result->getACL()->getUserReadAccess($alice)); - $this->assertTrue($result->getACL()->getUserWriteAccess($alice)); - $this->assertTrue($result->getACL()->getUserReadAccess($bob)); - $this->assertTrue($result->getACL()->getUserWriteAccess($bob)); - $this->assertFalse($result->getACL()->getPublicReadAccess()); - $this->assertFalse($result->getACL()->getPublicWriteAccess()); - $this->assertEquals(1, count($query->find())); - $object->set('foo', 'bar'); - $object->save(); - $object->destroy(); - - } - - public function testACLSaveAllWithPermissions() - { - $alice = new ParseUser(); - $alice->setUsername('alice'); - $alice->setPassword('wonderland'); - $alice->signUp(); - $acl = ParseACL::createACLWithUser($alice); - $object1 = ParseObject::create('Object'); - $object1->setACL($acl); - $object1->save(); - $object2 = ParseObject::create('Object'); - $object2->setACL($acl); - $object2->save(); - - $this->assertTrue($object1->getACL()->getUserReadAccess($alice)); - $this->assertTrue($object1->getACL()->getUserWriteAccess($alice)); - $this->assertFalse($object1->getACL()->getPublicReadAccess()); - $this->assertFalse($object1->getACL()->getPublicWriteAccess()); - $this->assertTrue($object2->getACL()->getUserReadAccess($alice)); - $this->assertTrue($object2->getACL()->getUserWriteAccess($alice)); - $this->assertFalse($object2->getACL()->getPublicReadAccess()); - $this->assertFalse($object2->getACL()->getPublicWriteAccess()); - - $object1->set('foo', 'bar'); - $object2->set('foo', 'bar'); - ParseObject::saveAll([$object1, $object2]); - - $query = new ParseQuery('Object'); - $query->equalTo('foo', 'bar'); - $this->assertEquals(2, count($query->find())); - - } - - public function testACLModifyingAfterLoad() - { - $user = new ParseUser(); - $user->setUsername('alice'); - $user->setPassword('wonderland'); - $user->signUp(); - $object = ParseObject::create('Object'); - $acl = ParseACL::createACLWithUser($user); - $object->setACL($acl); - $object->save(); - $this->assertTrue($object->getACL()->getUserReadAccess($user)); - $this->assertTrue($object->getACL()->getUserWriteAccess($user)); - $this->assertFalse($object->getACL()->getPublicReadAccess()); - $this->assertFalse($object->getACL()->getPublicWriteAccess()); - $query = new ParseQuery('Object'); - $objectAgain = $query->get($object->getObjectId()); - $objectAgain->getACL()->setPublicReadAccess(true); - - $this->assertTrue($objectAgain->getACL()->getUserReadAccess($user)); - $this->assertTrue($objectAgain->getACL()->getUserWriteAccess($user)); - $this->assertTrue($objectAgain->getACL()->getPublicReadAccess()); - $this->assertFalse($objectAgain->getACL()->getPublicWriteAccess()); - - - } - - public function testACLRequiresObjectId() - { - $acl = new ParseACL(); - try { - $acl->setReadAccess(null, true); - $this->fail('Exception should have thrown'); - } catch (Exception $e) { - } - try { - $acl->getReadAccess(null); - $this->fail('Exception should have thrown'); - } catch (Exception $e) { - } - try { - $acl->setWriteAccess(null, true); - $this->fail('Exception should have thrown'); - } catch (Exception $e) { - } - try { - $acl->getWriteAccess(null); - $this->fail('Exception should have thrown'); - } catch (Exception $e) { + public function testIncludedObjectsGetACLs() + { + ParseTestHelper::clearClass("Test"); + ParseTestHelper::clearClass("Related"); + $object = ParseObject::create('Test'); + $acl = new ParseACL(); + $acl->setPublicReadAccess(true); + $object->setACL($acl); + $object->save(); + $this->assertTrue($object->getACL()->getPublicReadAccess()); + + $related = ParseObject::create('Related'); + $related->set('test', $object); + $related->save(); + + $query = new ParseQuery('Related'); + $query->includeKey('test'); + $objectAgain = $query->first()->get('test'); + + $this->assertTrue($objectAgain->getACL()->getPublicReadAccess()); + $this->assertFalse($objectAgain->getACL()->getPublicWriteAccess()); } - $user = new ParseUser(); - try { - $acl->setReadAccess($user, true); - $this->fail('Exception should have thrown'); - } catch (Exception $e) { - } - try { - $acl->getReadAccess($user); - $this->fail('Exception should have thrown'); - } catch (Exception $e) { - } - try { - $acl->setWriteAccess($user, true); - $this->fail('Exception should have thrown'); - } catch (Exception $e) { - } - try { - $acl->getWriteAccess($user); - $this->fail('Exception should have thrown'); - } catch (Exception $e) { + public function testIncludedObjectsGetACLWithDefaultACL() + { + ParseTestHelper::clearClass("Test"); + ParseTestHelper::clearClass("Related"); + $defaultACL = new ParseACL(); + $defaultACL->setPublicReadAccess(true); + $defaultACL->setPublicWriteAccess(true); + ParseACL::setDefaultACL($defaultACL, true); + + $object = ParseObject::create('Test'); + $acl = new ParseACL(); + $acl->setPublicReadAccess(true); + $object->setACL($acl); + $object->save(); + + $this->assertTrue($object->getACL()->getPublicReadAccess()); + $related = ParseObject::create('Related'); + $related->set('test', $object); + $related->save(); + + $query = new ParseQuery('Related'); + $query->includeKey('test'); + $objectAgain = $query->first()->get('test'); + $this->assertTrue($objectAgain->getACL()->getPublicReadAccess()); + $this->assertFalse($objectAgain->getACL()->getPublicWriteAccess()); } - - } - - public function testIncludedObjectsGetACLs() - { - ParseTestHelper::clearClass("Test"); - ParseTestHelper::clearClass("Related"); - $object = ParseObject::create('Test'); - $acl = new ParseACL(); - $acl->setPublicReadAccess(true); - $object->setACL($acl); - $object->save(); - $this->assertTrue($object->getACL()->getPublicReadAccess()); - - $related = ParseObject::create('Related'); - $related->set('test', $object); - $related->save(); - - $query = new ParseQuery('Related'); - $query->includeKey('test'); - $objectAgain = $query->first()->get('test'); - - $this->assertTrue($objectAgain->getACL()->getPublicReadAccess()); - $this->assertFalse($objectAgain->getACL()->getPublicWriteAccess()); - } - - public function testIncludedObjectsGetACLWithDefaultACL() - { - ParseTestHelper::clearClass("Test"); - ParseTestHelper::clearClass("Related"); - $defaultACL = new ParseACL(); - $defaultACL->setPublicReadAccess(true); - $defaultACL->setPublicWriteAccess(true); - ParseACL::setDefaultACL($defaultACL, true); - - $object = ParseObject::create('Test'); - $acl = new ParseACL(); - $acl->setPublicReadAccess(true); - $object->setACL($acl); - $object->save(); - - $this->assertTrue($object->getACL()->getPublicReadAccess()); - $related = ParseObject::create('Related'); - $related->set('test', $object); - $related->save(); - - $query = new ParseQuery('Related'); - $query->includeKey('test'); - $objectAgain = $query->first()->get('test'); - $this->assertTrue($objectAgain->getACL()->getPublicReadAccess()); - $this->assertFalse($objectAgain->getACL()->getPublicWriteAccess()); - - } - } diff --git a/tests/ParseAnalyticsTest.php b/tests/ParseAnalyticsTest.php index 877cca3c..309f7dc1 100644 --- a/tests/ParseAnalyticsTest.php +++ b/tests/ParseAnalyticsTest.php @@ -1,6 +1,5 @@ assertEquals($expectedJSON, $json); - ParseAnalytics::track($event, $params ?: array()); - } + $json = ParseAnalytics::_toSaveJSON($params ?: []); + $this->assertEquals($expectedJSON, $json); + ParseAnalytics::track($event, $params ?: []); + } - public function testTrackEvent() - { - $expected = '{"dimensions":{}}'; - $this->assertAnalyticsValidation('testTrackEvent', null, $expected); - } + public function testTrackEvent() + { + $expected = '{"dimensions":{}}'; + $this->assertAnalyticsValidation('testTrackEvent', null, $expected); + } - public function testFailsOnEventName1() - { - $this->setExpectedException( + public function testFailsOnEventName1() + { + $this->setExpectedException( 'Exception', 'A name for the custom event must be provided.' ); - ParseAnalytics::track(''); - } + ParseAnalytics::track(''); + } - public function testFailsOnEventName2() - { - $this->setExpectedException( + public function testFailsOnEventName2() + { + $this->setExpectedException( 'Exception', 'A name for the custom event must be provided.' ); - ParseAnalytics::track(' '); - } + ParseAnalytics::track(' '); + } - public function testFailsOnEventName3() - { - $this->setExpectedException( + public function testFailsOnEventName3() + { + $this->setExpectedException( 'Exception', 'A name for the custom event must be provided.' ); - ParseAnalytics::track(" \n"); - } + ParseAnalytics::track(" \n"); + } - public function testTrackEventDimensions() - { - $expected = '{"dimensions":{"foo":"bar","bar":"baz"}}'; - $params = array( - 'foo' => 'bar', - 'bar' => 'baz' - ); - $this->assertAnalyticsValidation('testDimensions', $params, $expected); - - $date = date(DATE_RFC3339); - $expected = '{"dimensions":{"foo":"bar","bar":"baz","someDate":"' . - $date . '"}}'; - $params = array( + public function testTrackEventDimensions() + { + $expected = '{"dimensions":{"foo":"bar","bar":"baz"}}'; + $params = [ 'foo' => 'bar', 'bar' => 'baz', - 'someDate' => $date - ); - $this->assertAnalyticsValidation('testDate', $params, $expected); - } + ]; + $this->assertAnalyticsValidation('testDimensions', $params, $expected); -} \ No newline at end of file + $date = date(DATE_RFC3339); + $expected = '{"dimensions":{"foo":"bar","bar":"baz","someDate":"'. + $date.'"}}'; + $params = [ + 'foo' => 'bar', + 'bar' => 'baz', + 'someDate' => $date, + ]; + $this->assertAnalyticsValidation('testDate', $params, $expected); + } +} diff --git a/tests/ParseBytesTest.php b/tests/ParseBytesTest.php index 00975754..88773d8f 100644 --- a/tests/ParseBytesTest.php +++ b/tests/ParseBytesTest.php @@ -1,51 +1,50 @@ set("byteColumn", $bytes); - $obj->save(); - - $query = new ParseQuery("BytesObject"); - $objAgain = $query->get($obj->getObjectId()); - $this->assertEquals("Fosco", $objAgain->get("byteColumn")); - } - - public function testParseBytesFromBase64Data() - { - $obj = ParseObject::create("BytesObject"); - $bytes = ParseBytes::createFromBase64Data("R3JhbnRsYW5k"); - $obj->set("byteColumn", $bytes); - $obj->save(); - - $query = new ParseQuery("BytesObject"); - $objAgain = $query->get($obj->getObjectId()); - $this->assertEquals("Grantland", $objAgain->get("byteColumn")); + ParseTestHelper::setUp(); } -} \ No newline at end of file + public function setUp() + { + ParseTestHelper::clearClass("BytesObject"); + } + + public function tearDown() + { + ParseTestHelper::clearClass("BytesObject"); + ParseTestHelper::tearDown(); + } + + public function testParseBytesFromArray() + { + $obj = ParseObject::create("BytesObject"); + $bytes = ParseBytes::createFromByteArray([70, 111, 115, 99, 111]); + $obj->set("byteColumn", $bytes); + $obj->save(); + + $query = new ParseQuery("BytesObject"); + $objAgain = $query->get($obj->getObjectId()); + $this->assertEquals("Fosco", $objAgain->get("byteColumn")); + } + + public function testParseBytesFromBase64Data() + { + $obj = ParseObject::create("BytesObject"); + $bytes = ParseBytes::createFromBase64Data("R3JhbnRsYW5k"); + $obj->set("byteColumn", $bytes); + $obj->save(); + + $query = new ParseQuery("BytesObject"); + $objAgain = $query->get($obj->getObjectId()); + $this->assertEquals("Grantland", $objAgain->get("byteColumn")); + } +} diff --git a/tests/ParseCloudTest.php b/tests/ParseCloudTest.php index 04dc573e..0ce9b824 100644 --- a/tests/ParseCloudTest.php +++ b/tests/ParseCloudTest.php @@ -1,41 +1,39 @@ set('name', 'Zanzibar'); - $obj->save(); - $params = array('key1' => $obj); - $this->setExpectedException('\Exception', 'ParseObjects not allowed'); - ParseCloud::run('foo', $params); - } - - public function testFunctionsWithGeoPointParamsDoNotThrow() - { - $params = array('key1' => new ParseGeoPoint(50, 50)); - $this->setExpectedException('Parse\ParseException', 'function not found'); - ParseCloud::run('unknown_function', $params); - } - - public function testUnknownFunctionFailure() - { - $params = array('key1' => 'value1'); - $this->setExpectedException('Parse\ParseException','function not found'); - ParseCloud::run('unknown_function', $params); + ParseTestHelper::setUp(); } -} \ No newline at end of file + public function testFunctionsWithObjectParamsFails() + { + $obj = ParseObject::create('SomeClass'); + $obj->set('name', 'Zanzibar'); + $obj->save(); + $params = ['key1' => $obj]; + $this->setExpectedException('\Exception', 'ParseObjects not allowed'); + ParseCloud::run('foo', $params); + } + + public function testFunctionsWithGeoPointParamsDoNotThrow() + { + $params = ['key1' => new ParseGeoPoint(50, 50)]; + $this->setExpectedException('Parse\ParseException', 'function not found'); + ParseCloud::run('unknown_function', $params); + } + + public function testUnknownFunctionFailure() + { + $params = ['key1' => 'value1']; + $this->setExpectedException('Parse\ParseException', 'function not found'); + ParseCloud::run('unknown_function', $params); + } +} diff --git a/tests/ParseConfigTest.php b/tests/ParseConfigTest.php index b48066c2..8b6939c0 100644 --- a/tests/ParseConfigTest.php +++ b/tests/ParseConfigTest.php @@ -4,20 +4,20 @@ require_once 'ParseTestHelper.php'; -class ParseConfigMock extends ParseConfig { - public function __construct() { - $this->setConfig(["foo" => "bar", "some" => 1]); +class ParseConfigMock extends ParseConfig +{ + public function __construct() + { + $this->setConfig(["foo" => "bar", "some" => 1]); } } class ParseConfigTest extends PHPUnit_Framework_TestCase { - public function testGetConfig() { - $config = new ParseConfigMock(); - $this->assertEquals("bar", $config->get("foo")); - $this->assertEquals(1, $config->get("some")); + $config = new ParseConfigMock(); + $this->assertEquals("bar", $config->get("foo")); + $this->assertEquals(1, $config->get("some")); } - -} \ No newline at end of file +} diff --git a/tests/ParseFileTest.php b/tests/ParseFileTest.php index 00869c0f..9532459a 100644 --- a/tests/ParseFileTest.php +++ b/tests/ParseFileTest.php @@ -6,137 +6,136 @@ require_once 'ParseTestHelper.php'; -class ParseFileTest extends \PHPUnit_Framework_TestCase { - +class ParseFileTest extends \PHPUnit_Framework_TestCase +{ public static function setUpBeforeClass() { - ParseTestHelper::setUp(); - } - - public function tearDown() - { - ParseTestHelper::tearDown(); - ParseTestHelper::clearClass("TestFileObject"); + ParseTestHelper::setUp(); } - public function testParseFileFactories() - { - $file = ParseFile::_createFromServer("hi.txt", "http://"); - $file2 = ParseFile::createFromData("hello", "hi.txt"); - $file3 = ParseFile::createFromFile("ParseFileTest.php", + public function tearDown() + { + ParseTestHelper::tearDown(); + ParseTestHelper::clearClass("TestFileObject"); + } + + public function testParseFileFactories() + { + $file = ParseFile::_createFromServer("hi.txt", "http://"); + $file2 = ParseFile::createFromData("hello", "hi.txt"); + $file3 = ParseFile::createFromFile("ParseFileTest.php", "file.php"); - $this->assertEquals("http://", $file->getURL()); - $this->assertEquals("hi.txt", $file->getName()); - $this->assertEquals("hello", $file2->getData()); - $this->assertEquals("hi.txt", $file2->getName()); - $this->assertTrue( + $this->assertEquals("http://", $file->getURL()); + $this->assertEquals("hi.txt", $file->getName()); + $this->assertEquals("hello", $file2->getData()); + $this->assertEquals("hi.txt", $file2->getName()); + $this->assertTrue( strpos( $file3->getData(), 'i am looking for myself' ) !== false ); - } + } - public function testParseFileUpload() - { - $file = ParseFile::createFromData("Fosco", "test.txt"); - $file->save(); - $this->assertTrue( + public function testParseFileUpload() + { + $file = ParseFile::createFromData("Fosco", "test.txt"); + $file->save(); + $this->assertTrue( strpos($file->getURL(), 'http') !== false ); - $this->assertNotEquals("test.txt", $file->getName()); - } - - public function testParseFileDownload() - { - $file = ParseFile::_createFromServer("index.html", "http://example.com"); - $data = $file->getData(); - $this->assertTrue( + $this->assertNotEquals("test.txt", $file->getName()); + } + + public function testParseFileDownload() + { + $file = ParseFile::_createFromServer("index.html", "http://example.com"); + $data = $file->getData(); + $this->assertTrue( strpos($data, 'Example Domain') !== false ); - } - - public function testParseFileRoundTrip() - { - $contents = "What would Bryan do?"; - $file = ParseFile::createFromData($contents, "test.txt"); - $this->assertEquals($contents, $file->getData()); - $file->save(); - - $fileAgain = ParseFile::_createFromServer($file->getName(), $file->getURL()); - $this->assertEquals($contents, $fileAgain->getData()); - $fileAgain->save(); - $this->assertEquals($file->getURL(), $fileAgain->getURL()); - } - - public function testParseFileTypes() - { - $contents = "a fractal of rad design"; - $file = ParseFile::createFromData($contents, "noextension"); - $file2 = ParseFile::createFromData($contents, "photo.png", "text/plain"); - $file3 = ParseFile::createFromData($contents, "photo.png"); - $file->save(); - $file2->save(); - $file3->save(); - - $fileAgain = ParseFile::_createFromServer($file->getName(), $file->getURL()); - $file2Again = ParseFile::_createFromServer($file2->getName(), $file2->getURL()); - $file3Again = ParseFile::_createFromServer($file3->getName(), $file3->getURL()); - - $this->assertEquals($contents, $fileAgain->getData()); - $this->assertEquals($contents, $file2Again->getData()); - $this->assertEquals($contents, $file3Again->getData()); - - $this->assertEquals("unknown/unknown", $fileAgain->getMimeType()); - $this->assertEquals("text/plain", $file2Again->getMimeType()); - $this->assertEquals("image/png", $file3Again->getMimeType()); - } - - public function testFileOnObject() - { - $contents = "irrelephant"; - $file = ParseFile::createFromData($contents, "php.txt"); - $file->save(); - - $obj = ParseObject::create("TestFileObject"); - $obj->set("file", $file); - $obj->save(); - - $query = new ParseQuery("TestFileObject"); - $objAgain = $query->get($obj->getObjectId()); - $fileAgain = $objAgain->get("file"); - $contentsAgain = $fileAgain->getData(); - $this->assertEquals($contents, $contentsAgain); - } - - public function testUnsavedFileOnObjectSave() - { - $contents = "remember"; - $file = ParseFile::createFromData($contents, "bones.txt"); - $obj = ParseObject::create("TestFileObject"); - $obj->set("file", $file); - $obj->save(); - - $query = new ParseQuery("TestFileObject"); - $objAgain = $query->get($obj->getObjectId()); - $fileAgain = $objAgain->get("file"); - $contentsAgain = $fileAgain->getData(); - $this->assertEquals($contents, $contentsAgain); - } - - public function testFileDelete() - { - $data = "c-c-c-combo breaker"; - $name = "php.txt"; - $file = ParseFile::createFromData($data, $name); - $file->save(); - $url = $file->getURL(); - $fileAgain = ParseFile::_createFromServer($name, $url); - $contents = $fileAgain->getData(); - $this->assertEquals($data, $contents); - $file->delete(); - $fileAgain = ParseFile::_createFromServer($name, $url); - $this->setExpectedException('Parse\ParseException', 'Download failed'); - $contents = $fileAgain->getData(); - } - + } + + public function testParseFileRoundTrip() + { + $contents = "What would Bryan do?"; + $file = ParseFile::createFromData($contents, "test.txt"); + $this->assertEquals($contents, $file->getData()); + $file->save(); + + $fileAgain = ParseFile::_createFromServer($file->getName(), $file->getURL()); + $this->assertEquals($contents, $fileAgain->getData()); + $fileAgain->save(); + $this->assertEquals($file->getURL(), $fileAgain->getURL()); + } + + public function testParseFileTypes() + { + $contents = "a fractal of rad design"; + $file = ParseFile::createFromData($contents, "noextension"); + $file2 = ParseFile::createFromData($contents, "photo.png", "text/plain"); + $file3 = ParseFile::createFromData($contents, "photo.png"); + $file->save(); + $file2->save(); + $file3->save(); + + $fileAgain = ParseFile::_createFromServer($file->getName(), $file->getURL()); + $file2Again = ParseFile::_createFromServer($file2->getName(), $file2->getURL()); + $file3Again = ParseFile::_createFromServer($file3->getName(), $file3->getURL()); + + $this->assertEquals($contents, $fileAgain->getData()); + $this->assertEquals($contents, $file2Again->getData()); + $this->assertEquals($contents, $file3Again->getData()); + + $this->assertEquals("unknown/unknown", $fileAgain->getMimeType()); + $this->assertEquals("text/plain", $file2Again->getMimeType()); + $this->assertEquals("image/png", $file3Again->getMimeType()); + } + + public function testFileOnObject() + { + $contents = "irrelephant"; + $file = ParseFile::createFromData($contents, "php.txt"); + $file->save(); + + $obj = ParseObject::create("TestFileObject"); + $obj->set("file", $file); + $obj->save(); + + $query = new ParseQuery("TestFileObject"); + $objAgain = $query->get($obj->getObjectId()); + $fileAgain = $objAgain->get("file"); + $contentsAgain = $fileAgain->getData(); + $this->assertEquals($contents, $contentsAgain); + } + + public function testUnsavedFileOnObjectSave() + { + $contents = "remember"; + $file = ParseFile::createFromData($contents, "bones.txt"); + $obj = ParseObject::create("TestFileObject"); + $obj->set("file", $file); + $obj->save(); + + $query = new ParseQuery("TestFileObject"); + $objAgain = $query->get($obj->getObjectId()); + $fileAgain = $objAgain->get("file"); + $contentsAgain = $fileAgain->getData(); + $this->assertEquals($contents, $contentsAgain); + } + + public function testFileDelete() + { + $data = "c-c-c-combo breaker"; + $name = "php.txt"; + $file = ParseFile::createFromData($data, $name); + $file->save(); + $url = $file->getURL(); + $fileAgain = ParseFile::_createFromServer($name, $url); + $contents = $fileAgain->getData(); + $this->assertEquals($data, $contents); + $file->delete(); + $fileAgain = ParseFile::_createFromServer($name, $url); + $this->setExpectedException('Parse\ParseException', 'Download failed'); + $contents = $fileAgain->getData(); + } } diff --git a/tests/ParseGeoBoxTest.php b/tests/ParseGeoBoxTest.php index cc79d1e9..93622d39 100644 --- a/tests/ParseGeoBoxTest.php +++ b/tests/ParseGeoBoxTest.php @@ -1,156 +1,153 @@ set('location', $caltrainStationLocation); - $caltrainStation->set('name', 'caltrain'); - $caltrainStation->save(); + public function testGeoBox() + { + $caltrainStationLocation = new ParseGeoPoint(37.776346, -122.394218); + $caltrainStation = ParseObject::create('TestObject'); + $caltrainStation->set('location', $caltrainStationLocation); + $caltrainStation->set('name', 'caltrain'); + $caltrainStation->save(); - $santaClaraLocation = new ParseGeoPoint(37.325635, -121.945753); - $santaClara = new ParseObject('TestObject'); + $santaClaraLocation = new ParseGeoPoint(37.325635, -121.945753); + $santaClara = new ParseObject('TestObject'); - $santaClara->set('location', $santaClaraLocation); - $santaClara->set('name', 'santa clara'); - $santaClara->save(); + $santaClara->set('location', $santaClaraLocation); + $santaClara->set('name', 'santa clara'); + $santaClara->save(); - $southwestOfSF = new ParseGeoPoint(37.708813, -122.526398); - $northeastOfSF = new ParseGeoPoint(37.822802, -122.373962); + $southwestOfSF = new ParseGeoPoint(37.708813, -122.526398); + $northeastOfSF = new ParseGeoPoint(37.822802, -122.373962); // Try a correct query $query = new ParseQuery('TestObject'); - $query->withinGeoBox('location', $southwestOfSF, $northeastOfSF); - $objectsInSF = $query->find(); - $this->assertEquals(1, count($objectsInSF)); - $this->assertEquals('caltrain', $objectsInSF[0]->get('name')); + $query->withinGeoBox('location', $southwestOfSF, $northeastOfSF); + $objectsInSF = $query->find(); + $this->assertEquals(1, count($objectsInSF)); + $this->assertEquals('caltrain', $objectsInSF[0]->get('name')); // Switch order of args, should fail because it crosses the dateline $query = new ParseQuery('TestObject'); - $query->withinGeoBox('location', $northeastOfSF, $southwestOfSF); - try { - $results = $query->find(); - $this->assertTrue(FALSE, 'Query should fail because it crosses dateline'); - } catch (ParseException $e) { - } + $query->withinGeoBox('location', $northeastOfSF, $southwestOfSF); + try { + $results = $query->find(); + $this->assertTrue(false, 'Query should fail because it crosses dateline'); + } catch (ParseException $e) { + } - $northwestOfSF = new ParseGeoPoint(37.822802, -122.526398); - $southeastOfSF = new ParseGeoPoint(37.708813, -122.373962); + $northwestOfSF = new ParseGeoPoint(37.822802, -122.526398); + $southeastOfSF = new ParseGeoPoint(37.708813, -122.373962); // Switch just longitude, should fail because it crosses the dateline $query = new ParseQuery('TestObject'); - $query->withinGeoBox('location', $southeastOfSF, $northwestOfSF); - try { - $query->find(); - $this->assertTrue(FALSE, 'Query should fail because it crosses dateline'); - } catch (ParseException $e) { - } + $query->withinGeoBox('location', $southeastOfSF, $northwestOfSF); + try { + $query->find(); + $this->assertTrue(false, 'Query should fail because it crosses dateline'); + } catch (ParseException $e) { + } // Switch just the latitude, should fail because it doesnt make sense $query = new ParseQuery('TestObject'); - $query->withinGeoBox('location', $northwestOfSF, $southeastOfSF); - try { - $query->find(); - $this->assertTrue(FALSE, 'Query should fail because it makes no sense'); - } catch (ParseException $e) { + $query->withinGeoBox('location', $northwestOfSF, $southeastOfSF); + try { + $query->find(); + $this->assertTrue(false, 'Query should fail because it makes no sense'); + } catch (ParseException $e) { + } } - } - public function testGeoBoxSmallNearDateLine() - { - $nearWestOfDateLine = new ParseGeoPoint(0, 175); - $nearWestObject = ParseObject::create('TestObject'); - - $nearWestObject->set('location', $nearWestOfDateLine); - $nearWestObject->set('name', 'near west'); - $nearWestObject->set('order', 1); - $nearWestObject->save(); - - $nearEastOfDateLine = new ParseGeoPoint(0, -175); - $nearEastObject = ParseObject::create('TestObject'); - - $nearEastObject->set('location', $nearEastOfDateLine); - $nearEastObject->set('name', 'near east'); - $nearEastObject->set('order', 2); - $nearEastObject->save(); - - $farWestOfDateLine = new ParseGeoPoint(0, 165); - $farWestObject = ParseObject::create('TestObject'); - - $farWestObject->set('location', $farWestOfDateLine); - $farWestObject->set('name', 'far west'); - $farWestObject->set('order', 3); - $farWestObject->save(); - - $farEastOfDateLine = new ParseGeoPoint(0, -165); - $farEastObject = ParseObject::create('TestObject'); - - $farEastObject->set('location', $farEastOfDateLine); - $farEastObject->set('name', 'far east'); - $farEastObject->set('order', 4); - $farEastObject->save(); - - $southwestOfDateLine = new ParseGeoPoint(-10, 170); - $northeastOfDateLine = new ParseGeoPoint(10, -170); - - $query = new ParseQuery('TestObject'); - $query->withinGeoBox('location', $southwestOfDateLine, $northeastOfDateLine); - $query->ascending('order'); - try { - $query->find(); - $this->assertTrue(FALSE, 'Query should fail for crossing the date line.'); - } catch (ParseException $e) { + public function testGeoBoxSmallNearDateLine() + { + $nearWestOfDateLine = new ParseGeoPoint(0, 175); + $nearWestObject = ParseObject::create('TestObject'); + + $nearWestObject->set('location', $nearWestOfDateLine); + $nearWestObject->set('name', 'near west'); + $nearWestObject->set('order', 1); + $nearWestObject->save(); + + $nearEastOfDateLine = new ParseGeoPoint(0, -175); + $nearEastObject = ParseObject::create('TestObject'); + + $nearEastObject->set('location', $nearEastOfDateLine); + $nearEastObject->set('name', 'near east'); + $nearEastObject->set('order', 2); + $nearEastObject->save(); + + $farWestOfDateLine = new ParseGeoPoint(0, 165); + $farWestObject = ParseObject::create('TestObject'); + + $farWestObject->set('location', $farWestOfDateLine); + $farWestObject->set('name', 'far west'); + $farWestObject->set('order', 3); + $farWestObject->save(); + + $farEastOfDateLine = new ParseGeoPoint(0, -165); + $farEastObject = ParseObject::create('TestObject'); + + $farEastObject->set('location', $farEastOfDateLine); + $farEastObject->set('name', 'far east'); + $farEastObject->set('order', 4); + $farEastObject->save(); + + $southwestOfDateLine = new ParseGeoPoint(-10, 170); + $northeastOfDateLine = new ParseGeoPoint(10, -170); + + $query = new ParseQuery('TestObject'); + $query->withinGeoBox('location', $southwestOfDateLine, $northeastOfDateLine); + $query->ascending('order'); + try { + $query->find(); + $this->assertTrue(false, 'Query should fail for crossing the date line.'); + } catch (ParseException $e) { + } } - } - public function testGeoBoxTooLarge() - { - $centerPoint = new ParseGeoPoint(0, 0); - $center = ParseObject::create('TestObject'); + public function testGeoBoxTooLarge() + { + $centerPoint = new ParseGeoPoint(0, 0); + $center = ParseObject::create('TestObject'); - $center->set('location', $centerPoint); - $center->save(); + $center->set('location', $centerPoint); + $center->save(); - $southwest = new ParseGeoPoint(-89, -179); - $northeast = new ParseGeoPoint(89, 179); + $southwest = new ParseGeoPoint(-89, -179); + $northeast = new ParseGeoPoint(89, 179); // This is an interesting test case because mongo can actually handle this // kind of query, but // if one actually happens, it's probably that the developer switches the // two points. $query = new ParseQuery('TestObject'); - $query->withinGeoBox('location', $southwest, $northeast); - try { - $query->find(); - $this->assertTrue(FALSE, 'Query should fail for being too large.'); - } catch (ParseException $e) { + $query->withinGeoBox('location', $southwest, $northeast); + try { + $query->find(); + $this->assertTrue(false, 'Query should fail for being too large.'); + } catch (ParseException $e) { + } } - } } - diff --git a/tests/ParseGeoPointTest.php b/tests/ParseGeoPointTest.php index e68f488b..04be1421 100644 --- a/tests/ParseGeoPointTest.php +++ b/tests/ParseGeoPointTest.php @@ -1,147 +1,144 @@ set('location', $point); + public function testGeoPointBase() + { + $point = new ParseGeoPoint(44.0, -11.0); + $obj = ParseObject::create('TestObject'); + $obj->set('location', $point); - $obj->set('name', 'Ferndale'); - $obj->save(); + $obj->set('name', 'Ferndale'); + $obj->save(); // Non geo query $query = new ParseQuery('TestObject'); - $query->equalTo('name', 'Ferndale'); - $results = $query->find(); - $this->assertEquals(1, count($results)); + $query->equalTo('name', 'Ferndale'); + $results = $query->find(); + $this->assertEquals(1, count($results)); // Round trip encoding $actualPoint = $results[0]->get('location'); - $this->assertEquals(44.0, $actualPoint->getLatitude(), '', 0.0001); - $this->assertEquals(-11.0, $actualPoint->getLongitude(), '', 0.0001); + $this->assertEquals(44.0, $actualPoint->getLatitude(), '', 0.0001); + $this->assertEquals(-11.0, $actualPoint->getLongitude(), '', 0.0001); // nearsphere $point->setLatitude(66.0); - $query = new ParseQuery('TestObject'); - $query->near('location', $point); - $results = $query->find(); - $this->assertEquals(1, count($results)); - } - - public function testGeoLine() - { - for ($i = 0; $i < 10; ++$i) { - $obj = ParseObject::create('TestObject'); - $point = new ParseGeoPoint($i * 4.0 - 12.0, $i * 3.2 - 11.0); - $obj->set('location', $point); - $obj->set('construct', 'line'); - $obj->set('seq', $i); - $obj->save(); + $query = new ParseQuery('TestObject'); + $query->near('location', $point); + $results = $query->find(); + $this->assertEquals(1, count($results)); } - $query = new ParseQuery('TestObject'); - $point = new ParseGeoPoint(24.0, 19.0); - $query->equalTo('construct', 'line'); - $query->withinMiles('location', $point, 10000); - $results = $query->find(); - $this->assertEquals(10, count($results)); - $this->assertEquals(9, $results[0]->get('seq')); - $this->assertEquals(6, $results[3]->get('seq')); - } - - public function testGeoMaxDistance() - { - for ($i = 0; $i < 3; ++$i) { - $obj = ParseObject::create('TestObject'); - $point = new ParseGeoPoint(0.0, $i * 45.0); - $obj->set('location', $point); - $obj->set('id', $i); - $obj->save(); + public function testGeoLine() + { + for ($i = 0; $i < 10; ++$i) { + $obj = ParseObject::create('TestObject'); + $point = new ParseGeoPoint($i * 4.0 - 12.0, $i * 3.2 - 11.0); + $obj->set('location', $point); + $obj->set('construct', 'line'); + $obj->set('seq', $i); + $obj->save(); + } + + $query = new ParseQuery('TestObject'); + $point = new ParseGeoPoint(24.0, 19.0); + $query->equalTo('construct', 'line'); + $query->withinMiles('location', $point, 10000); + $results = $query->find(); + $this->assertEquals(10, count($results)); + $this->assertEquals(9, $results[0]->get('seq')); + $this->assertEquals(6, $results[3]->get('seq')); } + public function testGeoMaxDistance() + { + for ($i = 0; $i < 3; ++$i) { + $obj = ParseObject::create('TestObject'); + $point = new ParseGeoPoint(0.0, $i * 45.0); + $obj->set('location', $point); + $obj->set('id', $i); + $obj->save(); + } + // baseline all $query = new ParseQuery('TestObject'); - $point = new ParseGeoPoint(1.0, -1.0); - $query->near('location', $point); - $results = $query->find(); - $this->assertEquals(3, count($results)); + $point = new ParseGeoPoint(1.0, -1.0); + $query->near('location', $point); + $results = $query->find(); + $this->assertEquals(3, count($results)); // all $query = new ParseQuery('TestObject'); - $query->withinRadians('location', $point, 3.14 * 2); - $results = $query->find(); - $this->assertEquals(3, count($results)); + $query->withinRadians('location', $point, 3.14 * 2); + $results = $query->find(); + $this->assertEquals(3, count($results)); // all $query = new ParseQuery('TestObject'); - $query->withinRadians('location', $point, 3.14); - $results = $query->find(); - $this->assertEquals(3, count($results)); + $query->withinRadians('location', $point, 3.14); + $results = $query->find(); + $this->assertEquals(3, count($results)); // 2 $query = new ParseQuery('TestObject'); - $query->withinRadians('location', $point, 3.14 * 0.5); - $results = $query->find(); - $this->assertEquals(2, count($results)); - $this->assertEquals(1, $results[1]->get('id')); + $query->withinRadians('location', $point, 3.14 * 0.5); + $results = $query->find(); + $this->assertEquals(2, count($results)); + $this->assertEquals(1, $results[1]->get('id')); // 1 $query = new ParseQuery('TestObject'); - $query->withinRadians('location', $point, 3.14 * 0.25); - $results = $query->find(); - $this->assertEquals(1, count($results)); - $this->assertEquals(0, $results[0]->get('id')); - - } + $query->withinRadians('location', $point, 3.14 * 0.25); + $results = $query->find(); + $this->assertEquals(1, count($results)); + $this->assertEquals(0, $results[0]->get('id')); + } - public function testGeoMaxDistanceWithUnits() - { - ParseTestHelper::clearClass("PlaceObject"); + public function testGeoMaxDistanceWithUnits() + { + ParseTestHelper::clearClass("PlaceObject"); // [SAC] 38.52 -121.50 Sacramento,CA $sacramento = new ParseGeoPoint(38.52, -121.50); - $obj = ParseObject::create('PlaceObject'); - $obj->set('location', $sacramento); - $obj->set('name', 'Sacramento'); - $obj->save(); + $obj = ParseObject::create('PlaceObject'); + $obj->set('location', $sacramento); + $obj->set('name', 'Sacramento'); + $obj->save(); // [HNL] 21.35 -157.93 Honolulu Int,HI $honolulu = new ParseGeoPoint(21.35, -157.93); - $obj = ParseObject::create('PlaceObject'); - $obj->set('location', $honolulu); - $obj->set('name', 'Honolulu'); - $obj->save(); + $obj = ParseObject::create('PlaceObject'); + $obj->set('location', $honolulu); + $obj->set('name', 'Honolulu'); + $obj->save(); // [51Q] 37.75 -122.68 San Francisco,CA $sanfran = new ParseGeoPoint(37.75, -122.68); - $obj = ParseObject::create('PlaceObject'); - $obj->set('location', $sanfran); - $obj->set('name', 'San Francisco'); - $obj->save(); + $obj = ParseObject::create('PlaceObject'); + $obj->set('location', $sanfran); + $obj->set('name', 'San Francisco'); + $obj->save(); // test point SFO $point = new ParseGeoPoint(37.6189722, -122.3748889); @@ -149,59 +146,59 @@ public function testGeoMaxDistanceWithUnits() // Kilometers // baseline all $query = new ParseQuery('PlaceObject'); - $query->near('location', $point); - $results = $query->find(); - $this->assertEquals(3, count($results)); + $query->near('location', $point); + $results = $query->find(); + $this->assertEquals(3, count($results)); // max with all $query = new ParseQuery('PlaceObject'); - $query->withinKilometers('location', $point, 4000.0); - $results = $query->find(); - $this->assertEquals(3, count($results)); + $query->withinKilometers('location', $point, 4000.0); + $results = $query->find(); + $this->assertEquals(3, count($results)); // drop hawaii $query = new ParseQuery('PlaceObject'); - $query->withinKilometers('location', $point, 3700.0); - $results = $query->find(); - $this->assertEquals(2, count($results)); + $query->withinKilometers('location', $point, 3700.0); + $results = $query->find(); + $this->assertEquals(2, count($results)); // drop sacramento $query = new ParseQuery('PlaceObject'); - $query->withinKilometers('location', $point, 100.0); - $results = $query->find(); - $this->assertEquals(1, count($results)); - $this->assertEquals('San Francisco', $results[0]->get('name')); + $query->withinKilometers('location', $point, 100.0); + $results = $query->find(); + $this->assertEquals(1, count($results)); + $this->assertEquals('San Francisco', $results[0]->get('name')); // drop SF $query = new ParseQuery('PlaceObject'); - $query->withinKilometers('location', $point, 10.0); - $results = $query->find(); - $this->assertEquals(0, count($results)); + $query->withinKilometers('location', $point, 10.0); + $results = $query->find(); + $this->assertEquals(0, count($results)); // Miles // max with all $query = new ParseQuery('PlaceObject'); - $query->withinMiles('location', $point, 2500.0); - $results = $query->find(); - $this->assertEquals(3, count($results)); + $query->withinMiles('location', $point, 2500.0); + $results = $query->find(); + $this->assertEquals(3, count($results)); // drop hawaii $query = new ParseQuery('PlaceObject'); - $query->withinMiles('location', $point, 2200.0); - $results = $query->find(); - $this->assertEquals(2, count($results)); + $query->withinMiles('location', $point, 2200.0); + $results = $query->find(); + $this->assertEquals(2, count($results)); // drop sacramento $query = new ParseQuery('PlaceObject'); - $query->withinMiles('location', $point, 75.0); - $results = $query->find(); - $this->assertEquals(1, count($results)); - $this->assertEquals('San Francisco', $results[0]->get('name')); + $query->withinMiles('location', $point, 75.0); + $results = $query->find(); + $this->assertEquals(1, count($results)); + $this->assertEquals('San Francisco', $results[0]->get('name')); // drop SF $query = new ParseQuery('PlaceObject'); - $query->withinMiles('location', $point, 10.0); - $results = $query->find(); - $this->assertEquals(0, count($results)); - } + $query->withinMiles('location', $point, 10.0); + $results = $query->find(); + $this->assertEquals(0, count($results)); + } } diff --git a/tests/ParseMemoryStorageTest.php b/tests/ParseMemoryStorageTest.php index 113ba3ac..9e6c4f5f 100644 --- a/tests/ParseMemoryStorageTest.php +++ b/tests/ParseMemoryStorageTest.php @@ -1,71 +1,67 @@ clear(); - } + public function tearDown() + { + ParseTestHelper::tearDown(); + self::$parseStorage->clear(); + } - public function testIsUsingDefaultStorage() - { - $this->assertTrue( + public function testIsUsingDefaultStorage() + { + $this->assertTrue( self::$parseStorage instanceof Parse\ParseMemoryStorage ); - } - - public function testSetAndGet() - { - self::$parseStorage->set('foo', 'bar'); - $this->assertEquals('bar', self::$parseStorage->get('foo')); - } + } - public function testRemove() - { - self::$parseStorage->set('foo', 'bar'); - self::$parseStorage->remove('foo'); - $this->assertNull(self::$parseStorage->get('foo')); - } + public function testSetAndGet() + { + self::$parseStorage->set('foo', 'bar'); + $this->assertEquals('bar', self::$parseStorage->get('foo')); + } - public function testClear() - { - self::$parseStorage->set('foo', 'bar'); - self::$parseStorage->set('foo2', 'bar'); - self::$parseStorage->set('foo3', 'bar'); - self::$parseStorage->clear(); - $this->assertEmpty(self::$parseStorage->getKeys()); - } + public function testRemove() + { + self::$parseStorage->set('foo', 'bar'); + self::$parseStorage->remove('foo'); + $this->assertNull(self::$parseStorage->get('foo')); + } - public function testGetAll() - { - self::$parseStorage->set('foo', 'bar'); - self::$parseStorage->set('foo2', 'bar'); - self::$parseStorage->set('foo3', 'bar'); - $result = self::$parseStorage->getAll(); - $this->assertEquals('bar', $result['foo']); - $this->assertEquals('bar', $result['foo2']); - $this->assertEquals('bar', $result['foo3']); - $this->assertEquals(3, count($result)); - } + public function testClear() + { + self::$parseStorage->set('foo', 'bar'); + self::$parseStorage->set('foo2', 'bar'); + self::$parseStorage->set('foo3', 'bar'); + self::$parseStorage->clear(); + $this->assertEmpty(self::$parseStorage->getKeys()); + } -} \ No newline at end of file + public function testGetAll() + { + self::$parseStorage->set('foo', 'bar'); + self::$parseStorage->set('foo2', 'bar'); + self::$parseStorage->set('foo3', 'bar'); + $result = self::$parseStorage->getAll(); + $this->assertEquals('bar', $result['foo']); + $this->assertEquals('bar', $result['foo2']); + $this->assertEquals('bar', $result['foo3']); + $this->assertEquals(3, count($result)); + } +} diff --git a/tests/ParseObjectTest.php b/tests/ParseObjectTest.php index 2262d5a0..96158a24 100644 --- a/tests/ParseObjectTest.php +++ b/tests/ParseObjectTest.php @@ -1,929 +1,926 @@ set('test', 'test'); - $obj->save(); - } + public function testCreate() + { + $obj = ParseObject::create('TestObject'); + $obj->set('test', 'test'); + $obj->save(); + } - public function testUpdate() - { - $obj = ParseObject::create('TestObject'); - $obj->set('foo', 'bar'); - $obj->save(); - $obj->set('foo', 'changed'); - $obj->save(); - $this->assertEquals($obj->foo, 'changed', + public function testUpdate() + { + $obj = ParseObject::create('TestObject'); + $obj->set('foo', 'bar'); + $obj->save(); + $obj->set('foo', 'changed'); + $obj->save(); + $this->assertEquals($obj->foo, 'changed', 'Update should have succeeded'); - } + } - public function testSaveCycle() - { - $a = ParseObject::create('TestObject'); - $b = ParseObject::create('TestObject'); - $a->set('b', $b); - $a->save(); - $this->assertFalse($a->isDirty()); - $this->assertNotNull($a->getObjectId()); - $this->assertNotNull($b->getObjectId()); - $b->set('a', $a); - $b->save(); - $this->assertEquals($b, $a->get('b')); - $this->assertEquals($a, $b->get('a')); - } + public function testSaveCycle() + { + $a = ParseObject::create('TestObject'); + $b = ParseObject::create('TestObject'); + $a->set('b', $b); + $a->save(); + $this->assertFalse($a->isDirty()); + $this->assertNotNull($a->getObjectId()); + $this->assertNotNull($b->getObjectId()); + $b->set('a', $a); + $b->save(); + $this->assertEquals($b, $a->get('b')); + $this->assertEquals($a, $b->get('a')); + } - public function testReturnedObjectIsAParseObject() - { - $obj = ParseObject::create('TestObject'); - $obj->set('foo', 'bar'); - $obj->save(); + public function testReturnedObjectIsAParseObject() + { + $obj = ParseObject::create('TestObject'); + $obj->set('foo', 'bar'); + $obj->save(); - $query = new ParseQuery('TestObject'); - $returnedObject = $query->get($obj->getObjectId()); - $this->assertTrue($returnedObject instanceOf ParseObject, + $query = new ParseQuery('TestObject'); + $returnedObject = $query->get($obj->getObjectId()); + $this->assertTrue($returnedObject instanceof ParseObject, 'Returned object was not a ParseObject'); - $this->assertEquals('bar', $returnedObject->foo, + $this->assertEquals('bar', $returnedObject->foo, 'Value of foo was not saved.'); - } - - public function testFetch() - { - $obj = ParseObject::create('TestObject'); - $obj->set('test', 'test'); - $obj->save(); - $t2 = ParseObject::create('TestObject', $obj->getObjectId()); - $t2->fetch(); - $this->assertEquals('test', $t2->get('test'), 'Fetch failed.'); - } + } - public function testDelete() - { - $obj = ParseObject::create('TestObject'); - $obj->set('foo', 'bar'); - $obj->save(); - $obj->destroy(); - $query = new ParseQuery('TestObject'); - $this->setExpectedException('Parse\ParseException', 'Object not found'); - $out = $query->get($obj->getObjectId()); - } + public function testFetch() + { + $obj = ParseObject::create('TestObject'); + $obj->set('test', 'test'); + $obj->save(); + $t2 = ParseObject::create('TestObject', $obj->getObjectId()); + $t2->fetch(); + $this->assertEquals('test', $t2->get('test'), 'Fetch failed.'); + } - public function testFind() - { - ParseTestHelper::clearClass('TestObject'); - $obj = ParseObject::create('TestObject'); - $obj->set('foo', 'bar'); - $obj->save(); - $query = new ParseQuery('TestObject'); - $query->equalTo('foo', 'bar'); - $response = $query->count(); - $this->assertTrue($response == 1); - } + public function testDelete() + { + $obj = ParseObject::create('TestObject'); + $obj->set('foo', 'bar'); + $obj->save(); + $obj->destroy(); + $query = new ParseQuery('TestObject'); + $this->setExpectedException('Parse\ParseException', 'Object not found'); + $out = $query->get($obj->getObjectId()); + } - public function testRelationalFields() - { - ParseTestHelper::clearClass("Item"); - ParseTestHelper::clearClass("Container"); - $item = ParseObject::create("Item"); - $item->set("property", "x"); - $item->save(); - - $container = ParseObject::create("Container"); - $container->set("item", $item); - $container->save(); - - $query = new ParseQuery("Container"); - $query->includeKey("item"); - $containerAgain = $query->get($container->getObjectId()); - $itemAgain = $containerAgain->get("item"); - $this->assertEquals("x", $itemAgain->get("property")); - - $query->equalTo("item", $item); - $results = $query->find(); - $this->assertEquals(1, count($results)); - } + public function testFind() + { + ParseTestHelper::clearClass('TestObject'); + $obj = ParseObject::create('TestObject'); + $obj->set('foo', 'bar'); + $obj->save(); + $query = new ParseQuery('TestObject'); + $query->equalTo('foo', 'bar'); + $response = $query->count(); + $this->assertTrue($response == 1); + } - public function testRelationDeletion() - { - ParseTestHelper::clearClass("SimpleObject"); - ParseTestHelper::clearClass("Child"); - $simple = ParseObject::create("SimpleObject"); - $child = ParseObject::create("Child"); - $simple->set('child', $child); - $simple->save(); - $this->assertNotNull($simple->get('child')); - $simple->delete('child'); - $this->assertNull($simple->get('child')); - $this->assertTrue($simple->isDirty()); - $this->assertTrue($simple->isKeyDirty('child')); - $simple->save(); - $this->assertNull($simple->get('child')); - $this->assertFalse($simple->isDirty()); - $this->assertFalse($simple->isKeyDirty('child')); - - $query = new ParseQuery("SimpleObject"); - $simpleAgain = $query->get($simple->getObjectId()); - $this->assertNull($simpleAgain->get('child')); - } + public function testRelationalFields() + { + ParseTestHelper::clearClass("Item"); + ParseTestHelper::clearClass("Container"); + $item = ParseObject::create("Item"); + $item->set("property", "x"); + $item->save(); + + $container = ParseObject::create("Container"); + $container->set("item", $item); + $container->save(); + + $query = new ParseQuery("Container"); + $query->includeKey("item"); + $containerAgain = $query->get($container->getObjectId()); + $itemAgain = $containerAgain->get("item"); + $this->assertEquals("x", $itemAgain->get("property")); + + $query->equalTo("item", $item); + $results = $query->find(); + $this->assertEquals(1, count($results)); + } - public function testSaveAddsNoDataKeys() - { - $obj = ParseObject::create('TestObject'); - $obj->save(); - $json = $obj->_encode(); - $data = get_object_vars(json_decode($json)); - unset($data['objectId']); - unset($data['createdAt']); - unset($data['updatedAt']); - $this->assertEquals(0, count($data)); - } + public function testRelationDeletion() + { + ParseTestHelper::clearClass("SimpleObject"); + ParseTestHelper::clearClass("Child"); + $simple = ParseObject::create("SimpleObject"); + $child = ParseObject::create("Child"); + $simple->set('child', $child); + $simple->save(); + $this->assertNotNull($simple->get('child')); + $simple->delete('child'); + $this->assertNull($simple->get('child')); + $this->assertTrue($simple->isDirty()); + $this->assertTrue($simple->isKeyDirty('child')); + $simple->save(); + $this->assertNull($simple->get('child')); + $this->assertFalse($simple->isDirty()); + $this->assertFalse($simple->isKeyDirty('child')); + + $query = new ParseQuery("SimpleObject"); + $simpleAgain = $query->get($simple->getObjectId()); + $this->assertNull($simpleAgain->get('child')); + } - public function testRecursiveSave() - { - ParseTestHelper::clearClass('Container'); - ParseTestHelper::clearClass('Item'); - $a = ParseObject::create('Container'); - $b = ParseObject::create('Item'); - $b->set('foo', 'bar'); - $a->set('item', $b); - $a->save(); - $query = new ParseQuery('Container'); - $result = $query->find(); - $this->assertEquals(1, count($result)); - $containerAgain = $result[0]; - $itemAgain = $containerAgain->get('item'); - $itemAgain->fetch(); - $this->assertEquals('bar', $itemAgain->get('foo')); - } + public function testSaveAddsNoDataKeys() + { + $obj = ParseObject::create('TestObject'); + $obj->save(); + $json = $obj->_encode(); + $data = get_object_vars(json_decode($json)); + unset($data['objectId']); + unset($data['createdAt']); + unset($data['updatedAt']); + $this->assertEquals(0, count($data)); + } - public function testFetchRemovesOldFields() - { - $obj = ParseObject::create('SimpleObject'); - $obj->set('foo', 'bar'); - $obj->set('test', 'foo'); - $obj->save(); + public function testRecursiveSave() + { + ParseTestHelper::clearClass('Container'); + ParseTestHelper::clearClass('Item'); + $a = ParseObject::create('Container'); + $b = ParseObject::create('Item'); + $b->set('foo', 'bar'); + $a->set('item', $b); + $a->save(); + $query = new ParseQuery('Container'); + $result = $query->find(); + $this->assertEquals(1, count($result)); + $containerAgain = $result[0]; + $itemAgain = $containerAgain->get('item'); + $itemAgain->fetch(); + $this->assertEquals('bar', $itemAgain->get('foo')); + } - $query = new ParseQuery('SimpleObject'); - $object1 = $query->get($obj->getObjectId()); - $object2 = $query->get($obj->getObjectId()); - $this->assertEquals('foo', $object1->get('test')); - $this->assertEquals('foo', $object2->get('test')); - $object2->delete('test'); - $this->assertEquals('foo', $object1->get('test')); - $object2->save(); - $object1->fetch(); - $this->assertEquals(null, $object1->get('test')); - $this->assertEquals(null, $object2->get('test')); - $this->assertEquals('bar', $object1->get('foo')); - $this->assertEquals('bar', $object2->get('foo')); - } + public function testFetchRemovesOldFields() + { + $obj = ParseObject::create('SimpleObject'); + $obj->set('foo', 'bar'); + $obj->set('test', 'foo'); + $obj->save(); + + $query = new ParseQuery('SimpleObject'); + $object1 = $query->get($obj->getObjectId()); + $object2 = $query->get($obj->getObjectId()); + $this->assertEquals('foo', $object1->get('test')); + $this->assertEquals('foo', $object2->get('test')); + $object2->delete('test'); + $this->assertEquals('foo', $object1->get('test')); + $object2->save(); + $object1->fetch(); + $this->assertEquals(null, $object1->get('test')); + $this->assertEquals(null, $object2->get('test')); + $this->assertEquals('bar', $object1->get('foo')); + $this->assertEquals('bar', $object2->get('foo')); + } - public function testCreatedAtAndUpdatedAtExposed() - { - $obj = ParseObject::create('TestObject'); - $obj->save(); - $this->assertNotNull($obj->getObjectId()); - $this->assertNotNull($obj->getCreatedAt()); - $this->assertNotNull($obj->getUpdatedAt()); - } + public function testCreatedAtAndUpdatedAtExposed() + { + $obj = ParseObject::create('TestObject'); + $obj->save(); + $this->assertNotNull($obj->getObjectId()); + $this->assertNotNull($obj->getCreatedAt()); + $this->assertNotNull($obj->getUpdatedAt()); + } - public function testCreatedAtDoesNotChange() - { - $obj = ParseObject::create('TestObject'); - $obj->save(); - $this->assertNotNull($obj->getObjectId()); - $objAgain = ParseObject::create('TestObject', $obj->getObjectId()); - $objAgain->fetch(); - $this->assertEquals( + public function testCreatedAtDoesNotChange() + { + $obj = ParseObject::create('TestObject'); + $obj->save(); + $this->assertNotNull($obj->getObjectId()); + $objAgain = ParseObject::create('TestObject', $obj->getObjectId()); + $objAgain->fetch(); + $this->assertEquals( $obj->getCreatedAt(), $objAgain->getCreatedAt() ); - } + } - public function testUpdatedAtGetsUpdated() - { - $obj = ParseObject::create('TestObject'); - $obj->set('foo', 'bar'); - $obj->save(); - $this->assertNotNull($obj->getUpdatedAt()); - $firstUpdate = $obj->getUpdatedAt(); + public function testUpdatedAtGetsUpdated() + { + $obj = ParseObject::create('TestObject'); + $obj->set('foo', 'bar'); + $obj->save(); + $this->assertNotNull($obj->getUpdatedAt()); + $firstUpdate = $obj->getUpdatedAt(); // Parse is so fast, this test was flaky as the \DateTimes were equal. sleep(1); - $obj->set('foo', 'baz'); - $obj->save(); - $this->assertNotEquals($obj->getUpdatedAt(), $firstUpdate); - } + $obj->set('foo', 'baz'); + $obj->save(); + $this->assertNotEquals($obj->getUpdatedAt(), $firstUpdate); + } - public function testCreatedAtIsReasonable() - { - $startTime = new \DateTime(); - $obj = ParseObject::create('TestObject'); - $obj->set('foo', 'bar'); - $obj->save(); - $endTime = new \DateTime(); - $startDiff = abs( + public function testCreatedAtIsReasonable() + { + $startTime = new \DateTime(); + $obj = ParseObject::create('TestObject'); + $obj->set('foo', 'bar'); + $obj->save(); + $endTime = new \DateTime(); + $startDiff = abs( $startTime->getTimestamp() - $obj->getCreatedAt()->getTimestamp() ); - $endDiff = abs( + $endDiff = abs( $endTime->getTimestamp() - $obj->getCreatedAt()->getTimestamp() ); - $this->assertLessThan(5000, $startDiff); - $this->assertLessThan(5000, $endDiff); - } + $this->assertLessThan(5000, $startDiff); + $this->assertLessThan(5000, $endDiff); + } - public function testCanSetNull() - { - $obj = ParseObject::create('TestObject'); - $obj->set('foo', null); - $obj->save(); - $this->assertEquals(null, $obj->get('foo')); - } + public function testCanSetNull() + { + $obj = ParseObject::create('TestObject'); + $obj->set('foo', null); + $obj->save(); + $this->assertEquals(null, $obj->get('foo')); + } - public function testCanSetBoolean() - { - $obj = ParseObject::create('TestObject'); - $obj->set('yes', true); - $obj->set('no', false); - $obj->save(); - $this->assertTrue($obj->get('yes')); - $this->assertFalse($obj->get('no')); - } + public function testCanSetBoolean() + { + $obj = ParseObject::create('TestObject'); + $obj->set('yes', true); + $obj->set('no', false); + $obj->save(); + $this->assertTrue($obj->get('yes')); + $this->assertFalse($obj->get('no')); + } - public function testInvalidClassName() - { - $obj = ParseObject::create('Foo^bar'); - $this->setExpectedException('Parse\ParseException', 'bad characters in classname'); - $obj->save(); - } + public function testInvalidClassName() + { + $obj = ParseObject::create('Foo^bar'); + $this->setExpectedException('Parse\ParseException', 'bad characters in classname'); + $obj->save(); + } - public function testInvalidKeyName() - { - $obj = ParseObject::create("TestItem"); - $obj->set('foo^bar', 'baz'); - $this->setExpectedException('Parse\ParseException', + public function testInvalidKeyName() + { + $obj = ParseObject::create("TestItem"); + $obj->set('foo^bar', 'baz'); + $this->setExpectedException('Parse\ParseException', 'invalid field name'); - $obj->save(); - } - - public function testSimpleFieldDeletion() - { - $obj = ParseObject::create("TestObject"); - $obj->set('foo', 'bar'); - $obj->save(); - $obj->delete('foo'); - $this->assertFalse($obj->has('foo'), 'foo should have been unset.'); - $this->assertTrue($obj->isKeyDirty('foo'), 'foo should be dirty.'); - $this->assertTrue($obj->isDirty(), 'the whole object should be dirty.'); - $obj->save(); - $this->assertFalse($obj->has('foo'), 'foo should have been unset.'); - $this->assertFalse($obj->isKeyDirty('foo'), 'object was just saved.'); - $this->assertFalse($obj->isDirty(), 'object was just saved.'); - - $query = new ParseQuery("TestObject"); - $result = $query->get($obj->getObjectId()); - $this->assertFalse($result->has('foo'), 'foo was not removed.'); - } - - public function testFieldDeletionBeforeFirstSave() - { - $obj = ParseObject::create('TestObject'); - $obj->set('foo', 'bar'); - $obj->delete('foo'); - $this->assertFalse($obj->has('foo'), 'foo should have been unset.'); - $this->assertTrue($obj->isKeyDirty('foo'), 'foo should be dirty.'); - $this->assertTrue($obj->isDirty(), 'the whole object should be dirty.'); - $obj->save(); - $this->assertFalse($obj->has('foo'), 'foo should have been unset.'); - $this->assertFalse($obj->isKeyDirty('foo'), 'object was just saved.'); - $this->assertFalse($obj->isDirty(), 'object was just saved.'); - } - - public function testDeletedKeysGetCleared() - { - $obj = ParseObject::create('TestObject'); - $obj->set('foo', 'bar'); - $obj->delete('foo'); - $obj->save(); - $obj->set('foo', 'baz'); - $obj->save(); - - $query = new ParseQuery("TestObject"); - $result = $query->get($obj->getObjectId()); - $this->assertEquals('baz', $result->get('foo')); - } - - public function testSettingAfterDeleting() - { - $obj = ParseObject::create('TestObject'); - $obj->set('foo', 'bar'); - $obj->save(); - $obj->delete('foo'); - $obj->set('foo', 'baz'); - $obj->save(); - - $query = new ParseQuery("TestObject"); - $result = $query->get($obj->getObjectId()); - $this->assertEquals('baz', $result->get('foo')); - } - - public function testDirtyKeys() - { - $obj = ParseObject::create('TestObject'); - $obj->set('cat', 'good'); - $obj->set('dog', 'bad'); - $obj->save(); - $this->assertFalse($obj->isDirty()); - $this->assertFalse($obj->isKeyDirty('cat')); - $this->assertFalse($obj->isKeyDirty('dog')); - $obj->set('dog', 'okay'); - $this->assertTrue($obj->isKeyDirty('dog')); - $this->assertTrue($obj->isDirty()); - } - - public function testOldAttributeUnsetThenUnset() - { - $obj = ParseObject::create('TestObject'); - $obj->set('x', 3); - $obj->save(); - $obj->delete('x'); - $obj->delete('x'); - $obj->save(); - $this->assertFalse($obj->has('x')); - $this->assertNull($obj->get('x')); - - $query = new ParseQuery('TestObject'); - $result = $query->get($obj->getObjectId()); - $this->assertFalse($result->has('x')); - $this->assertNull($result->get('x')); - } - - public function testNewAttributeUnsetThenUnset() - { - $obj = ParseObject::create('TestObject'); - $obj->set('x', 5); - $obj->delete('x'); - $obj->delete('x'); - $obj->save(); - $this->assertFalse($obj->has('x')); - $this->assertNull($obj->get('x')); - - $query = new ParseQuery('TestObject'); - $result = $query->get($obj->getObjectId()); - $this->assertFalse($result->has('x')); - $this->assertNull($result->get('x')); - } - - public function testUnknownAttributeUnsetThenUnset() - { - $obj = ParseObject::create('TestObject'); - $obj->delete('x'); - $obj->delete('x'); - $obj->save(); - $this->assertFalse($obj->has('x')); - $this->assertNull($obj->get('x')); - - $query = new ParseQuery('TestObject'); - $result = $query->get($obj->getObjectId()); - $this->assertFalse($result->has('x')); - $this->assertNull($result->get('x')); - } - - public function oldAttributeUnsetThenClear() - { - $obj = ParseObject::create('TestObject'); - $obj->set('x', 3); - $obj->save(); - $obj->delete('x'); - $obj->clear(); - $obj->save(); - $this->assertFalse($obj->has('x')); - $this->assertNull($obj->get('x')); - - $query = new ParseQuery('TestObject'); - $result = $query->get($obj->getObjectId()); - $this->assertFalse($result->has('x')); - $this->assertNull($result->get('x')); - } + $obj->save(); + } - public function testNewAttributeUnsetThenClear() - { - $obj = ParseObject::create('TestObject'); - $obj->set('x', 5); - $obj->delete('x'); - $obj->clear(); - $obj->save(); - $this->assertFalse($obj->has('x')); - $this->assertNull($obj->get('x')); + public function testSimpleFieldDeletion() + { + $obj = ParseObject::create("TestObject"); + $obj->set('foo', 'bar'); + $obj->save(); + $obj->delete('foo'); + $this->assertFalse($obj->has('foo'), 'foo should have been unset.'); + $this->assertTrue($obj->isKeyDirty('foo'), 'foo should be dirty.'); + $this->assertTrue($obj->isDirty(), 'the whole object should be dirty.'); + $obj->save(); + $this->assertFalse($obj->has('foo'), 'foo should have been unset.'); + $this->assertFalse($obj->isKeyDirty('foo'), 'object was just saved.'); + $this->assertFalse($obj->isDirty(), 'object was just saved.'); + + $query = new ParseQuery("TestObject"); + $result = $query->get($obj->getObjectId()); + $this->assertFalse($result->has('foo'), 'foo was not removed.'); + } - $query = new ParseQuery('TestObject'); - $result = $query->get($obj->getObjectId()); - $this->assertFalse($result->has('x')); - $this->assertNull($result->get('x')); - } + public function testFieldDeletionBeforeFirstSave() + { + $obj = ParseObject::create('TestObject'); + $obj->set('foo', 'bar'); + $obj->delete('foo'); + $this->assertFalse($obj->has('foo'), 'foo should have been unset.'); + $this->assertTrue($obj->isKeyDirty('foo'), 'foo should be dirty.'); + $this->assertTrue($obj->isDirty(), 'the whole object should be dirty.'); + $obj->save(); + $this->assertFalse($obj->has('foo'), 'foo should have been unset.'); + $this->assertFalse($obj->isKeyDirty('foo'), 'object was just saved.'); + $this->assertFalse($obj->isDirty(), 'object was just saved.'); + } - public function testUnknownAttributeUnsetThenClear() - { - $obj = ParseObject::create('TestObject'); - $obj->delete('x'); - $obj->clear(); - $obj->save(); - $this->assertFalse($obj->has('x')); - $this->assertNull($obj->get('x')); + public function testDeletedKeysGetCleared() + { + $obj = ParseObject::create('TestObject'); + $obj->set('foo', 'bar'); + $obj->delete('foo'); + $obj->save(); + $obj->set('foo', 'baz'); + $obj->save(); + + $query = new ParseQuery("TestObject"); + $result = $query->get($obj->getObjectId()); + $this->assertEquals('baz', $result->get('foo')); + } - $query = new ParseQuery('TestObject'); - $result = $query->get($obj->getObjectId()); - $this->assertFalse($result->has('x')); - $this->assertNull($result->get('x')); - } + public function testSettingAfterDeleting() + { + $obj = ParseObject::create('TestObject'); + $obj->set('foo', 'bar'); + $obj->save(); + $obj->delete('foo'); + $obj->set('foo', 'baz'); + $obj->save(); + + $query = new ParseQuery("TestObject"); + $result = $query->get($obj->getObjectId()); + $this->assertEquals('baz', $result->get('foo')); + } - public function oldAttributeClearThenUnset() - { - $obj = ParseObject::create('TestObject'); - $obj->set('x', 3); - $obj->save(); - $obj->clear(); - $obj->delete('x'); - $obj->save(); - $this->assertFalse($obj->has('x')); - $this->assertNull($obj->get('x')); + public function testDirtyKeys() + { + $obj = ParseObject::create('TestObject'); + $obj->set('cat', 'good'); + $obj->set('dog', 'bad'); + $obj->save(); + $this->assertFalse($obj->isDirty()); + $this->assertFalse($obj->isKeyDirty('cat')); + $this->assertFalse($obj->isKeyDirty('dog')); + $obj->set('dog', 'okay'); + $this->assertTrue($obj->isKeyDirty('dog')); + $this->assertTrue($obj->isDirty()); + } - $query = new ParseQuery('TestObject'); - $result = $query->get($obj->getObjectId()); - $this->assertFalse($result->has('x')); - $this->assertNull($result->get('x')); - } + public function testOldAttributeUnsetThenUnset() + { + $obj = ParseObject::create('TestObject'); + $obj->set('x', 3); + $obj->save(); + $obj->delete('x'); + $obj->delete('x'); + $obj->save(); + $this->assertFalse($obj->has('x')); + $this->assertNull($obj->get('x')); + + $query = new ParseQuery('TestObject'); + $result = $query->get($obj->getObjectId()); + $this->assertFalse($result->has('x')); + $this->assertNull($result->get('x')); + } - public function testNewAttributeClearThenUnset() - { - $obj = ParseObject::create('TestObject'); - $obj->set('x', 5); - $obj->clear(); - $obj->delete('x'); - $obj->save(); - $this->assertFalse($obj->has('x')); - $this->assertNull($obj->get('x')); + public function testNewAttributeUnsetThenUnset() + { + $obj = ParseObject::create('TestObject'); + $obj->set('x', 5); + $obj->delete('x'); + $obj->delete('x'); + $obj->save(); + $this->assertFalse($obj->has('x')); + $this->assertNull($obj->get('x')); + + $query = new ParseQuery('TestObject'); + $result = $query->get($obj->getObjectId()); + $this->assertFalse($result->has('x')); + $this->assertNull($result->get('x')); + } - $query = new ParseQuery('TestObject'); - $result = $query->get($obj->getObjectId()); - $this->assertFalse($result->has('x')); - $this->assertNull($result->get('x')); - } + public function testUnknownAttributeUnsetThenUnset() + { + $obj = ParseObject::create('TestObject'); + $obj->delete('x'); + $obj->delete('x'); + $obj->save(); + $this->assertFalse($obj->has('x')); + $this->assertNull($obj->get('x')); + + $query = new ParseQuery('TestObject'); + $result = $query->get($obj->getObjectId()); + $this->assertFalse($result->has('x')); + $this->assertNull($result->get('x')); + } - public function testUnknownAttributeClearThenUnset() - { - $obj = ParseObject::create('TestObject'); - $obj->clear(); - $obj->delete('x'); - $obj->save(); - $this->assertFalse($obj->has('x')); - $this->assertNull($obj->get('x')); + public function oldAttributeUnsetThenClear() + { + $obj = ParseObject::create('TestObject'); + $obj->set('x', 3); + $obj->save(); + $obj->delete('x'); + $obj->clear(); + $obj->save(); + $this->assertFalse($obj->has('x')); + $this->assertNull($obj->get('x')); + + $query = new ParseQuery('TestObject'); + $result = $query->get($obj->getObjectId()); + $this->assertFalse($result->has('x')); + $this->assertNull($result->get('x')); + } - $query = new ParseQuery('TestObject'); - $result = $query->get($obj->getObjectId()); - $this->assertFalse($result->has('x')); - $this->assertNull($result->get('x')); - } + public function testNewAttributeUnsetThenClear() + { + $obj = ParseObject::create('TestObject'); + $obj->set('x', 5); + $obj->delete('x'); + $obj->clear(); + $obj->save(); + $this->assertFalse($obj->has('x')); + $this->assertNull($obj->get('x')); + + $query = new ParseQuery('TestObject'); + $result = $query->get($obj->getObjectId()); + $this->assertFalse($result->has('x')); + $this->assertNull($result->get('x')); + } - public function oldAttributeClearThenClear() - { - $obj = ParseObject::create('TestObject'); - $obj->set('x', 3); - $obj->save(); - $obj->clear(); - $obj->clear(); - $obj->save(); - $this->assertFalse($obj->has('x')); - $this->assertNull($obj->get('x')); + public function testUnknownAttributeUnsetThenClear() + { + $obj = ParseObject::create('TestObject'); + $obj->delete('x'); + $obj->clear(); + $obj->save(); + $this->assertFalse($obj->has('x')); + $this->assertNull($obj->get('x')); + + $query = new ParseQuery('TestObject'); + $result = $query->get($obj->getObjectId()); + $this->assertFalse($result->has('x')); + $this->assertNull($result->get('x')); + } - $query = new ParseQuery('TestObject'); - $result = $query->get($obj->getObjectId()); - $this->assertFalse($result->has('x')); - $this->assertNull($result->get('x')); - } + public function oldAttributeClearThenUnset() + { + $obj = ParseObject::create('TestObject'); + $obj->set('x', 3); + $obj->save(); + $obj->clear(); + $obj->delete('x'); + $obj->save(); + $this->assertFalse($obj->has('x')); + $this->assertNull($obj->get('x')); + + $query = new ParseQuery('TestObject'); + $result = $query->get($obj->getObjectId()); + $this->assertFalse($result->has('x')); + $this->assertNull($result->get('x')); + } - public function testNewAttributeClearThenClear() - { - $obj = ParseObject::create('TestObject'); - $obj->set('x', 5); - $obj->clear(); - $obj->clear(); - $obj->save(); - $this->assertFalse($obj->has('x')); - $this->assertNull($obj->get('x')); + public function testNewAttributeClearThenUnset() + { + $obj = ParseObject::create('TestObject'); + $obj->set('x', 5); + $obj->clear(); + $obj->delete('x'); + $obj->save(); + $this->assertFalse($obj->has('x')); + $this->assertNull($obj->get('x')); + + $query = new ParseQuery('TestObject'); + $result = $query->get($obj->getObjectId()); + $this->assertFalse($result->has('x')); + $this->assertNull($result->get('x')); + } - $query = new ParseQuery('TestObject'); - $result = $query->get($obj->getObjectId()); - $this->assertFalse($result->has('x')); - $this->assertNull($result->get('x')); - } + public function testUnknownAttributeClearThenUnset() + { + $obj = ParseObject::create('TestObject'); + $obj->clear(); + $obj->delete('x'); + $obj->save(); + $this->assertFalse($obj->has('x')); + $this->assertNull($obj->get('x')); + + $query = new ParseQuery('TestObject'); + $result = $query->get($obj->getObjectId()); + $this->assertFalse($result->has('x')); + $this->assertNull($result->get('x')); + } - public function testUnknownAttributeClearThenClear() - { - $obj = ParseObject::create('TestObject'); - $obj->clear(); - $obj->clear(); - $obj->save(); - $this->assertFalse($obj->has('x')); - $this->assertNull($obj->get('x')); + public function oldAttributeClearThenClear() + { + $obj = ParseObject::create('TestObject'); + $obj->set('x', 3); + $obj->save(); + $obj->clear(); + $obj->clear(); + $obj->save(); + $this->assertFalse($obj->has('x')); + $this->assertNull($obj->get('x')); + + $query = new ParseQuery('TestObject'); + $result = $query->get($obj->getObjectId()); + $this->assertFalse($result->has('x')); + $this->assertNull($result->get('x')); + } - $query = new ParseQuery('TestObject'); - $result = $query->get($obj->getObjectId()); - $this->assertFalse($result->has('x')); - $this->assertNull($result->get('x')); - } + public function testNewAttributeClearThenClear() + { + $obj = ParseObject::create('TestObject'); + $obj->set('x', 5); + $obj->clear(); + $obj->clear(); + $obj->save(); + $this->assertFalse($obj->has('x')); + $this->assertNull($obj->get('x')); + + $query = new ParseQuery('TestObject'); + $result = $query->get($obj->getObjectId()); + $this->assertFalse($result->has('x')); + $this->assertNull($result->get('x')); + } - public function testSavingChildrenInArray() - { - ParseTestHelper::clearClass("Parent"); - ParseTestHelper::clearClass("Child"); - $parent = ParseObject::create("Parent"); - $child1 = ParseObject::create("Child"); - $child2 = ParseObject::create("Child"); - $child1->set('name', 'tyrian'); - $child2->set('name', 'cersei'); - $parent->setArray('children', array($child1, $child2)); - $parent->save(); - - $query = new ParseQuery("Child"); - $query->ascending('name'); - $results = $query->find(); - $this->assertEquals(2, count($results)); - $this->assertEquals('cersei', $results[0]->get('name')); - $this->assertEquals('tyrian', $results[1]->get('name')); - } + public function testUnknownAttributeClearThenClear() + { + $obj = ParseObject::create('TestObject'); + $obj->clear(); + $obj->clear(); + $obj->save(); + $this->assertFalse($obj->has('x')); + $this->assertNull($obj->get('x')); + + $query = new ParseQuery('TestObject'); + $result = $query->get($obj->getObjectId()); + $this->assertFalse($result->has('x')); + $this->assertNull($result->get('x')); + } - public function testManySaveAfterAFailure() - { - $obj = ParseObject::create("TestObject"); - $obj->set("number", 1); - $obj->save(); - $obj2 = ParseObject::create("TestObject"); - $obj2->set("number", "two"); - $exceptions = 0; - try { - $obj2->save(); - } catch (\Parse\ParseException $pe) { - $exceptions++; - } - $obj2->set('foo', 'bar'); - try { - $obj2->save(); - } catch (\Parse\ParseException $pe) { - $exceptions++; - } - $obj2->set('foo', 'baz'); - try { - $obj2->save(); - } catch (\Parse\ParseException $pe) { - $exceptions++; - } - $obj2->set('number', 3); - $obj2->save(); - if ($exceptions != 3) { - $this->fail("Did not cause expected # of exceptions."); + public function testSavingChildrenInArray() + { + ParseTestHelper::clearClass("Parent"); + ParseTestHelper::clearClass("Child"); + $parent = ParseObject::create("Parent"); + $child1 = ParseObject::create("Child"); + $child2 = ParseObject::create("Child"); + $child1->set('name', 'tyrian'); + $child2->set('name', 'cersei'); + $parent->setArray('children', [$child1, $child2]); + $parent->save(); + + $query = new ParseQuery("Child"); + $query->ascending('name'); + $results = $query->find(); + $this->assertEquals(2, count($results)); + $this->assertEquals('cersei', $results[0]->get('name')); + $this->assertEquals('tyrian', $results[1]->get('name')); } - } - public function testNewKeyIsDirtyAfterSave() - { - $obj = ParseObject::create("TestObject"); - $obj->save(); - $obj->set('content', 'x'); - $obj->fetch(); - $this->assertTrue($obj->isKeyDirty('content')); - } + public function testManySaveAfterAFailure() + { + $obj = ParseObject::create("TestObject"); + $obj->set("number", 1); + $obj->save(); + $obj2 = ParseObject::create("TestObject"); + $obj2->set("number", "two"); + $exceptions = 0; + try { + $obj2->save(); + } catch (\Parse\ParseException $pe) { + $exceptions++; + } + $obj2->set('foo', 'bar'); + try { + $obj2->save(); + } catch (\Parse\ParseException $pe) { + $exceptions++; + } + $obj2->set('foo', 'baz'); + try { + $obj2->save(); + } catch (\Parse\ParseException $pe) { + $exceptions++; + } + $obj2->set('number', 3); + $obj2->save(); + if ($exceptions != 3) { + $this->fail("Did not cause expected # of exceptions."); + } + } - public function testAddWithAnObject() - { - $parent = ParseObject::create("Person"); - $child = ParseObject::create("Person"); - $child->save(); - $parent->add("children", array($child)); - $parent->save(); + public function testNewKeyIsDirtyAfterSave() + { + $obj = ParseObject::create("TestObject"); + $obj->save(); + $obj->set('content', 'x'); + $obj->fetch(); + $this->assertTrue($obj->isKeyDirty('content')); + } - $query = new ParseQuery("Person"); - $parentAgain = $query->get($parent->getObjectId()); - $children = $parentAgain->get("children"); - $this->assertEquals( + public function testAddWithAnObject() + { + $parent = ParseObject::create("Person"); + $child = ParseObject::create("Person"); + $child->save(); + $parent->add("children", [$child]); + $parent->save(); + + $query = new ParseQuery("Person"); + $parentAgain = $query->get($parent->getObjectId()); + $children = $parentAgain->get("children"); + $this->assertEquals( $child->getObjectId(), $children[0]->getObjectId() ); - } - - public function testAddUnique() - { - $obj = ParseObject::create("TestObject"); - $obj->setArray('arr', [1, 2, 3]); - $obj->addUnique('arr', [1]); - $this->assertEquals(3, count($obj->get('arr'))); - $obj->addUnique('arr', [4]); - $this->assertEquals(4, count($obj->get('arr'))); + } - $obj->save(); - $obj2 = ParseObject::create("TestObject"); - $obj3 = ParseObject::create("TestObject"); - $obj2->save(); - $obj3->save(); - - $obj4 = ParseObject::create("TestObject"); - $obj4->setArray('parseObjects', [$obj, $obj2]); - $obj4->save(); - $obj4->addUnique('parseObjects', [$obj3]); - $this->assertEquals(3, count($obj4->get('parseObjects'))); - $obj4->addUnique('parseObjects', [$obj2]); - $this->assertEquals(3, count($obj4->get('parseObjects'))); - } + public function testAddUnique() + { + $obj = ParseObject::create("TestObject"); + $obj->setArray('arr', [1, 2, 3]); + $obj->addUnique('arr', [1]); + $this->assertEquals(3, count($obj->get('arr'))); + $obj->addUnique('arr', [4]); + $this->assertEquals(4, count($obj->get('arr'))); + + $obj->save(); + $obj2 = ParseObject::create("TestObject"); + $obj3 = ParseObject::create("TestObject"); + $obj2->save(); + $obj3->save(); + + $obj4 = ParseObject::create("TestObject"); + $obj4->setArray('parseObjects', [$obj, $obj2]); + $obj4->save(); + $obj4->addUnique('parseObjects', [$obj3]); + $this->assertEquals(3, count($obj4->get('parseObjects'))); + $obj4->addUnique('parseObjects', [$obj2]); + $this->assertEquals(3, count($obj4->get('parseObjects'))); + } - public function testToJSONSavedObject() - { - $obj = ParseObject::create('TestObject'); - $obj->set('foo', 'bar'); - $obj->save(); - $json = $obj->_encode(); - $decoded = json_decode($json); - $this->assertTrue(isset($decoded->objectId)); - $this->assertTrue(isset($decoded->createdAt)); - $this->assertTrue(isset($decoded->updatedAt)); - $this->assertTrue(isset($decoded->foo)); - } + public function testToJSONSavedObject() + { + $obj = ParseObject::create('TestObject'); + $obj->set('foo', 'bar'); + $obj->save(); + $json = $obj->_encode(); + $decoded = json_decode($json); + $this->assertTrue(isset($decoded->objectId)); + $this->assertTrue(isset($decoded->createdAt)); + $this->assertTrue(isset($decoded->updatedAt)); + $this->assertTrue(isset($decoded->foo)); + } - public function testToJSONUnsavedObject() - { - $obj = ParseObject::create('TestObject'); - $obj->set('foo', 'bar'); - $json = $obj->_encode(); - $decoded = json_decode($json); - $this->assertFalse(isset($decoded->objectId)); - $this->assertFalse(isset($decoded->createdAt)); - $this->assertFalse(isset($decoded->updatedAt)); - $this->assertTrue(isset($decoded->foo)); - } + public function testToJSONUnsavedObject() + { + $obj = ParseObject::create('TestObject'); + $obj->set('foo', 'bar'); + $json = $obj->_encode(); + $decoded = json_decode($json); + $this->assertFalse(isset($decoded->objectId)); + $this->assertFalse(isset($decoded->createdAt)); + $this->assertFalse(isset($decoded->updatedAt)); + $this->assertTrue(isset($decoded->foo)); + } - public function testRemoveOperation() - { - $obj = ParseObject::create('TestObject'); - $obj->setArray('arr', [1, 2, 3]); - $obj->save(); - $this->assertEquals(3, count($obj->get('arr'))); - $obj->remove('arr', 1); - $this->assertEquals(2, count($obj->get('arr'))); - $obj->remove('arr', 1); - $obj->save(); - $query = new ParseQuery("TestObject"); - $objAgain = $query->get($obj->getObjectId()); - $this->assertEquals(2, count($objAgain->get('arr'))); - $objAgain->remove('arr', 2); - $this->assertEquals(1, count($objAgain->get('arr'))); - } + public function testRemoveOperation() + { + $obj = ParseObject::create('TestObject'); + $obj->setArray('arr', [1, 2, 3]); + $obj->save(); + $this->assertEquals(3, count($obj->get('arr'))); + $obj->remove('arr', 1); + $this->assertEquals(2, count($obj->get('arr'))); + $obj->remove('arr', 1); + $obj->save(); + $query = new ParseQuery("TestObject"); + $objAgain = $query->get($obj->getObjectId()); + $this->assertEquals(2, count($objAgain->get('arr'))); + $objAgain->remove('arr', 2); + $this->assertEquals(1, count($objAgain->get('arr'))); + } - public function testRemoveOperationWithParseObjects() - { - $o1 = ParseObject::create('TestObject'); - $o2 = ParseObject::create('TestObject'); - $o3 = ParseObject::create('TestObject'); - ParseObject::saveAll([$o1, $o2, $o3]); - $obj = ParseObject::create('TestObject'); - $obj->setArray('objs', [$o1, $o2, $o3]); - $obj->save(); - $this->assertEquals(3, count($obj->get('objs'))); - $obj->remove('objs', $o3); - $this->assertEquals(2, count($obj->get('objs'))); - $obj->remove('objs', $o3); - $obj->save(); - $query = new ParseQuery("TestObject"); - $objAgain = $query->get($obj->getObjectId()); - $this->assertEquals(2, count($objAgain->get('objs'))); - $objAgain->remove('objs', $o2); - $this->assertEquals(1, count($objAgain->get('objs'))); - } + public function testRemoveOperationWithParseObjects() + { + $o1 = ParseObject::create('TestObject'); + $o2 = ParseObject::create('TestObject'); + $o3 = ParseObject::create('TestObject'); + ParseObject::saveAll([$o1, $o2, $o3]); + $obj = ParseObject::create('TestObject'); + $obj->setArray('objs', [$o1, $o2, $o3]); + $obj->save(); + $this->assertEquals(3, count($obj->get('objs'))); + $obj->remove('objs', $o3); + $this->assertEquals(2, count($obj->get('objs'))); + $obj->remove('objs', $o3); + $obj->save(); + $query = new ParseQuery("TestObject"); + $objAgain = $query->get($obj->getObjectId()); + $this->assertEquals(2, count($objAgain->get('objs'))); + $objAgain->remove('objs', $o2); + $this->assertEquals(1, count($objAgain->get('objs'))); + } - public function testDestroyAll() - { - ParseTestHelper::clearClass("TestObject"); - $o1 = ParseObject::create('TestObject'); - $o2 = ParseObject::create('TestObject'); - $o3 = ParseObject::create('TestObject'); - ParseObject::saveAll([$o1, $o2, $o3]); - ParseObject::destroyAll([$o1, $o2, $o3]); - $query = new ParseQuery("TestObject"); - $results = $query->find(); - $this->assertEquals(0, count($results)); - } + public function testDestroyAll() + { + ParseTestHelper::clearClass("TestObject"); + $o1 = ParseObject::create('TestObject'); + $o2 = ParseObject::create('TestObject'); + $o3 = ParseObject::create('TestObject'); + ParseObject::saveAll([$o1, $o2, $o3]); + ParseObject::destroyAll([$o1, $o2, $o3]); + $query = new ParseQuery("TestObject"); + $results = $query->find(); + $this->assertEquals(0, count($results)); + } - public function testEmptyArray() - { - $obj = ParseObject::create('TestObject'); - $obj->setArray('baz', array()); - $obj->save(); - $query = new ParseQuery('TestObject'); - $returnedObject = $query->get($obj->getObjectId()); - $this->assertTrue(is_array($returnedObject->get('baz')), + public function testEmptyArray() + { + $obj = ParseObject::create('TestObject'); + $obj->setArray('baz', []); + $obj->save(); + $query = new ParseQuery('TestObject'); + $returnedObject = $query->get($obj->getObjectId()); + $this->assertTrue(is_array($returnedObject->get('baz')), 'Value was not stored as an array.'); - $this->assertEquals(0, count($returnedObject->get('baz'))); - } - - public function testArraySetAndAdd() - { - $obj = ParseObject::create('TestObject'); - $obj->setArray('arrayfield', array('a', 'b')); - $obj->save(); - $obj->add('arrayfield', array('c', 'd', 'e')); - $obj->save(); - } - - public function testObjectIsDirty() - { - $obj = ParseObject::create('Gogo'); - $key1 = 'awesome'; - $key2 = 'great'; - $key3 = 'arrayKey'; - $value1 = 'very true'; - $value2 = true; - - $obj->set($key1, $value1); - $this->assertTrue($obj->isKeyDirty($key1)); - $this->assertFalse($obj->isKeyDirty($key2)); - $this->assertTrue($obj->isDirty()); - - $obj->save(); - $this->assertFalse($obj->isKeyDirty($key1)); - $this->assertFalse($obj->isKeyDirty($key2)); - $this->assertFalse($obj->isDirty()); + $this->assertEquals(0, count($returnedObject->get('baz'))); + } - $obj->set($key2, $value2); - $this->assertTrue($obj->isKeyDirty($key2)); - $this->assertFalse($obj->isKeyDirty($key1)); - $this->assertTrue($obj->isDirty()); + public function testArraySetAndAdd() + { + $obj = ParseObject::create('TestObject'); + $obj->setArray('arrayfield', ['a', 'b']); + $obj->save(); + $obj->add('arrayfield', ['c', 'd', 'e']); + $obj->save(); + } - $query = new ParseQuery('Gogo'); - $queriedObj = $query->get($obj->getObjectId()); - $this->assertEquals($value1, $queriedObj->get($key1)); - $this->assertFalse($queriedObj->get($key2) === $value2); + public function testObjectIsDirty() + { + $obj = ParseObject::create('Gogo'); + $key1 = 'awesome'; + $key2 = 'great'; + $key3 = 'arrayKey'; + $value1 = 'very true'; + $value2 = true; + + $obj->set($key1, $value1); + $this->assertTrue($obj->isKeyDirty($key1)); + $this->assertFalse($obj->isKeyDirty($key2)); + $this->assertTrue($obj->isDirty()); + + $obj->save(); + $this->assertFalse($obj->isKeyDirty($key1)); + $this->assertFalse($obj->isKeyDirty($key2)); + $this->assertFalse($obj->isDirty()); + + $obj->set($key2, $value2); + $this->assertTrue($obj->isKeyDirty($key2)); + $this->assertFalse($obj->isKeyDirty($key1)); + $this->assertTrue($obj->isDirty()); + + $query = new ParseQuery('Gogo'); + $queriedObj = $query->get($obj->getObjectId()); + $this->assertEquals($value1, $queriedObj->get($key1)); + $this->assertFalse($queriedObj->get($key2) === $value2); // check dirtiness of queried item $this->assertFalse($queriedObj->isKeyDirty($key1)); - $this->assertFalse($queriedObj->isKeyDirty($key2)); - $this->assertFalse($queriedObj->isDirty()); + $this->assertFalse($queriedObj->isKeyDirty($key2)); + $this->assertFalse($queriedObj->isDirty()); - $obj->save(); - $queriedObj = $query->get($obj->getObjectId()); - $this->assertEquals($value1, $queriedObj->get($key1)); - $this->assertEquals($value2, $queriedObj->get($key2)); - $this->assertFalse($queriedObj->isKeyDirty($key1)); - $this->assertFalse($queriedObj->isKeyDirty($key2)); - $this->assertFalse($queriedObj->isDirty()); + $obj->save(); + $queriedObj = $query->get($obj->getObjectId()); + $this->assertEquals($value1, $queriedObj->get($key1)); + $this->assertEquals($value2, $queriedObj->get($key2)); + $this->assertFalse($queriedObj->isKeyDirty($key1)); + $this->assertFalse($queriedObj->isKeyDirty($key2)); + $this->assertFalse($queriedObj->isDirty()); // check array - $obj->add($key3, array($value1, $value2, $value1)); - $this->assertTrue($obj->isDirty()); + $obj->add($key3, [$value1, $value2, $value1]); + $this->assertTrue($obj->isDirty()); - $obj->save(); - $this->assertFalse($obj->isDirty()); - } + $obj->save(); + $this->assertFalse($obj->isDirty()); + } - public function testObjectIsDirtyWithChildren() - { - $obj = ParseObject::create('Sito'); - $key = 'testKey'; - $childKey = 'testChildKey'; - $childSimultaneousKey = 'testChildKeySimultaneous'; - $value = 'someRandomValue'; - $child = ParseObject::create('Sito'); - $childSimultaneous = ParseObject::create('Sito'); - $childArray1 = ParseObject::create('Sito'); - $childArray2 = ParseObject::create('Sito'); - - $child->set('randomKey', 'randomValue'); - $this->assertTrue($child->isDirty()); - - $obj->set($key, $value); - $this->assertTrue($obj->isDirty()); + public function testObjectIsDirtyWithChildren() + { + $obj = ParseObject::create('Sito'); + $key = 'testKey'; + $childKey = 'testChildKey'; + $childSimultaneousKey = 'testChildKeySimultaneous'; + $value = 'someRandomValue'; + $child = ParseObject::create('Sito'); + $childSimultaneous = ParseObject::create('Sito'); + $childArray1 = ParseObject::create('Sito'); + $childArray2 = ParseObject::create('Sito'); - $obj->save(); - $this->assertFalse($obj->isDirty()); + $child->set('randomKey', 'randomValue'); + $this->assertTrue($child->isDirty()); + + $obj->set($key, $value); + $this->assertTrue($obj->isDirty()); - $obj->set($childKey, $child); - $this->assertTrue($obj->isKeyDirty($childKey)); - $this->assertTrue($obj->isDirty()); + $obj->save(); + $this->assertFalse($obj->isDirty()); + + $obj->set($childKey, $child); + $this->assertTrue($obj->isKeyDirty($childKey)); + $this->assertTrue($obj->isDirty()); // check when child is saved, parent should still be dirty $child->save(); - $this->assertFalse($child->isDirty()); - $this->assertTrue($obj->isDirty()); + $this->assertFalse($child->isDirty()); + $this->assertTrue($obj->isDirty()); - $obj->save(); - $this->assertFalse($child->isDirty()); - $this->assertFalse($obj->isDirty()); + $obj->save(); + $this->assertFalse($child->isDirty()); + $this->assertFalse($obj->isDirty()); - $childSimultaneous->set('randomKey', 'randomValue'); - $obj->set($childSimultaneousKey, $childSimultaneous); - $this->assertTrue($obj->isDirty()); + $childSimultaneous->set('randomKey', 'randomValue'); + $obj->set($childSimultaneousKey, $childSimultaneous); + $this->assertTrue($obj->isDirty()); // check case with array $childArray1->set('random', 'random2'); - $obj->add('arrayKey', array($childArray1, $childArray2)); - $this->assertTrue($obj->isDirty()); - $childArray1->save(); - $childArray2->save(); - $this->assertFalse($childArray1->getObjectId() === null); - $this->assertFalse($childArray2->getObjectId() === null); - $this->assertFalse($obj->getObjectId() === null); - $this->assertTrue($obj->isDirty()); - $obj->save(); - $this->assertFalse($obj->isDirty()); + $obj->add('arrayKey', [$childArray1, $childArray2]); + $this->assertTrue($obj->isDirty()); + $childArray1->save(); + $childArray2->save(); + $this->assertFalse($childArray1->getObjectId() === null); + $this->assertFalse($childArray2->getObjectId() === null); + $this->assertFalse($obj->getObjectId() === null); + $this->assertTrue($obj->isDirty()); + $obj->save(); + $this->assertFalse($obj->isDirty()); // check simultaneous save $obj->save(); - $this->assertFalse($obj->isDirty()); - $this->assertFalse($childSimultaneous->isDirty()); - } + $this->assertFalse($obj->isDirty()); + $this->assertFalse($childSimultaneous->isDirty()); + } - public function testSaveAll() - { - ParseTestHelper::clearClass("TestObject"); - $objs = array(); - for ($i = 1; $i <= 90; $i++) { - $obj = ParseObject::create('TestObject'); - $obj->set('test', 'test'); - $objs[] = $obj; - } - ParseObject::saveAll($objs); - $query = new ParseQuery('TestObject'); - $result = $query->find(); - $this->assertEquals(90, count($result)); - } + public function testSaveAll() + { + ParseTestHelper::clearClass("TestObject"); + $objs = []; + for ($i = 1; $i <= 90; $i++) { + $obj = ParseObject::create('TestObject'); + $obj->set('test', 'test'); + $objs[] = $obj; + } + ParseObject::saveAll($objs); + $query = new ParseQuery('TestObject'); + $result = $query->find(); + $this->assertEquals(90, count($result)); + } - public function testEmptyObjectsAndArrays() - { - $obj = ParseObject::create('TestObject'); - $obj->setArray('arr', array()); - $obj->setAssociativeArray('obj', array()); - $saveOpArray = new SetOperation(array()); - $saveOpAssoc = new SetOperation(array(), true); - $this->assertTrue( + public function testEmptyObjectsAndArrays() + { + $obj = ParseObject::create('TestObject'); + $obj->setArray('arr', []); + $obj->setAssociativeArray('obj', []); + $saveOpArray = new SetOperation([]); + $saveOpAssoc = new SetOperation([], true); + $this->assertTrue( is_array($saveOpArray->_encode()), "Value should be array." ); - $this->assertTrue( + $this->assertTrue( is_object($saveOpAssoc->_encode()), "Value should be object." ); - $obj->save(); - $obj->setAssociativeArray('obj', array( + $obj->save(); + $obj->setAssociativeArray('obj', [ 'foo' => 'bar', - 'baz' => 'yay' - )); - $obj->save(); - $query = new ParseQuery('TestObject'); - $objAgain = $query->get($obj->getObjectId()); - $this->assertTrue(is_array($objAgain->get('arr'))); - $this->assertTrue(is_array($objAgain->get('obj'))); - $this->assertEquals('bar', $objAgain->get('obj')['foo']); - $this->assertEquals('yay', $objAgain->get('obj')['baz']); - } - - public function testDatetimeHandling() - { - $date = new DateTime('2014-04-30T12:34:56.789Z'); - $obj = ParseObject::create('TestObject'); - $obj->set('f8', $date); - $obj->save(); - $query = new ParseQuery('TestObject'); - $objAgain = $query->get($obj->getObjectId()); - $dateAgain = $objAgain->get('f8'); - $this->assertTrue($date->getTimestamp() == $dateAgain->getTimestamp()); - } + 'baz' => 'yay', + ]); + $obj->save(); + $query = new ParseQuery('TestObject'); + $objAgain = $query->get($obj->getObjectId()); + $this->assertTrue(is_array($objAgain->get('arr'))); + $this->assertTrue(is_array($objAgain->get('obj'))); + $this->assertEquals('bar', $objAgain->get('obj')['foo']); + $this->assertEquals('yay', $objAgain->get('obj')['baz']); + } - public function testBatchSaveExceptions() - { - $obj1 = ParseObject::create("TestObject"); - $obj2 = ParseObject::create("TestObject"); - $obj1->set("fos^^co", "hi"); - $obj2->set("fo^^mo", "hi"); - try { - ParseObject::saveAll([$obj1, $obj2]); - $this->fail("Save should have failed."); - } catch (\Parse\ParseAggregateException $ex) { - $errors = $ex->getErrors(); - $this->assertContains("invalid field name", $errors[0]['error']); - $this->assertContains("invalid field name", $errors[1]['error']); + public function testDatetimeHandling() + { + $date = new DateTime('2014-04-30T12:34:56.789Z'); + $obj = ParseObject::create('TestObject'); + $obj->set('f8', $date); + $obj->save(); + $query = new ParseQuery('TestObject'); + $objAgain = $query->get($obj->getObjectId()); + $dateAgain = $objAgain->get('f8'); + $this->assertTrue($date->getTimestamp() == $dateAgain->getTimestamp()); } - } + public function testBatchSaveExceptions() + { + $obj1 = ParseObject::create("TestObject"); + $obj2 = ParseObject::create("TestObject"); + $obj1->set("fos^^co", "hi"); + $obj2->set("fo^^mo", "hi"); + try { + ParseObject::saveAll([$obj1, $obj2]); + $this->fail("Save should have failed."); + } catch (\Parse\ParseAggregateException $ex) { + $errors = $ex->getErrors(); + $this->assertContains("invalid field name", $errors[0]['error']); + $this->assertContains("invalid field name", $errors[1]['error']); + } + } } diff --git a/tests/ParsePushTest.php b/tests/ParsePushTest.php index d58066e0..3582461a 100644 --- a/tests/ParsePushTest.php +++ b/tests/ParsePushTest.php @@ -1,49 +1,47 @@ array(''), - 'data' => array('alert' => 'sample message') - )); + ParseTestHelper::setUp(); } - public function testPushToQuery() - { - $query = ParseInstallation::query(); - $query->equalTo('key', 'value'); - ParsePush::send(array( - 'data' => array('alert' => 'iPhone 5 is out!'), - 'where' => $query - )); - } - - public function testPushDates() - { - ParsePush::send(array( - 'data' => array('alert' => 'iPhone 5 is out!'), - 'push_time' => new DateTime(), + public function tearDown() + { + ParseTestHelper::tearDown(); + } + + public function testBasicPush() + { + ParsePush::send([ + 'channels' => [''], + 'data' => ['alert' => 'sample message'], + ]); + } + + public function testPushToQuery() + { + $query = ParseInstallation::query(); + $query->equalTo('key', 'value'); + ParsePush::send([ + 'data' => ['alert' => 'iPhone 5 is out!'], + 'where' => $query, + ]); + } + + public function testPushDates() + { + ParsePush::send([ + 'data' => ['alert' => 'iPhone 5 is out!'], + 'push_time' => new DateTime(), 'expiration_time' => new DateTime(), - 'channels' => array() - )); - } -} \ No newline at end of file + 'channels' => [], + ]); + } +} diff --git a/tests/ParseQueryTest.php b/tests/ParseQueryTest.php index 71a23e73..f714af03 100644 --- a/tests/ParseQueryTest.php +++ b/tests/ParseQueryTest.php @@ -1,30 +1,28 @@ saveObjects($numberOfObjects, function ($i) { + public function provideTestObjects($numberOfObjects) + { + $this->saveObjects($numberOfObjects, function ($i) { $obj = ParseObject::create('TestObject'); - $obj->set('foo', 'bar' . $i); + $obj->set('foo', 'bar'.$i); + return $obj; }); - } + } - public function testBasicQuery() - { - $baz = new ParseObject("TestObject"); - $baz->set("foo", "baz"); - $qux = new ParseObject("TestObject"); - $qux->set("foo", "qux"); - $baz->save(); - $qux->save(); - - $query = new ParseQuery("TestObject"); - $query->equalTo("foo", "baz"); - $results = $query->find(); - $this->assertEquals(1, count($results), + public function testBasicQuery() + { + $baz = new ParseObject("TestObject"); + $baz->set("foo", "baz"); + $qux = new ParseObject("TestObject"); + $qux->set("foo", "qux"); + $baz->save(); + $qux->save(); + + $query = new ParseQuery("TestObject"); + $query->equalTo("foo", "baz"); + $results = $query->find(); + $this->assertEquals(1, count($results), 'Did not find object.'); - $this->assertEquals("baz", $results[0]->get("foo"), + $this->assertEquals("baz", $results[0]->get("foo"), 'Did not return the correct object.'); - } + } - public function testQueryWithLimit() - { - $baz = new ParseObject("TestObject"); - $baz->set("foo", "baz"); - $qux = new ParseObject("TestObject"); - $qux->set("foo", "qux"); - $baz->save(); - $qux->save(); - - $query = new ParseQuery("TestObject"); - $query->limit(1); - $results = $query->find(); - $this->assertEquals(1, count($results), + public function testQueryWithLimit() + { + $baz = new ParseObject("TestObject"); + $baz->set("foo", "baz"); + $qux = new ParseObject("TestObject"); + $qux->set("foo", "qux"); + $baz->save(); + $qux->save(); + + $query = new ParseQuery("TestObject"); + $query->limit(1); + $results = $query->find(); + $this->assertEquals(1, count($results), 'Did not return correct number of objects.'); - } + } - public function testEqualTo() - { - $obj = ParseObject::create('TestObject'); - $obj->set('foo', 'bar'); - $obj->save(); - $query = new ParseQuery('TestObject'); - $query->equalTo('objectId', $obj->getObjectId()); - $results = $query->find(); - $this->assertTrue(count($results) == 1, 'Did not find object.'); - } + public function testEqualTo() + { + $obj = ParseObject::create('TestObject'); + $obj->set('foo', 'bar'); + $obj->save(); + $query = new ParseQuery('TestObject'); + $query->equalTo('objectId', $obj->getObjectId()); + $results = $query->find(); + $this->assertTrue(count($results) == 1, 'Did not find object.'); + } - public function testNotEqualTo() - { - $this->provideTestObjects(10); - $query = new ParseQuery('TestObject'); - $query->notEqualTo('foo', 'bar9'); - $results = $query->find(); - $this->assertEquals(count($results), 9, - 'Did not find 9 objects, found ' . count($results)); - } + public function testNotEqualTo() + { + $this->provideTestObjects(10); + $query = new ParseQuery('TestObject'); + $query->notEqualTo('foo', 'bar9'); + $results = $query->find(); + $this->assertEquals(count($results), 9, + 'Did not find 9 objects, found '.count($results)); + } - public function testLessThan() - { - $this->provideTestObjects(10); - $query = new ParseQuery('TestObject'); - $query->lessThan('foo', 'bar1'); - $results = $query->find(); - $this->assertEquals(count($results), 1, + public function testLessThan() + { + $this->provideTestObjects(10); + $query = new ParseQuery('TestObject'); + $query->lessThan('foo', 'bar1'); + $results = $query->find(); + $this->assertEquals(count($results), 1, 'LessThan function did not return correct number of objects.'); - $this->assertEquals($results[0]->get('foo'), 'bar0', + $this->assertEquals($results[0]->get('foo'), 'bar0', 'LessThan function did not return the correct object'); - } + } - public function testLessThanOrEqualTo() - { - $this->provideTestObjects(10); - $query = new ParseQuery('TestObject'); - $query->lessThanOrEqualTo('foo', 'bar0'); - $results = $query->find(); - $this->assertEquals(count($results), 1, + public function testLessThanOrEqualTo() + { + $this->provideTestObjects(10); + $query = new ParseQuery('TestObject'); + $query->lessThanOrEqualTo('foo', 'bar0'); + $results = $query->find(); + $this->assertEquals(count($results), 1, 'LessThanOrEqualTo function did not return correct number of objects.'); - $this->assertEquals($results[0]->get('foo'), 'bar0', + $this->assertEquals($results[0]->get('foo'), 'bar0', 'LessThanOrEqualTo function did not return the correct object.'); - } + } - public function testStartsWithSingle() - { - $this->provideTestObjects(10); - $query = new ParseQuery('TestObject'); - $query->startsWith('foo', 'bar0'); - $results = $query->find(); - $this->assertEquals(count($results), 1, + public function testStartsWithSingle() + { + $this->provideTestObjects(10); + $query = new ParseQuery('TestObject'); + $query->startsWith('foo', 'bar0'); + $results = $query->find(); + $this->assertEquals(count($results), 1, 'StartsWith function did not return correct number of objects.'); - $this->assertEquals($results[0]->get('foo'), 'bar0', + $this->assertEquals($results[0]->get('foo'), 'bar0', 'StartsWith function did not return the correct object.'); - } + } - public function testStartsWithMultiple() - { - $this->provideTestObjects(10); - $query = new ParseQuery('TestObject'); - $query->startsWith('foo', 'bar'); - $results = $query->find(); - $this->assertEquals(count($results), 10, + public function testStartsWithMultiple() + { + $this->provideTestObjects(10); + $query = new ParseQuery('TestObject'); + $query->startsWith('foo', 'bar'); + $results = $query->find(); + $this->assertEquals(count($results), 10, 'StartsWith function did not return correct number of objects.'); - } + } - public function testStartsWithMiddle() - { - $this->provideTestObjects(10); - $query = new ParseQuery('TestObject'); - $query->startsWith('foo', 'ar'); - $results = $query->find(); - $this->assertEquals(count($results), 0, + public function testStartsWithMiddle() + { + $this->provideTestObjects(10); + $query = new ParseQuery('TestObject'); + $query->startsWith('foo', 'ar'); + $results = $query->find(); + $this->assertEquals(count($results), 0, 'StartsWith function did not return correct number of objects.'); - } + } - public function testStartsWithRegexDelimiters() - { - $testObject = ParseObject::create("TestObject"); - $testObject->set("foo", "foob\E"); - $testObject->save(); - $query = new ParseQuery('TestObject'); - $query->startsWith('foo', 'foob\E'); - $results = $query->find(); - $this->assertEquals(count($results), 1, + public function testStartsWithRegexDelimiters() + { + $testObject = ParseObject::create("TestObject"); + $testObject->set("foo", "foob\E"); + $testObject->save(); + $query = new ParseQuery('TestObject'); + $query->startsWith('foo', 'foob\E'); + $results = $query->find(); + $this->assertEquals(count($results), 1, 'StartsWith function did not return correct number of objects.'); - $query->startsWith('foo', 'foobE'); - $results = $query->find(); - $this->assertEquals(count($results), 0, + $query->startsWith('foo', 'foobE'); + $results = $query->find(); + $this->assertEquals(count($results), 0, 'StartsWith function did not return correct number of objects.'); - } + } - public function testStartsWithRegexDot() - { - $testObject = ParseObject::create("TestObject"); - $testObject->set("foo", "foobarfoo"); - $testObject->save(); - $query = new ParseQuery('TestObject'); - $query->startsWith('foo', 'foo(.)*'); - $results = $query->find(); - $this->assertEquals(count($results), 0, + public function testStartsWithRegexDot() + { + $testObject = ParseObject::create("TestObject"); + $testObject->set("foo", "foobarfoo"); + $testObject->save(); + $query = new ParseQuery('TestObject'); + $query->startsWith('foo', 'foo(.)*'); + $results = $query->find(); + $this->assertEquals(count($results), 0, 'StartsWith function did not return correct number of objects.'); - $query->startsWith('foo', 'foo.*'); - $results = $query->find(); - $this->assertEquals(count($results), 0, + $query->startsWith('foo', 'foo.*'); + $results = $query->find(); + $this->assertEquals(count($results), 0, 'StartsWith function did not return correct number of objects.'); - $query->startsWith('foo', 'foo'); - $results = $query->find(); - $this->assertEquals(count($results), 1, + $query->startsWith('foo', 'foo'); + $results = $query->find(); + $this->assertEquals(count($results), 1, 'StartsWith function did not return correct number of objects.'); - } + } - public function testStartsWithRegexSlash() - { - $testObject = ParseObject::create("TestObject"); - $testObject->set("foo", "foobarfoo"); - $testObject->save(); - $query = new ParseQuery('TestObject'); - $query->startsWith('foo', 'foo/bar'); - $results = $query->find(); - $this->assertEquals(count($results), 0, + public function testStartsWithRegexSlash() + { + $testObject = ParseObject::create("TestObject"); + $testObject->set("foo", "foobarfoo"); + $testObject->save(); + $query = new ParseQuery('TestObject'); + $query->startsWith('foo', 'foo/bar'); + $results = $query->find(); + $this->assertEquals(count($results), 0, 'StartsWith function did not return correct number of objects.'); - $query->startsWith('foo', 'foobar'); - $results = $query->find(); - $this->assertEquals(count($results), 1, + $query->startsWith('foo', 'foobar'); + $results = $query->find(); + $this->assertEquals(count($results), 1, 'StartsWith function did not return correct number of objects.'); - } + } - public function testStartsWithRegexQuestionmark() - { - $testObject = ParseObject::create("TestObject"); - $testObject->set("foo", "foobarfoo"); - $testObject->save(); - $query = new ParseQuery('TestObject'); - $query->startsWith('foo', 'foox?bar'); - $results = $query->find(); - $this->assertEquals(count($results), 0, + public function testStartsWithRegexQuestionmark() + { + $testObject = ParseObject::create("TestObject"); + $testObject->set("foo", "foobarfoo"); + $testObject->save(); + $query = new ParseQuery('TestObject'); + $query->startsWith('foo', 'foox?bar'); + $results = $query->find(); + $this->assertEquals(count($results), 0, 'StartsWith function did not return correct number of objects.'); - $query->startsWith('foo', 'foo(x)?bar'); - $results = $query->find(); - $this->assertEquals(count($results), 0, + $query->startsWith('foo', 'foo(x)?bar'); + $results = $query->find(); + $this->assertEquals(count($results), 0, 'StartsWith function did not return correct number of objects.'); - $query->startsWith('foo', 'foobar'); - $results = $query->find(); - $this->assertEquals(count($results), 1, + $query->startsWith('foo', 'foobar'); + $results = $query->find(); + $this->assertEquals(count($results), 1, 'StartsWith function did not return correct number of objects.'); - } + } - public function testGreaterThan() - { - $this->provideTestObjects(10); - $query = new ParseQuery('TestObject'); - $query->greaterThan('foo', 'bar8'); - $results = $query->find(); - $this->assertEquals(count($results), 1, + public function testGreaterThan() + { + $this->provideTestObjects(10); + $query = new ParseQuery('TestObject'); + $query->greaterThan('foo', 'bar8'); + $results = $query->find(); + $this->assertEquals(count($results), 1, 'GreaterThan function did not return correct number of objects.'); - $this->assertEquals($results[0]->get('foo'), 'bar9', + $this->assertEquals($results[0]->get('foo'), 'bar9', 'GreaterThan function did not return the correct object.'); - } + } - public function testGreaterThanOrEqualTo() - { - $this->provideTestObjects(10); - $query = new ParseQuery('TestObject'); - $query->greaterThanOrEqualTo('foo', 'bar9'); - $results = $query->find(); - $this->assertEquals(count($results), 1, + public function testGreaterThanOrEqualTo() + { + $this->provideTestObjects(10); + $query = new ParseQuery('TestObject'); + $query->greaterThanOrEqualTo('foo', 'bar9'); + $results = $query->find(); + $this->assertEquals(count($results), 1, 'GreaterThanOrEqualTo function did not return correct number of objects.'); - $this->assertEquals($results[0]->get('foo'), 'bar9', + $this->assertEquals($results[0]->get('foo'), 'bar9', 'GreaterThanOrEqualTo function did not return the correct object.'); - } + } - public function testLessThanOrEqualGreaterThanOrEqual() - { - $this->provideTestObjects(10); - $query = new ParseQuery('TestObject'); - $query->lessThanOrEqualTo('foo', 'bar4'); - $query->greaterThanOrEqualTo('foo', 'bar2'); - $results = $query->find(); - $this->assertEquals(3, count($results), + public function testLessThanOrEqualGreaterThanOrEqual() + { + $this->provideTestObjects(10); + $query = new ParseQuery('TestObject'); + $query->lessThanOrEqualTo('foo', 'bar4'); + $query->greaterThanOrEqualTo('foo', 'bar2'); + $results = $query->find(); + $this->assertEquals(3, count($results), 'LessThanGreaterThan did not return correct number of objects.'); - } + } - public function testLessThanGreaterThan() - { - $this->provideTestObjects(10); - $query = new ParseQuery('TestObject'); - $query->lessThan('foo', 'bar5'); - $query->greaterThan('foo', 'bar3'); - $results = $query->find(); - $this->assertEquals(1, count($results), + public function testLessThanGreaterThan() + { + $this->provideTestObjects(10); + $query = new ParseQuery('TestObject'); + $query->lessThan('foo', 'bar5'); + $query->greaterThan('foo', 'bar3'); + $results = $query->find(); + $this->assertEquals(1, count($results), 'LessThanGreaterThan did not return correct number of objects.'); - $this->assertEquals('bar4', $results[0]->get('foo'), + $this->assertEquals('bar4', $results[0]->get('foo'), 'LessThanGreaterThan did not return the correct object.'); - } + } - public function testObjectIdEqualTo() - { - ParseTestHelper::clearClass("BoxedNumber"); - $boxedNumberArray = array(); - $this->saveObjects(5, function ($i) use (&$boxedNumberArray) { + public function testObjectIdEqualTo() + { + ParseTestHelper::clearClass("BoxedNumber"); + $boxedNumberArray = []; + $this->saveObjects(5, function ($i) use (&$boxedNumberArray) { $boxedNumber = new ParseObject("BoxedNumber"); $boxedNumber->set("number", $i); $boxedNumberArray[] = $boxedNumber; + return $boxedNumber; }); - $query = new ParseQuery("BoxedNumber"); - $query->equalTo("objectId", $boxedNumberArray[4]->getObjectId()); - $results = $query->find(); - $this->assertEquals(1, count($results), + $query = new ParseQuery("BoxedNumber"); + $query->equalTo("objectId", $boxedNumberArray[4]->getObjectId()); + $results = $query->find(); + $this->assertEquals(1, count($results), 'Did not find object.'); - $this->assertEquals(4, $results[0]->get("number"), + $this->assertEquals(4, $results[0]->get("number"), 'Did not return the correct object.'); - } + } - public function testFindNoElements() - { - ParseTestHelper::clearClass("BoxedNumber"); - $this->saveObjects(5, function ($i) { + public function testFindNoElements() + { + ParseTestHelper::clearClass("BoxedNumber"); + $this->saveObjects(5, function ($i) { $boxedNumber = new ParseObject("BoxedNumber"); $boxedNumber->set("number", $i); + return $boxedNumber; }); - $query = new ParseQuery("BoxedNumber"); - $query->equalTo("number", 17); - $results = $query->find(); - $this->assertEquals(0, count($results), + $query = new ParseQuery("BoxedNumber"); + $query->equalTo("number", 17); + $results = $query->find(); + $this->assertEquals(0, count($results), 'Did not return correct number of objects.'); - } + } - public function testFindWithError() - { - $query = new ParseQuery("TestObject"); - $this->setExpectedException('Parse\ParseException', 'Invalid key', 102); - $query->equalTo('$foo', 'bar'); - $query->find(); - } + public function testFindWithError() + { + $query = new ParseQuery("TestObject"); + $this->setExpectedException('Parse\ParseException', 'Invalid key', 102); + $query->equalTo('$foo', 'bar'); + $query->find(); + } - public function testGet() - { - $testObj = ParseObject::create("TestObject"); - $testObj->set("foo", "bar"); - $testObj->save(); - $query = new ParseQuery("TestObject"); - $result = $query->get($testObj->getObjectId()); - $this->assertEquals($testObj->getObjectId(), $result->getObjectId(), + public function testGet() + { + $testObj = ParseObject::create("TestObject"); + $testObj->set("foo", "bar"); + $testObj->save(); + $query = new ParseQuery("TestObject"); + $result = $query->get($testObj->getObjectId()); + $this->assertEquals($testObj->getObjectId(), $result->getObjectId(), 'Did not return the correct object.'); - $this->assertEquals("bar", $result->get("foo"), + $this->assertEquals("bar", $result->get("foo"), 'Did not return the correct object.'); - } + } - public function testGetError() - { - $obj = ParseObject::create("TestObject"); - $obj->set('foo', 'bar'); - $obj->save(); - $query = new ParseQuery("TestObject"); - $this->setExpectedException('Parse\ParseException', 'Object not found', 101); - $query->get("InvalidObjectID"); - } + public function testGetError() + { + $obj = ParseObject::create("TestObject"); + $obj->set('foo', 'bar'); + $obj->save(); + $query = new ParseQuery("TestObject"); + $this->setExpectedException('Parse\ParseException', 'Object not found', 101); + $query->get("InvalidObjectID"); + } - public function testGetNull() - { - $obj = ParseObject::create("TestObject"); - $obj->set('foo', 'bar'); - $obj->save(); - $query = new ParseQuery("TestObject"); - $this->setExpectedException('Parse\ParseException', 'Object not found', 101); - $query->get(null); - } + public function testGetNull() + { + $obj = ParseObject::create("TestObject"); + $obj->set('foo', 'bar'); + $obj->save(); + $query = new ParseQuery("TestObject"); + $this->setExpectedException('Parse\ParseException', 'Object not found', 101); + $query->get(null); + } - public function testFirst() - { - $testObject = ParseObject::create("TestObject"); - $testObject->set("foo", "bar"); - $testObject->save(); - $query = new ParseQuery("TestObject"); - $query->equalTo("foo", "bar"); - $result = $query->first(); - $this->assertEquals("bar", $result->get("foo"), + public function testFirst() + { + $testObject = ParseObject::create("TestObject"); + $testObject->set("foo", "bar"); + $testObject->save(); + $query = new ParseQuery("TestObject"); + $query->equalTo("foo", "bar"); + $result = $query->first(); + $this->assertEquals("bar", $result->get("foo"), 'Did not return the correct object.'); - } + } - public function testFirstWithError() - { - $query = new ParseQuery("TestObject"); - $query->equalTo('$foo', 'bar'); - $this->setExpectedException('Parse\ParseException', 'Invalid key', 102); - $query->first(); - } + public function testFirstWithError() + { + $query = new ParseQuery("TestObject"); + $query->equalTo('$foo', 'bar'); + $this->setExpectedException('Parse\ParseException', 'Invalid key', 102); + $query->first(); + } - public function testFirstNoResult() - { - $testObject = ParseObject::create("TestObject"); - $testObject->set("foo", "bar"); - $testObject->save(); - $query = new ParseQuery("TestObject"); - $query->equalTo("foo", "baz"); - $result = $query->first(); - $this->assertTrue(empty($result), + public function testFirstNoResult() + { + $testObject = ParseObject::create("TestObject"); + $testObject->set("foo", "bar"); + $testObject->save(); + $query = new ParseQuery("TestObject"); + $query->equalTo("foo", "baz"); + $result = $query->first(); + $this->assertTrue(empty($result), 'Did not return correct number of objects.'); - } + } - public function testFirstWithTwoResults() - { - $this->saveObjects(2, function ($i) { + public function testFirstWithTwoResults() + { + $this->saveObjects(2, function ($i) { $testObject = ParseObject::create("TestObject"); $testObject->set("foo", "bar"); + return $testObject; }); - $query = new ParseQuery("TestObject"); - $query->equalTo("foo", "bar"); - $result = $query->first(); - $this->assertEquals("bar", $result->get("foo"), + $query = new ParseQuery("TestObject"); + $query->equalTo("foo", "bar"); + $result = $query->first(); + $this->assertEquals("bar", $result->get("foo"), 'Did not return the correct object.'); - } + } - public function testNotEqualToObject() - { - ParseTestHelper::clearClass("Container"); - ParseTestHelper::clearClass("Item"); - $items = array(); - $this->saveObjects(2, function ($i) use (&$items) { + public function testNotEqualToObject() + { + ParseTestHelper::clearClass("Container"); + ParseTestHelper::clearClass("Item"); + $items = []; + $this->saveObjects(2, function ($i) use (&$items) { $items[] = ParseObject::create("Item"); + return $items[$i]; }); - $this->saveObjects(2, function ($i) use ($items) { + $this->saveObjects(2, function ($i) use ($items) { $container = ParseObject::create("Container"); $container->set("item", $items[$i]); + return $container; }); - $query = new ParseQuery("Container"); - $query->notEqualTo("item", $items[0]); - $result = $query->find(); - $this->assertEquals(1, count($result), + $query = new ParseQuery("Container"); + $query->notEqualTo("item", $items[0]); + $result = $query->find(); + $this->assertEquals(1, count($result), 'Did not return the correct object.'); - } + } - public function testSkip() - { - $this->saveObjects(2, function ($i) { + public function testSkip() + { + $this->saveObjects(2, function ($i) { return ParseObject::create("TestObject"); }); - $query = new ParseQuery("TestObject"); - $query->skip(1); - $result = $query->find(); - $this->assertEquals(1, count($result), + $query = new ParseQuery("TestObject"); + $query->skip(1); + $result = $query->find(); + $this->assertEquals(1, count($result), 'Did not return the correct object.'); - $query->skip(3); - $result = $query->find(); - $this->assertEquals(0, count($result), + $query->skip(3); + $result = $query->find(); + $this->assertEquals(0, count($result), 'Did not return the correct object.'); - } + } - public function testSkipDoesNotAffectCount() - { - $this->saveObjects(2, function ($i) { + public function testSkipDoesNotAffectCount() + { + $this->saveObjects(2, function ($i) { return ParseObject::create("TestObject"); }); - $query = new ParseQuery("TestObject"); - $count = $query->count(); - $this->assertEquals(2, $count, + $query = new ParseQuery("TestObject"); + $count = $query->count(); + $this->assertEquals(2, $count, 'Did not return correct number of objects.'); - $query->skip(1); - $this->assertEquals(2, $count, + $query->skip(1); + $this->assertEquals(2, $count, 'Did not return correct number of objects.'); - $query->skip(3); - $this->assertEquals(2, $count, + $query->skip(3); + $this->assertEquals(2, $count, 'Did not return correct number of objects.'); - } + } - public function testCount() - { - ParseTestHelper::clearClass("BoxedNumber"); - $this->saveObjects(3, function ($i) { + public function testCount() + { + ParseTestHelper::clearClass("BoxedNumber"); + $this->saveObjects(3, function ($i) { $boxedNumber = ParseObject::create("BoxedNumber"); $boxedNumber->set("x", $i + 1); + return $boxedNumber; }); - $query = new ParseQuery("BoxedNumber"); - $query->greaterThan("x", 1); - $count = $query->count(); - $this->assertEquals(2, $count, + $query = new ParseQuery("BoxedNumber"); + $query->greaterThan("x", 1); + $count = $query->count(); + $this->assertEquals(2, $count, 'Did not return correct number of objects.'); - } + } - public function testCountError() - { - $query = new ParseQuery("Test"); - $query->equalTo('$foo', "bar"); - $this->setExpectedException('Parse\ParseException', 'Invalid key', 102); - $query->count(); - } + public function testCountError() + { + $query = new ParseQuery("Test"); + $query->equalTo('$foo', "bar"); + $this->setExpectedException('Parse\ParseException', 'Invalid key', 102); + $query->count(); + } - public function testOrderByAscendingNumber() - { - ParseTestHelper::clearClass("BoxedNumber"); - $numbers = [3, 1, 2]; - $this->saveObjects(3, function ($i) use ($numbers) { + public function testOrderByAscendingNumber() + { + ParseTestHelper::clearClass("BoxedNumber"); + $numbers = [3, 1, 2]; + $this->saveObjects(3, function ($i) use ($numbers) { $boxedNumber = ParseObject::create("BoxedNumber"); $boxedNumber->set("number", $numbers[$i]); + return $boxedNumber; }); - $query = new ParseQuery("BoxedNumber"); - $query->ascending("number"); - $results = $query->find(); - $this->assertEquals(3, count($results), + $query = new ParseQuery("BoxedNumber"); + $query->ascending("number"); + $results = $query->find(); + $this->assertEquals(3, count($results), 'Did not return correct number of objects.'); - for ($i = 0; $i < 3; $i++) { - $this->assertEquals($i + 1, $results[$i]->get("number"), + for ($i = 0; $i < 3; $i++) { + $this->assertEquals($i + 1, $results[$i]->get("number"), 'Did not return the correct object.'); + } } - } - public function testOrderByDescendingNumber() - { - ParseTestHelper::clearClass("BoxedNumber"); - $numbers = [3, 1, 2]; - $this->saveObjects(3, function ($i) use ($numbers) { + public function testOrderByDescendingNumber() + { + ParseTestHelper::clearClass("BoxedNumber"); + $numbers = [3, 1, 2]; + $this->saveObjects(3, function ($i) use ($numbers) { $boxedNumber = ParseObject::create("BoxedNumber"); $boxedNumber->set("number", $numbers[$i]); + return $boxedNumber; }); - $query = new ParseQuery("BoxedNumber"); - $query->descending("number"); - $results = $query->find(); - $this->assertEquals(3, count($results), + $query = new ParseQuery("BoxedNumber"); + $query->descending("number"); + $results = $query->find(); + $this->assertEquals(3, count($results), 'Did not return correct number of objects.'); - for ($i = 0; $i < 3; $i++) { - $this->assertEquals(3 - $i, $results[$i]->get("number"), + for ($i = 0; $i < 3; $i++) { + $this->assertEquals(3 - $i, $results[$i]->get("number"), 'Did not return the correct object.'); + } } - } - public function provideTestObjectsForQuery($numberOfObjects) - { - $this->saveObjects($numberOfObjects, function ($i) { + public function provideTestObjectsForQuery($numberOfObjects) + { + $this->saveObjects($numberOfObjects, function ($i) { $parent = ParseObject::create("ParentObject"); $child = ParseObject::create("ChildObject"); $child->set("x", $i); $parent->set("x", 10 + $i); $parent->set("child", $child); + return $parent; }); - } + } - public function testMatchesQuery() - { - ParseTestHelper::clearClass("ChildObject"); - ParseTestHelper::clearClass("ParentObject"); - $this->provideTestObjectsForQuery(10); - $subQuery = new ParseQuery("ChildObject"); - $subQuery->greaterThan("x", 5); - $query = new ParseQuery("ParentObject"); - $query->matchesQuery("child", $subQuery); - $results = $query->find(); - - $this->assertEquals(4, count($results), + public function testMatchesQuery() + { + ParseTestHelper::clearClass("ChildObject"); + ParseTestHelper::clearClass("ParentObject"); + $this->provideTestObjectsForQuery(10); + $subQuery = new ParseQuery("ChildObject"); + $subQuery->greaterThan("x", 5); + $query = new ParseQuery("ParentObject"); + $query->matchesQuery("child", $subQuery); + $results = $query->find(); + + $this->assertEquals(4, count($results), 'Did not return correct number of objects.'); - foreach ($results as $parentObj) { - $this->assertGreaterThan(15, $parentObj->get("x"), + foreach ($results as $parentObj) { + $this->assertGreaterThan(15, $parentObj->get("x"), 'Did not return the correct object.'); + } } - } - public function testDoesNotMatchQuery() - { - ParseTestHelper::clearClass("ChildObject"); - ParseTestHelper::clearClass("ParentObject"); - $this->provideTestObjectsForQuery(10); - $subQuery = new ParseQuery("ChildObject"); - $subQuery->greaterThan("x", 5); - $query = new ParseQuery("ParentObject"); - $query->doesNotMatchQuery("child", $subQuery); - $results = $query->find(); - - $this->assertEquals(6, count($results), + public function testDoesNotMatchQuery() + { + ParseTestHelper::clearClass("ChildObject"); + ParseTestHelper::clearClass("ParentObject"); + $this->provideTestObjectsForQuery(10); + $subQuery = new ParseQuery("ChildObject"); + $subQuery->greaterThan("x", 5); + $query = new ParseQuery("ParentObject"); + $query->doesNotMatchQuery("child", $subQuery); + $results = $query->find(); + + $this->assertEquals(6, count($results), 'Did not return the correct object.'); - foreach ($results as $parentObj) { - $this->assertLessThanOrEqual(15, $parentObj->get("x"), + foreach ($results as $parentObj) { + $this->assertLessThanOrEqual(15, $parentObj->get("x"), 'Did not return the correct object.'); - $this->assertGreaterThanOrEqual(10, $parentObj->get("x"), + $this->assertGreaterThanOrEqual(10, $parentObj->get("x"), 'Did not return the correct object.'); + } } - } - public function provideTestObjectsForKeyInQuery() - { - ParseTestHelper::clearClass("Restaurant"); - ParseTestHelper::clearClass("Person"); - $restaurantLocations = ["Djibouti", "Ouagadougou"]; - $restaurantRatings = [5, 3]; - $numberOFRestaurantObjects = count($restaurantLocations); + public function provideTestObjectsForKeyInQuery() + { + ParseTestHelper::clearClass("Restaurant"); + ParseTestHelper::clearClass("Person"); + $restaurantLocations = ["Djibouti", "Ouagadougou"]; + $restaurantRatings = [5, 3]; + $numberOFRestaurantObjects = count($restaurantLocations); - $personHomeTown = ["Djibouti", "Ouagadougou", "Detroit"]; - $personName = ["Bob", "Tom", "Billy"]; - $numberOfPersonObjects = count($personHomeTown); + $personHomeTown = ["Djibouti", "Ouagadougou", "Detroit"]; + $personName = ["Bob", "Tom", "Billy"]; + $numberOfPersonObjects = count($personHomeTown); - $this->saveObjects($numberOFRestaurantObjects, function ($i) use ($restaurantRatings, $restaurantLocations) { + $this->saveObjects($numberOFRestaurantObjects, function ($i) use ($restaurantRatings, $restaurantLocations) { $restaurant = ParseObject::create("Restaurant"); $restaurant->set("ratings", $restaurantRatings[$i]); $restaurant->set("location", $restaurantLocations[$i]); + return $restaurant; }); - $this->saveObjects($numberOfPersonObjects, function ($i) use ($personHomeTown, $personName) { + $this->saveObjects($numberOfPersonObjects, function ($i) use ($personHomeTown, $personName) { $person = ParseObject::create("Person"); $person->set("hometown", $personHomeTown[$i]); $person->set("name", $personName[$i]); + return $person; }); - } + } - public function testMatchesKeyInQuery() - { - $this->provideTestObjectsForKeyInQuery(); - $subQuery = new ParseQuery("Restaurant"); - $subQuery->greaterThan("ratings", 4); + public function testMatchesKeyInQuery() + { + $this->provideTestObjectsForKeyInQuery(); + $subQuery = new ParseQuery("Restaurant"); + $subQuery->greaterThan("ratings", 4); - $query = new ParseQuery("Person"); - $query->matchesKeyInQuery("hometown", "location", $subQuery); - $results = $query->find(); + $query = new ParseQuery("Person"); + $query->matchesKeyInQuery("hometown", "location", $subQuery); + $results = $query->find(); - $this->assertEquals(1, count($results), + $this->assertEquals(1, count($results), 'Did not return correct number of objects.'); - $this->assertEquals("Bob", $results[0]->get("name"), + $this->assertEquals("Bob", $results[0]->get("name"), 'Did not return the correct object.'); - } + } - public function testDoesNotMatchKeyInQuery() - { - $this->provideTestObjectsForKeyInQuery(); - $subQuery = new ParseQuery("Restaurant"); - $subQuery->greaterThanOrEqualTo("ratings", 3); + public function testDoesNotMatchKeyInQuery() + { + $this->provideTestObjectsForKeyInQuery(); + $subQuery = new ParseQuery("Restaurant"); + $subQuery->greaterThanOrEqualTo("ratings", 3); - $query = new ParseQuery("Person"); - $query->doesNotmatchKeyInQuery("hometown", "location", $subQuery); - $results = $query->find(); + $query = new ParseQuery("Person"); + $query->doesNotmatchKeyInQuery("hometown", "location", $subQuery); + $results = $query->find(); - $this->assertEquals(1, count($results), + $this->assertEquals(1, count($results), 'Did not return correct number of objects.'); - $this->assertEquals("Billy", $results[0]->get("name"), + $this->assertEquals("Billy", $results[0]->get("name"), 'Did not return the correct object.'); - } + } - public function testOrQueries() - { - $this->provideTestObjects(10); - $subQuery1 = new ParseQuery("TestObject"); - $subQuery1->lessThan("foo", "bar2"); - $subQuery2 = new ParseQuery("TestObject"); - $subQuery2->greaterThan("foo", "bar5"); - - $mainQuery = ParseQuery::orQueries([$subQuery1, $subQuery2]); - $results = $mainQuery->find(); - $length = count($results); - $this->assertEquals(6, $length, + public function testOrQueries() + { + $this->provideTestObjects(10); + $subQuery1 = new ParseQuery("TestObject"); + $subQuery1->lessThan("foo", "bar2"); + $subQuery2 = new ParseQuery("TestObject"); + $subQuery2->greaterThan("foo", "bar5"); + + $mainQuery = ParseQuery::orQueries([$subQuery1, $subQuery2]); + $results = $mainQuery->find(); + $length = count($results); + $this->assertEquals(6, $length, 'Did not return correct number of objects.'); - for ($i = 0; $i < $length; $i++) { - $this->assertTrue($results[$i]->get("foo") < "bar2" || + for ($i = 0; $i < $length; $i++) { + $this->assertTrue($results[$i]->get("foo") < "bar2" || $results[$i]->get("foo") > "bar5", 'Did not return the correct object.'); + } } - } - public function testComplexQueries() - { - ParseTestHelper::clearClass("Child"); - ParseTestHelper::clearClass("Parent"); - $this->saveObjects(10, function ($i) { + public function testComplexQueries() + { + ParseTestHelper::clearClass("Child"); + ParseTestHelper::clearClass("Parent"); + $this->saveObjects(10, function ($i) { $child = new ParseObject("Child"); $child->set("x", $i); $parent = new ParseObject("Parent"); $parent->set("y", $i); $parent->set("child", $child); + return $parent; }); - $subQuery = new ParseQuery("Child"); - $subQuery->equalTo("x", 4); - $query1 = new ParseQuery("Parent"); - $query1->matchesQuery("child", $subQuery); - $query2 = new ParseQuery("Parent"); - $query2->lessThan("y", 2); - - $orQuery = ParseQuery::orQueries([$query1, $query2]); - $results = $orQuery->find(); - $this->assertEquals(3, count($results), + $subQuery = new ParseQuery("Child"); + $subQuery->equalTo("x", 4); + $query1 = new ParseQuery("Parent"); + $query1->matchesQuery("child", $subQuery); + $query2 = new ParseQuery("Parent"); + $query2->lessThan("y", 2); + + $orQuery = ParseQuery::orQueries([$query1, $query2]); + $results = $orQuery->find(); + $this->assertEquals(3, count($results), 'Did not return correct number of objects.'); - } + } - public function testEach() - { - ParseTestHelper::clearClass("Object"); - $total = 50; - $count = 25; - $this->saveObjects($total, function ($i) { + public function testEach() + { + ParseTestHelper::clearClass("Object"); + $total = 50; + $count = 25; + $this->saveObjects($total, function ($i) { $obj = new ParseObject("Object"); $obj->set("x", $i + 1); + return $obj; }); - $query = new ParseQuery("Object"); - $query->lessThanOrEqualTo("x", $count); + $query = new ParseQuery("Object"); + $query->lessThanOrEqualTo("x", $count); - $values = array(); - $query->each(function ($obj) use (&$values) { + $values = []; + $query->each(function ($obj) use (&$values) { $values[] = $obj->get("x"); }, 10); - $valuesLength = count($values); - $this->assertEquals($count, $valuesLength, + $valuesLength = count($values); + $this->assertEquals($count, $valuesLength, 'Did not return correct number of objects.'); - sort($values); - for ($i = 0; $i < $valuesLength; $i++) { - $this->assertEquals($i + 1, $values[$i], + sort($values); + for ($i = 0; $i < $valuesLength; $i++) { + $this->assertEquals($i + 1, $values[$i], 'Did not return the correct object.'); + } } - } - public function testEachFailsWithOrder() - { - ParseTestHelper::clearClass("Object"); - $total = 50; - $count = 25; - $this->saveObjects($total, function ($i) { + public function testEachFailsWithOrder() + { + ParseTestHelper::clearClass("Object"); + $total = 50; + $count = 25; + $this->saveObjects($total, function ($i) { $obj = new ParseObject("Object"); $obj->set("x", $i + 1); + return $obj; }); - $query = new ParseQuery("Object"); - $query->lessThanOrEqualTo("x", $count); - $query->ascending("x"); - $this->setExpectedException('\Exception', 'sort'); - $query->each(function ($obj) { + $query = new ParseQuery("Object"); + $query->lessThanOrEqualTo("x", $count); + $query->ascending("x"); + $this->setExpectedException('\Exception', 'sort'); + $query->each(function ($obj) { }); - } + } - public function testEachFailsWithSkip() - { - $total = 50; - $count = 25; - $this->saveObjects($total, function ($i) { + public function testEachFailsWithSkip() + { + $total = 50; + $count = 25; + $this->saveObjects($total, function ($i) { $obj = new ParseObject("Object"); $obj->set("x", $i + 1); + return $obj; }); - $query = new ParseQuery("Object"); - $query->lessThanOrEqualTo("x", $count); - $query->skip(5); - $this->setExpectedException('\Exception', 'skip'); - $query->each(function ($obj) { + $query = new ParseQuery("Object"); + $query->lessThanOrEqualTo("x", $count); + $query->skip(5); + $this->setExpectedException('\Exception', 'skip'); + $query->each(function ($obj) { }); - } + } - public function testEachFailsWithLimit() - { - $total = 50; - $count = 25; - $this->saveObjects($total, function ($i) { + public function testEachFailsWithLimit() + { + $total = 50; + $count = 25; + $this->saveObjects($total, function ($i) { $obj = new ParseObject("Object"); $obj->set("x", $i + 1); + return $obj; }); - $query = new ParseQuery("Object"); - $query->lessThanOrEqualTo("x", $count); - $query->limit(5); - $this->setExpectedException('\Exception', 'limit'); - $query->each(function ($obj) { + $query = new ParseQuery("Object"); + $query->lessThanOrEqualTo("x", $count); + $query->limit(5); + $this->setExpectedException('\Exception', 'limit'); + $query->each(function ($obj) { }); - } + } - public function testContainsAllNumberArrayQueries() - { - ParseTestHelper::clearClass("NumberSet"); - $numberSet1 = new ParseObject("NumberSet"); - $numberSet1->setArray("numbers", [1, 2, 3, 4, 5]); - $numberSet2 = new ParseObject("NumberSet"); - $numberSet2->setArray("numbers", [1, 3, 4, 5]); - $numberSet1->save(); - $numberSet2->save(); - - $query = new ParseQuery("NumberSet"); - $query->containsAll("numbers", [1, 2, 3]); - $results = $query->find(); - $this->assertEquals(1, count($results), + public function testContainsAllNumberArrayQueries() + { + ParseTestHelper::clearClass("NumberSet"); + $numberSet1 = new ParseObject("NumberSet"); + $numberSet1->setArray("numbers", [1, 2, 3, 4, 5]); + $numberSet2 = new ParseObject("NumberSet"); + $numberSet2->setArray("numbers", [1, 3, 4, 5]); + $numberSet1->save(); + $numberSet2->save(); + + $query = new ParseQuery("NumberSet"); + $query->containsAll("numbers", [1, 2, 3]); + $results = $query->find(); + $this->assertEquals(1, count($results), 'Did not return correct number of objects.'); - } + } - public function testContainsAllStringArrayQueries() - { - ParseTestHelper::clearClass("StringSet"); - $stringSet1 = new ParseObject("StringSet"); - $stringSet1->setArray("strings", ["a", "b", "c", "d", "e"]); - $stringSet1->save(); - $stringSet2 = new ParseObject("StringSet"); - $stringSet2->setArray("strings", ["a", "c", "d", "e"]); - $stringSet2->save(); - - $query = new ParseQuery("StringSet"); - $query->containsAll("strings", ["a", "b", "c"]); - $results = $query->find(); - $this->assertEquals(1, count($results), + public function testContainsAllStringArrayQueries() + { + ParseTestHelper::clearClass("StringSet"); + $stringSet1 = new ParseObject("StringSet"); + $stringSet1->setArray("strings", ["a", "b", "c", "d", "e"]); + $stringSet1->save(); + $stringSet2 = new ParseObject("StringSet"); + $stringSet2->setArray("strings", ["a", "c", "d", "e"]); + $stringSet2->save(); + + $query = new ParseQuery("StringSet"); + $query->containsAll("strings", ["a", "b", "c"]); + $results = $query->find(); + $this->assertEquals(1, count($results), 'Did not return correct number of objects.'); - } + } - public function testContainsAllDateArrayQueries() - { - ParseTestHelper::clearClass("DateSet"); - $dates1 = array( + public function testContainsAllDateArrayQueries() + { + ParseTestHelper::clearClass("DateSet"); + $dates1 = [ new DateTime("2013-02-01T00:00:00Z"), new DateTime("2013-02-02T00:00:00Z"), new DateTime("2013-02-03T00:00:00Z"), - new DateTime("2013-02-04T00:00:00Z") - ); - $dates2 = array( + new DateTime("2013-02-04T00:00:00Z"), + ]; + $dates2 = [ new DateTime("2013-02-01T00:00:00Z"), new DateTime("2013-02-03T00:00:00Z"), - new DateTime("2013-02-04T00:00:00Z") - ); - - $obj1 = ParseObject::create("DateSet"); - $obj1->setArray("dates", $dates1); - $obj1->save(); - $obj2 = ParseObject::create("DateSet"); - $obj2->setArray("dates", $dates2); - $obj2->save(); - - $query = new ParseQuery("DateSet"); - $query->containsAll("dates", array( + new DateTime("2013-02-04T00:00:00Z"), + ]; + + $obj1 = ParseObject::create("DateSet"); + $obj1->setArray("dates", $dates1); + $obj1->save(); + $obj2 = ParseObject::create("DateSet"); + $obj2->setArray("dates", $dates2); + $obj2->save(); + + $query = new ParseQuery("DateSet"); + $query->containsAll("dates", [ new DateTime("2013-02-01T00:00:00Z"), new DateTime("2013-02-02T00:00:00Z"), - new DateTime("2013-02-03T00:00:00Z") - )); - $result = $query->find(); - $this->assertEquals(1, count($result), + new DateTime("2013-02-03T00:00:00Z"), + ]); + $result = $query->find(); + $this->assertEquals(1, count($result), 'Did not return correct number of objects.'); - } + } - public function testContainsAllObjectArrayQueries() - { - ParseTestHelper::clearClass("MessageSet"); - $messageList = array(); - $this->saveObjects(4, function ($i) use (&$messageList) { + public function testContainsAllObjectArrayQueries() + { + ParseTestHelper::clearClass("MessageSet"); + $messageList = []; + $this->saveObjects(4, function ($i) use (&$messageList) { $messageList[] = ParseObject::create("TestObject"); $messageList[$i]->set("i", $i); + return $messageList[$i]; }); - $messageSet1 = ParseObject::create("MessageSet"); - $messageSet1->setArray("messages", $messageList); - $messageSet1->save(); - $messageSet2 = ParseObject::create("MessageSet"); - $messageSet2->setArray("message", - array($messageList[0], $messageList[1], $messageList[3]) + $messageSet1 = ParseObject::create("MessageSet"); + $messageSet1->setArray("messages", $messageList); + $messageSet1->save(); + $messageSet2 = ParseObject::create("MessageSet"); + $messageSet2->setArray("message", + [$messageList[0], $messageList[1], $messageList[3]] ); - $messageSet2->save(); + $messageSet2->save(); - $query = new ParseQuery("MessageSet"); - $query->containsAll("messages", array($messageList[0], $messageList[2])); - $results = $query->find(); - $this->assertEquals(1, count($results), + $query = new ParseQuery("MessageSet"); + $query->containsAll("messages", [$messageList[0], $messageList[2]]); + $results = $query->find(); + $this->assertEquals(1, count($results), 'Did not return correct number of objects.'); - } + } - public function testContainedInObjectArrayQueries() - { - $messageList = array(); - $this->saveObjects(4, function ($i) use (&$messageList) { + public function testContainedInObjectArrayQueries() + { + $messageList = []; + $this->saveObjects(4, function ($i) use (&$messageList) { $message = ParseObject::create("TestObject"); if ($i > 0) { - $message->set("prior", $messageList[$i - 1]); + $message->set("prior", $messageList[$i - 1]); } $messageList[] = $message; + return $message; }); - $query = new ParseQuery("TestObject"); - $query->containedIn("prior", array($messageList[0], $messageList[2])); - $results = $query->find(); - $this->assertEquals(2, count($results), + $query = new ParseQuery("TestObject"); + $query->containedIn("prior", [$messageList[0], $messageList[2]]); + $results = $query->find(); + $this->assertEquals(2, count($results), 'Did not return correct number of objects.'); - } + } - public function testContainedInQueries() - { - ParseTestHelper::clearClass("BoxedNumber"); - $this->saveObjects(10, function ($i) { + public function testContainedInQueries() + { + ParseTestHelper::clearClass("BoxedNumber"); + $this->saveObjects(10, function ($i) { $boxedNumber = ParseObject::create("BoxedNumber"); $boxedNumber->set("number", $i); + return $boxedNumber; }); - $query = new ParseQuery("BoxedNumber"); - $query->containedIn("number", [3, 5, 7, 9, 11]); - $results = $query->find(); - $this->assertEquals(4, count($results), + $query = new ParseQuery("BoxedNumber"); + $query->containedIn("number", [3, 5, 7, 9, 11]); + $results = $query->find(); + $this->assertEquals(4, count($results), 'Did not return correct number of objects.'); - } + } - public function testNotContainedInQueries() - { - ParseTestHelper::clearClass("BoxedNumber"); - $this->saveObjects(10, function ($i) { + public function testNotContainedInQueries() + { + ParseTestHelper::clearClass("BoxedNumber"); + $this->saveObjects(10, function ($i) { $boxedNumber = ParseObject::create("BoxedNumber"); $boxedNumber->set("number", $i); + return $boxedNumber; }); - $query = new ParseQuery("BoxedNumber"); - $query->notContainedIn("number", [3, 5, 7, 9, 11]); - $results = $query->find(); - $this->assertEquals(6, count($results), + $query = new ParseQuery("BoxedNumber"); + $query->notContainedIn("number", [3, 5, 7, 9, 11]); + $results = $query->find(); + $this->assertEquals(6, count($results), 'Did not return correct number of objects.'); - } + } - public function testObjectIdContainedInQueries() - { - ParseTestHelper::clearClass("BoxedNumber"); - $objects = array(); - $this->saveObjects(5, function ($i) use (&$objects) { + public function testObjectIdContainedInQueries() + { + ParseTestHelper::clearClass("BoxedNumber"); + $objects = []; + $this->saveObjects(5, function ($i) use (&$objects) { $boxedNumber = ParseObject::create("BoxedNumber"); $boxedNumber->set("number", $i); $objects[] = $boxedNumber; + return $boxedNumber; }); - $query = new ParseQuery("BoxedNumber"); - $query->containedIn("objectId", [$objects[2]->getObjectId(), + $query = new ParseQuery("BoxedNumber"); + $query->containedIn("objectId", [$objects[2]->getObjectId(), $objects[3]->getObjectId(), $objects[0]->getObjectId(), - "NONSENSE"] + "NONSENSE", ] ); - $query->ascending("number"); - $results = $query->find(); - $this->assertEquals(3, count($results), + $query->ascending("number"); + $results = $query->find(); + $this->assertEquals(3, count($results), 'Did not return correct number of objects.'); - $this->assertEquals(0, $results[0]->get("number"), + $this->assertEquals(0, $results[0]->get("number"), 'Did not return the correct object.'); - $this->assertEquals(2, $results[1]->get("number"), + $this->assertEquals(2, $results[1]->get("number"), 'Did not return the correct object.'); - $this->assertEquals(3, $results[2]->get("number"), + $this->assertEquals(3, $results[2]->get("number"), 'Did not return the correct object.'); - } + } - public function testStartsWith() - { - $someAscii = "\\E' !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTU" . + public function testStartsWith() + { + $someAscii = "\\E' !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTU". "VWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'"; - $prefixes = ['zax', 'start', '', '']; - $suffixes = ['qub', '', 'end', '']; - $this->saveObjects(4, function ($i) use ($prefixes, $suffixes, $someAscii) { + $prefixes = ['zax', 'start', '', '']; + $suffixes = ['qub', '', 'end', '']; + $this->saveObjects(4, function ($i) use ($prefixes, $suffixes, $someAscii) { $obj = ParseObject::create("TestObject"); - $obj->set("myString", $prefixes[$i] . $someAscii . $suffixes[$i]); + $obj->set("myString", $prefixes[$i].$someAscii.$suffixes[$i]); + return $obj; }); - $query = new ParseQuery("TestObject"); - $query->startsWith("myString", $someAscii); - $results = $query->find(); - $this->assertEquals(2, count($results), + $query = new ParseQuery("TestObject"); + $query->startsWith("myString", $someAscii); + $results = $query->find(); + $this->assertEquals(2, count($results), 'Did not return correct number of objects.'); - } + } - public function provideTestObjectsForOrderBy() - { - ParseTestHelper::clearClass("BoxedNumber"); - $strings = ['a', 'b', 'c', 'd']; - $numbers = [3, 1, 3, 2]; - for ($i = 0; $i < 4; $i++) { - $obj = ParseObject::create("BoxedNumber"); - $obj->set('string', $strings[$i]); - $obj->set('number', $numbers[$i]); - $obj->save(); + public function provideTestObjectsForOrderBy() + { + ParseTestHelper::clearClass("BoxedNumber"); + $strings = ['a', 'b', 'c', 'd']; + $numbers = [3, 1, 3, 2]; + for ($i = 0; $i < 4; $i++) { + $obj = ParseObject::create("BoxedNumber"); + $obj->set('string', $strings[$i]); + $obj->set('number', $numbers[$i]); + $obj->save(); + } } - } - public function testOrderByAscNumberThenDescString() - { - $this->provideTestObjectsForOrderBy(); - $query = new ParseQuery("BoxedNumber"); - $query->ascending('number')->addDescending('string'); - $results = $query->find(); - $expected = [[1, 'b'], [2, 'd'], [3, 'c'], [3, 'a']]; - $this->assertEquals(4, count($results), + public function testOrderByAscNumberThenDescString() + { + $this->provideTestObjectsForOrderBy(); + $query = new ParseQuery("BoxedNumber"); + $query->ascending('number')->addDescending('string'); + $results = $query->find(); + $expected = [[1, 'b'], [2, 'd'], [3, 'c'], [3, 'a']]; + $this->assertEquals(4, count($results), 'Did not return correct number of objects.'); - for ($i = 0; $i < 4; $i++) { - $this->assertEquals($expected[$i][0], $results[$i]->get('number'), + for ($i = 0; $i < 4; $i++) { + $this->assertEquals($expected[$i][0], $results[$i]->get('number'), 'Did not return the correct object.'); - $this->assertEquals($expected[$i][1], $results[$i]->get('string'), + $this->assertEquals($expected[$i][1], $results[$i]->get('string'), 'Did not return the correct object.'); + } } - } - public function testOrderByDescNumberThenAscString() - { - $this->provideTestObjectsForOrderBy(); - $query = new ParseQuery("BoxedNumber"); - $query->descending('number')->addAscending('string'); - $results = $query->find(); - $expected = [[3, 'a'], [3, 'c'], [2, 'd'], [1, 'b']]; - $this->assertEquals(4, count($results), + public function testOrderByDescNumberThenAscString() + { + $this->provideTestObjectsForOrderBy(); + $query = new ParseQuery("BoxedNumber"); + $query->descending('number')->addAscending('string'); + $results = $query->find(); + $expected = [[3, 'a'], [3, 'c'], [2, 'd'], [1, 'b']]; + $this->assertEquals(4, count($results), 'Did not return correct number of objects.'); - for ($i = 0; $i < 4; $i++) { - $this->assertEquals($expected[$i][0], $results[$i]->get('number'), + for ($i = 0; $i < 4; $i++) { + $this->assertEquals($expected[$i][0], $results[$i]->get('number'), 'Did not return the correct object.'); - $this->assertEquals($expected[$i][1], $results[$i]->get('string'), + $this->assertEquals($expected[$i][1], $results[$i]->get('string'), 'Did not return the correct object.'); + } } - } - public function testOrderByDescNumberAndString() - { - $this->provideTestObjectsForOrderBy(); - $query = new ParseQuery("BoxedNumber"); - $query->descending(['number', 'string']); - $results = $query->find(); - $expected = [[3, 'c'], [3, 'a'], [2, 'd'], [1, 'b']]; - $this->assertEquals(4, count($results), + public function testOrderByDescNumberAndString() + { + $this->provideTestObjectsForOrderBy(); + $query = new ParseQuery("BoxedNumber"); + $query->descending(['number', 'string']); + $results = $query->find(); + $expected = [[3, 'c'], [3, 'a'], [2, 'd'], [1, 'b']]; + $this->assertEquals(4, count($results), 'Did not return correct number of objects.'); - for ($i = 0; $i < 4; $i++) { - $this->assertEquals($expected[$i][0], $results[$i]->get('number'), + for ($i = 0; $i < 4; $i++) { + $this->assertEquals($expected[$i][0], $results[$i]->get('number'), 'Did not return the correct object.'); - $this->assertEquals($expected[$i][1], $results[$i]->get('string'), + $this->assertEquals($expected[$i][1], $results[$i]->get('string'), 'Did not return the correct object.'); + } } - } - public function testCannotOrderByPassword() - { - $this->provideTestObjectsForOrderBy(); - $query = new ParseQuery("BoxedNumber"); - $query->ascending('_password'); - $this->setExpectedException('Parse\ParseException', "", 105); - $query->find(); - } + public function testCannotOrderByPassword() + { + $this->provideTestObjectsForOrderBy(); + $query = new ParseQuery("BoxedNumber"); + $query->ascending('_password'); + $this->setExpectedException('Parse\ParseException', "", 105); + $query->find(); + } - public function testOrderByCreatedAtAsc() - { - $this->provideTestObjectsForOrderBy(); - $query = new ParseQuery("BoxedNumber"); - $query->ascending('createdAt'); - $query->find(); - $results = $query->find(); - $this->assertEquals(4, count($results), + public function testOrderByCreatedAtAsc() + { + $this->provideTestObjectsForOrderBy(); + $query = new ParseQuery("BoxedNumber"); + $query->ascending('createdAt'); + $query->find(); + $results = $query->find(); + $this->assertEquals(4, count($results), 'Did not return correct number of objects.'); - $expected = [3, 1, 3, 2]; - for ($i = 0; $i < 4; $i++) { - $this->assertEquals($expected[$i], $results[$i]->get('number'), + $expected = [3, 1, 3, 2]; + for ($i = 0; $i < 4; $i++) { + $this->assertEquals($expected[$i], $results[$i]->get('number'), 'Did not return the correct object.'); + } } - } - public function testOrderByCreatedAtDesc() - { - $this->provideTestObjectsForOrderBy(); - $query = new ParseQuery("BoxedNumber"); - $query->descending('createdAt'); - $query->find(); - $results = $query->find(); - $this->assertEquals(4, count($results), + public function testOrderByCreatedAtDesc() + { + $this->provideTestObjectsForOrderBy(); + $query = new ParseQuery("BoxedNumber"); + $query->descending('createdAt'); + $query->find(); + $results = $query->find(); + $this->assertEquals(4, count($results), 'Did not return correct number of objects.'); - $expected = [2, 3, 1, 3]; - for ($i = 0; $i < 4; $i++) { - $this->assertEquals($expected[$i], $results[$i]->get('number'), + $expected = [2, 3, 1, 3]; + for ($i = 0; $i < 4; $i++) { + $this->assertEquals($expected[$i], $results[$i]->get('number'), 'Did not return the correct object.'); + } } - } - public function testOrderByUpdatedAtAsc() - { - $numbers = [3, 1, 2]; - $objects = array(); - $this->saveObjects(3, function ($i) use ($numbers, &$objects) { + public function testOrderByUpdatedAtAsc() + { + $numbers = [3, 1, 2]; + $objects = []; + $this->saveObjects(3, function ($i) use ($numbers, &$objects) { $obj = ParseObject::create("TestObject"); $obj->set('number', $numbers[$i]); $objects[] = $obj; + return $obj; }); - $objects[1]->set('number', 4); - $objects[1]->save(); - $query = new ParseQuery("TestObject"); - $query->ascending('updatedAt'); - $results = $query->find(); - $this->assertEquals(3, count($results), + $objects[1]->set('number', 4); + $objects[1]->save(); + $query = new ParseQuery("TestObject"); + $query->ascending('updatedAt'); + $results = $query->find(); + $this->assertEquals(3, count($results), 'Did not return correct number of objects.'); - $expected = [3, 2, 4]; - for ($i = 0; $i < 3; $i++) { - $this->assertEquals($expected[$i], $results[$i]->get('number'), + $expected = [3, 2, 4]; + for ($i = 0; $i < 3; $i++) { + $this->assertEquals($expected[$i], $results[$i]->get('number'), 'Did not return the correct object.'); + } } - } - public function testOrderByUpdatedAtDesc() - { - $numbers = [3, 1, 2]; - $objects = array(); - $this->saveObjects(3, function ($i) use ($numbers, &$objects) { + public function testOrderByUpdatedAtDesc() + { + $numbers = [3, 1, 2]; + $objects = []; + $this->saveObjects(3, function ($i) use ($numbers, &$objects) { $obj = ParseObject::create("TestObject"); $obj->set('number', $numbers[$i]); $objects[] = $obj; + return $obj; }); - $objects[1]->set('number', 4); - $objects[1]->save(); - $query = new ParseQuery("TestObject"); - $query->descending('updatedAt'); - $results = $query->find(); - $this->assertEquals(3, count($results), + $objects[1]->set('number', 4); + $objects[1]->save(); + $query = new ParseQuery("TestObject"); + $query->descending('updatedAt'); + $results = $query->find(); + $this->assertEquals(3, count($results), 'Did not return correct number of objects.'); - $expected = [4, 2, 3]; - for ($i = 0; $i < 3; $i++) { - $this->assertEquals($expected[$i], $results[$i]->get('number'), + $expected = [4, 2, 3]; + for ($i = 0; $i < 3; $i++) { + $this->assertEquals($expected[$i], $results[$i]->get('number'), 'Did not return the correct object.'); + } } - } - public function testSelectKeysQuery() - { - $obj = ParseObject::create("TestObject"); - $obj->set('foo', 'baz'); - $obj->set('bar', 1); - $obj->save(); - $query = new ParseQuery("TestObject"); - $query->select('foo'); - $result = $query->first(); - $this->assertEquals('baz', $result->get('foo'), + public function testSelectKeysQuery() + { + $obj = ParseObject::create("TestObject"); + $obj->set('foo', 'baz'); + $obj->set('bar', 1); + $obj->save(); + $query = new ParseQuery("TestObject"); + $query->select('foo'); + $result = $query->first(); + $this->assertEquals('baz', $result->get('foo'), 'Did not return the correct object.'); - $this->setExpectedException('\Exception', 'Call fetch()'); - $result->get('bar'); - - } + $this->setExpectedException('\Exception', 'Call fetch()'); + $result->get('bar'); + } - public function testGetWithoutError() - { - $obj = ParseObject::create("TestObject"); - $obj->set('foo', 'baz'); - $obj->set('bar', 1); - $this->assertEquals('baz', $obj->get('foo'), + public function testGetWithoutError() + { + $obj = ParseObject::create("TestObject"); + $obj->set('foo', 'baz'); + $obj->set('bar', 1); + $this->assertEquals('baz', $obj->get('foo'), 'Did not return the correct object.'); - $this->assertEquals(1, $obj->get('bar'), + $this->assertEquals(1, $obj->get('bar'), 'Did not return the correct object.'); - $obj->save(); - } - public function testSelectKeysQueryArrayArg() - { - $obj = ParseObject::create("TestObject"); - $obj->set('foo', 'baz'); - $obj->set('bar', 1); - $obj->save(); - $query = new ParseQuery("TestObject"); - $query->select(['foo', 'bar']); - $result = $query->first(); - $this->assertEquals('baz', $result->get('foo'), + $obj->save(); + } + public function testSelectKeysQueryArrayArg() + { + $obj = ParseObject::create("TestObject"); + $obj->set('foo', 'baz'); + $obj->set('bar', 1); + $obj->save(); + $query = new ParseQuery("TestObject"); + $query->select(['foo', 'bar']); + $result = $query->first(); + $this->assertEquals('baz', $result->get('foo'), 'Did not return the correct object.'); - $this->assertEquals(1, $result->get('bar'), + $this->assertEquals(1, $result->get('bar'), 'Did not return the correct object.'); + } - } - - public function testExists() - { - $this->saveObjects(9, function ($i) { + public function testExists() + { + $this->saveObjects(9, function ($i) { $obj = ParseObject::create("TestObject"); if ($i & 1) { - $obj->set('y', $i); + $obj->set('y', $i); } else { - $obj->set('x', $i); + $obj->set('x', $i); } + return $obj; }); - $query = new ParseQuery("TestObject"); - $query->exists('x'); - $results = $query->find(); - $this->assertEquals(5, count($results), + $query = new ParseQuery("TestObject"); + $query->exists('x'); + $results = $query->find(); + $this->assertEquals(5, count($results), 'Did not return correct number of objects.'); - } + } - public function testDoesNotExist() - { - $this->saveObjects(9, function ($i) { + public function testDoesNotExist() + { + $this->saveObjects(9, function ($i) { $obj = ParseObject::create("TestObject"); if ($i & 1) { - $obj->set('y', $i); + $obj->set('y', $i); } else { - $obj->set('x', $i); + $obj->set('x', $i); } + return $obj; }); - $query = new ParseQuery("TestObject"); - $query->doesNotExist('x'); - $results = $query->find(); - $this->assertEquals(4, count($results), + $query = new ParseQuery("TestObject"); + $query->doesNotExist('x'); + $results = $query->find(); + $this->assertEquals(4, count($results), 'Did not return correct number of objects.'); - } + } - public function testExistsRelation() - { - ParseTestHelper::clearClass("Item"); - $this->saveObjects(9, function ($i) { + public function testExistsRelation() + { + ParseTestHelper::clearClass("Item"); + $this->saveObjects(9, function ($i) { $obj = ParseObject::create("TestObject"); if ($i & 1) { - $obj->set('y', $i); + $obj->set('y', $i); } else { - $item = ParseObject::create("Item"); - $item->set('e', $i); - $obj->set('e', $item); + $item = ParseObject::create("Item"); + $item->set('e', $i); + $obj->set('e', $item); } + return $obj; }); - $query = new ParseQuery("TestObject"); - $query->exists('e'); - $results = $query->find(); - $this->assertEquals(5, count($results), + $query = new ParseQuery("TestObject"); + $query->exists('e'); + $results = $query->find(); + $this->assertEquals(5, count($results), 'Did not return correct number of objects.'); - } + } - public function testDoesNotExistRelation() - { - ParseTestHelper::clearClass("Item"); - $this->saveObjects(9, function ($i) { + public function testDoesNotExistRelation() + { + ParseTestHelper::clearClass("Item"); + $this->saveObjects(9, function ($i) { $obj = ParseObject::create("TestObject"); if ($i & 1) { - $obj->set('y', $i); + $obj->set('y', $i); } else { - $item = ParseObject::create("Item"); - $item->set('x', $i); - $obj->set('x', $i); + $item = ParseObject::create("Item"); + $item->set('x', $i); + $obj->set('x', $i); } + return $obj; }); - $query = new ParseQuery("TestObject"); - $query->doesNotExist('x'); - $results = $query->find(); - $this->assertEquals(4, count($results), + $query = new ParseQuery("TestObject"); + $query->doesNotExist('x'); + $results = $query->find(); + $this->assertEquals(4, count($results), 'Did not return correct number of objects.'); - } + } - public function testDoNotIncludeRelation() - { - $child = ParseObject::create("Child"); - $child->set('x', 1); - $child->save(); - $parent = ParseObject::create("Parent"); - $parent->set('child', $child); - $parent->set('y', 1); - $parent->save(); - $query = new ParseQuery('Parent'); - $result = $query->first(); - $this->setExpectedException('\Exception', 'Call fetch()'); - $result->get('child')->get('x'); - } + public function testDoNotIncludeRelation() + { + $child = ParseObject::create("Child"); + $child->set('x', 1); + $child->save(); + $parent = ParseObject::create("Parent"); + $parent->set('child', $child); + $parent->set('y', 1); + $parent->save(); + $query = new ParseQuery('Parent'); + $result = $query->first(); + $this->setExpectedException('\Exception', 'Call fetch()'); + $result->get('child')->get('x'); + } - public function testIncludeRelation() - { - ParseTestHelper::clearClass("Child"); - ParseTestHelper::clearClass("Parent"); - $child = ParseObject::create("Child"); - $child->set('x', 1); - $child->save(); - $parent = ParseObject::create("Parent"); - $parent->set('child', $child); - $parent->set('y', 1); - $parent->save(); - $query = new ParseQuery('Parent'); - $query->includeKey('child'); - $result = $query->first(); - $this->assertEquals($result->get('y'), $result->get('child')->get('x'), + public function testIncludeRelation() + { + ParseTestHelper::clearClass("Child"); + ParseTestHelper::clearClass("Parent"); + $child = ParseObject::create("Child"); + $child->set('x', 1); + $child->save(); + $parent = ParseObject::create("Parent"); + $parent->set('child', $child); + $parent->set('y', 1); + $parent->save(); + $query = new ParseQuery('Parent'); + $query->includeKey('child'); + $result = $query->first(); + $this->assertEquals($result->get('y'), $result->get('child')->get('x'), 'Object should be fetched.'); - $this->assertEquals(1, $result->get('child')->get('x'), + $this->assertEquals(1, $result->get('child')->get('x'), 'Object should be fetched.'); - } + } - public function testNestedIncludeRelation() - { - ParseTestHelper::clearClass("Child"); - ParseTestHelper::clearClass("Parent"); - ParseTestHelper::clearClass("GrandParent"); - $child = ParseObject::create("Child"); - $child->set('x', 1); - $child->save(); - $parent = ParseObject::create("Parent"); - $parent->set('child', $child); - $parent->set('y', 1); - $parent->save(); - $grandParent = ParseObject::create("GrandParent"); - $grandParent->set('parent', $parent); - $grandParent->set('z', 1); - $grandParent->save(); - - $query = new ParseQuery('GrandParent'); - $query->includeKey('parent.child'); - $result = $query->first(); - $this->assertEquals($result->get('z'), $result->get('parent')->get('y'), + public function testNestedIncludeRelation() + { + ParseTestHelper::clearClass("Child"); + ParseTestHelper::clearClass("Parent"); + ParseTestHelper::clearClass("GrandParent"); + $child = ParseObject::create("Child"); + $child->set('x', 1); + $child->save(); + $parent = ParseObject::create("Parent"); + $parent->set('child', $child); + $parent->set('y', 1); + $parent->save(); + $grandParent = ParseObject::create("GrandParent"); + $grandParent->set('parent', $parent); + $grandParent->set('z', 1); + $grandParent->save(); + + $query = new ParseQuery('GrandParent'); + $query->includeKey('parent.child'); + $result = $query->first(); + $this->assertEquals($result->get('z'), $result->get('parent')->get('y'), 'Object should be fetched.'); - $this->assertEquals($result->get('z'), + $this->assertEquals($result->get('z'), $result->get('parent')->get('child')->get('x'), 'Object should be fetched.'); - } + } - public function testIncludeArrayRelation() - { - ParseTestHelper::clearClass("Child"); - ParseTestHelper::clearClass("Parent"); - $children = array(); - $this->saveObjects(5, function ($i) use (&$children) { + public function testIncludeArrayRelation() + { + ParseTestHelper::clearClass("Child"); + ParseTestHelper::clearClass("Parent"); + $children = []; + $this->saveObjects(5, function ($i) use (&$children) { $child = ParseObject::create("Child"); $child->set('x', $i); $children[] = $child; + return $child; }); - $parent = ParseObject::create("Parent"); - $parent->setArray('children', $children); - $parent->save(); - - $query = new ParseQuery("Parent"); - $query->includeKey('children'); - $result = $query->find(); - $this->assertEquals(1, count($result), + $parent = ParseObject::create("Parent"); + $parent->setArray('children', $children); + $parent->save(); + + $query = new ParseQuery("Parent"); + $query->includeKey('children'); + $result = $query->find(); + $this->assertEquals(1, count($result), 'Did not return correct number of objects.'); - $children = $result[0]->get('children'); - $length = count($children); - for ($i = 0; $i < $length; $i++) { - $this->assertEquals($i, $children[$i]->get('x'), + $children = $result[0]->get('children'); + $length = count($children); + for ($i = 0; $i < $length; $i++) { + $this->assertEquals($i, $children[$i]->get('x'), 'Object should be fetched.'); + } } - } - public function testIncludeWithNoResults() - { - ParseTestHelper::clearClass("Child"); - ParseTestHelper::clearClass("Parent"); - $query = new ParseQuery("Parent"); - $query->includeKey('children'); - $result = $query->find(); - $this->assertEquals(0, count($result), + public function testIncludeWithNoResults() + { + ParseTestHelper::clearClass("Child"); + ParseTestHelper::clearClass("Parent"); + $query = new ParseQuery("Parent"); + $query->includeKey('children'); + $result = $query->find(); + $this->assertEquals(0, count($result), 'Did not return correct number of objects.'); - } + } - public function testIncludeWithNonExistentKey() - { - ParseTestHelper::clearClass("Child"); - ParseTestHelper::clearClass("Parent"); - $parent = ParseObject::create("Parent"); - $parent->set('foo', 'bar'); - $parent->save(); - - $query = new ParseQuery("Parent"); - $query->includeKey('child'); - $results = $query->find(); - $this->assertEquals(1, count($results), + public function testIncludeWithNonExistentKey() + { + ParseTestHelper::clearClass("Child"); + ParseTestHelper::clearClass("Parent"); + $parent = ParseObject::create("Parent"); + $parent->set('foo', 'bar'); + $parent->save(); + + $query = new ParseQuery("Parent"); + $query->includeKey('child'); + $results = $query->find(); + $this->assertEquals(1, count($results), 'Did not return correct number of objects.'); - } + } - public function testIncludeOnTheWrongKeyType() - { - ParseTestHelper::clearClass("Child"); - ParseTestHelper::clearClass("Parent"); - $parent = ParseObject::create("Parent"); - $parent->set('foo', 'bar'); - $parent->save(); - - $query = new ParseQuery("Parent"); - $query->includeKey('foo'); - $this->setExpectedException('Parse\ParseException', '', 102); - $results = $query->find(); - $this->assertEquals(1, count($results), + public function testIncludeOnTheWrongKeyType() + { + ParseTestHelper::clearClass("Child"); + ParseTestHelper::clearClass("Parent"); + $parent = ParseObject::create("Parent"); + $parent->set('foo', 'bar'); + $parent->save(); + + $query = new ParseQuery("Parent"); + $query->includeKey('foo'); + $this->setExpectedException('Parse\ParseException', '', 102); + $results = $query->find(); + $this->assertEquals(1, count($results), 'Did not return correct number of objects.'); - } + } - public function testIncludeWhenOnlySomeObjectsHaveChildren() - { - ParseTestHelper::clearClass("Child"); - ParseTestHelper::clearClass("Parent"); - $child = ParseObject::create('Child'); - $child->set('foo', 'bar'); - $child->save(); - $this->saveObjects(4, function ($i) use ($child) { + public function testIncludeWhenOnlySomeObjectsHaveChildren() + { + ParseTestHelper::clearClass("Child"); + ParseTestHelper::clearClass("Parent"); + $child = ParseObject::create('Child'); + $child->set('foo', 'bar'); + $child->save(); + $this->saveObjects(4, function ($i) use ($child) { $parent = ParseObject::create('Parent'); $parent->set('num', $i); if ($i & 1) { - $parent->set('child', $child); + $parent->set('child', $child); } + return $parent; }); - $query = new ParseQuery('Parent'); - $query->includeKey(['child']); - $query->ascending('num'); - $results = $query->find(); - $this->assertEquals(4, count($results), + $query = new ParseQuery('Parent'); + $query->includeKey(['child']); + $query->ascending('num'); + $results = $query->find(); + $this->assertEquals(4, count($results), 'Did not return correct number of objects.'); - $length = count($results); - for ($i = 0; $i < $length; $i++) { - if ($i & 1) { - $this->assertEquals('bar', $results[$i]->get('child')->get('foo'), + $length = count($results); + for ($i = 0; $i < $length; $i++) { + if ($i & 1) { + $this->assertEquals('bar', $results[$i]->get('child')->get('foo'), 'Object should be fetched'); - } else { - $this->assertEquals(null, $results[$i]->get('child'), + } else { + $this->assertEquals(null, $results[$i]->get('child'), 'Should not have child'); - } + } + } } - } - public function testIncludeMultipleKeys() - { - ParseTestHelper::clearClass("Foo"); - ParseTestHelper::clearClass("Bar"); - ParseTestHelper::clearClass("Parent"); - $foo = ParseObject::create('Foo'); - $foo->set('rev', 'oof'); - $foo->save(); - $bar = ParseObject::create('Bar'); - $bar->set('rev', 'rab'); - $bar->save(); - - $parent = ParseObject::create('Parent'); - $parent->set('foofoo', $foo); - $parent->set('barbar', $bar); - $parent->save(); - - $query = new ParseQuery('Parent'); - $query->includeKey(['foofoo', 'barbar']); - $result = $query->first(); - $this->assertEquals('oof', $result->get('foofoo')->get('rev'), + public function testIncludeMultipleKeys() + { + ParseTestHelper::clearClass("Foo"); + ParseTestHelper::clearClass("Bar"); + ParseTestHelper::clearClass("Parent"); + $foo = ParseObject::create('Foo'); + $foo->set('rev', 'oof'); + $foo->save(); + $bar = ParseObject::create('Bar'); + $bar->set('rev', 'rab'); + $bar->save(); + + $parent = ParseObject::create('Parent'); + $parent->set('foofoo', $foo); + $parent->set('barbar', $bar); + $parent->save(); + + $query = new ParseQuery('Parent'); + $query->includeKey(['foofoo', 'barbar']); + $result = $query->first(); + $this->assertEquals('oof', $result->get('foofoo')->get('rev'), 'Object should be fetched'); - $this->assertEquals('rab', $result->get('barbar')->get('rev'), + $this->assertEquals('rab', $result->get('barbar')->get('rev'), 'Object should be fetched'); - } + } - public function testEqualToObject() - { - ParseTestHelper::clearClass("Item"); - ParseTestHelper::clearClass("Container"); - $items = array(); - $this->saveObjects(2, function ($i) use (&$items) { + public function testEqualToObject() + { + ParseTestHelper::clearClass("Item"); + ParseTestHelper::clearClass("Container"); + $items = []; + $this->saveObjects(2, function ($i) use (&$items) { $items[] = ParseObject::create("Item"); $items[$i]->set('x', $i); + return $items[$i]; }); - $this->saveObjects(2, function ($i) use ($items) { + $this->saveObjects(2, function ($i) use ($items) { $container = ParseObject::create("Container"); $container->set('item', $items[$i]); + return $container; }); - $query = new ParseQuery("Container"); - $query->equalTo('item', $items[0]); - $result = $query->find(); - $this->assertEquals(1, count($result), + $query = new ParseQuery("Container"); + $query->equalTo('item', $items[0]); + $result = $query->find(); + $this->assertEquals(1, count($result), 'Did not return the correct object.'); - } + } - public function testEqualToNull() - { - $this->saveObjects(10, function ($i) { + public function testEqualToNull() + { + $this->saveObjects(10, function ($i) { $obj = ParseObject::create('TestObject'); $obj->set('num', $i); + return $obj; }); - $query = new ParseQuery('TestObject'); - $query->equalTo('num', null); - $results = $query->find(); - $this->assertEquals(0, count($results), + $query = new ParseQuery('TestObject'); + $query->equalTo('num', null); + $results = $query->find(); + $this->assertEquals(0, count($results), 'Did not return correct number of objects.'); - } + } - public function provideTimeTestObjects() - { - ParseTestHelper::clearClass("TimeObject"); - $items = array(); - $this->saveObjects(3, function ($i) use (&$items) { + public function provideTimeTestObjects() + { + ParseTestHelper::clearClass("TimeObject"); + $items = []; + $this->saveObjects(3, function ($i) use (&$items) { $timeObject = ParseObject::create('TimeObject'); - $timeObject->set('name', 'item' . $i); + $timeObject->set('name', 'item'.$i); $timeObject->set('time', new DateTime()); sleep(1); $items[] = $timeObject; + return $timeObject; }); - return $items; - } - public function testTimeEquality() - { - $items = $this->provideTimeTestObjects(); - $query = new ParseQuery('TimeObject'); - $query->equalTo('time', $items[1]->get('time')); - $results = $query->find(); - $this->assertEquals(1, count($results), + return $items; + } + + public function testTimeEquality() + { + $items = $this->provideTimeTestObjects(); + $query = new ParseQuery('TimeObject'); + $query->equalTo('time', $items[1]->get('time')); + $results = $query->find(); + $this->assertEquals(1, count($results), 'Did not return correct number of objects.'); - $this->assertEquals('item1', $results[0]->get('name')); - } + $this->assertEquals('item1', $results[0]->get('name')); + } - public function testTimeLessThan() - { - $items = $this->provideTimeTestObjects(); - $query = new ParseQuery('TimeObject'); - $query->lessThan('time', $items[2]->get('time')); - $results = $query->find(); - $this->assertEquals(2, count($results), + public function testTimeLessThan() + { + $items = $this->provideTimeTestObjects(); + $query = new ParseQuery('TimeObject'); + $query->lessThan('time', $items[2]->get('time')); + $results = $query->find(); + $this->assertEquals(2, count($results), 'Did not return correct number of objects.'); - } + } - public function testRestrictedGetFailsWithoutMasterKey() - { - $obj = ParseObject::create("TestObject"); - $restrictedACL = new ParseACL(); - $obj->setACL($restrictedACL); - $obj->save(); - $query = new ParseQuery("TestObject"); - $this->setExpectedException('Parse\ParseException', 'not found'); - $objAgain = $query->get($obj->getObjectId()); - } + public function testRestrictedGetFailsWithoutMasterKey() + { + $obj = ParseObject::create("TestObject"); + $restrictedACL = new ParseACL(); + $obj->setACL($restrictedACL); + $obj->save(); + $query = new ParseQuery("TestObject"); + $this->setExpectedException('Parse\ParseException', 'not found'); + $objAgain = $query->get($obj->getObjectId()); + } - public function testRestrictedGetWithMasterKey() - { - $obj = ParseObject::create("TestObject"); - $restrictedACL = new ParseACL(); - $obj->setACL($restrictedACL); - $obj->save(); - - $query = new ParseQuery("TestObject"); - $objAgain = $query->get($obj->getObjectId(), true); - $this->assertEquals($obj->getObjectId(), $objAgain->getObjectId()); - } + public function testRestrictedGetWithMasterKey() + { + $obj = ParseObject::create("TestObject"); + $restrictedACL = new ParseACL(); + $obj->setACL($restrictedACL); + $obj->save(); - public function testRestrictedCount() - { - $obj = ParseObject::create("TestObject"); - $restrictedACL = new ParseACL(); - $obj->setACL($restrictedACL); - $obj->save(); - - $query = new ParseQuery("TestObject"); - $count = $query->count(); - $this->assertEquals(0, $count); - $count = $query->count(true); - $this->assertEquals(1, $count); - } + $query = new ParseQuery("TestObject"); + $objAgain = $query->get($obj->getObjectId(), true); + $this->assertEquals($obj->getObjectId(), $objAgain->getObjectId()); + } + public function testRestrictedCount() + { + $obj = ParseObject::create("TestObject"); + $restrictedACL = new ParseACL(); + $obj->setACL($restrictedACL); + $obj->save(); + + $query = new ParseQuery("TestObject"); + $count = $query->count(); + $this->assertEquals(0, $count); + $count = $query->count(true); + $this->assertEquals(1, $count); + } } diff --git a/tests/ParseRelationTest.php b/tests/ParseRelationTest.php index c19a1b17..c0aad55d 100644 --- a/tests/ParseRelationTest.php +++ b/tests/ParseRelationTest.php @@ -2,18 +2,20 @@ use Parse\ParseObject; use Parse\ParseQuery; + require_once 'ParseTestHelper.php'; -class ParseRelationTest extends PHPUnit_Framework_TestCase { +class ParseRelationTest extends PHPUnit_Framework_TestCase +{ public static function setUpBeforeClass() { - ParseTestHelper::setUp(); + ParseTestHelper::setUp(); } - public function tearDown() - { - ParseTestHelper::tearDown(); - } + public function tearDown() + { + ParseTestHelper::tearDown(); + } /** * This function used as a helper function in test functions to save objects. @@ -24,112 +26,110 @@ public function tearDown() */ public function saveObjects($numberOfObjects, $callback) { - $allObjects = array(); - for ($i = 0; $i < $numberOfObjects; $i++) { - $allObjects[] = $callback($i); - } - ParseObject::saveAll($allObjects); + $allObjects = []; + for ($i = 0; $i < $numberOfObjects; $i++) { + $allObjects[] = $callback($i); + } + ParseObject::saveAll($allObjects); } - public function testParseRelations() - { - $children = array(); - $this->saveObjects(10, function ($i) use (&$children) { + public function testParseRelations() + { + $children = []; + $this->saveObjects(10, function ($i) use (&$children) { $child = ParseObject::create('ChildObject'); $child->set('x', $i); $children[] = $child; + return $child; }); - $parent = ParseObject::create('ParentObject'); - $relation = $parent->getRelation('children'); - $relation->add($children[0]); - $parent->set('foo', 1); - $parent->save(); - - $results = $relation->getQuery()->find(); - $this->assertEquals(1, count($results)); - $this->assertEquals($children[0]->getObjectId(), $results[0]->getObjectId()); - $this->assertFalse($parent->isDirty()); - - $parentAgain = (new ParseQuery('ParentObject'))->get($parent->getObjectId()); - $relationAgain = $parentAgain->get('children'); - $this->assertNotNull($relationAgain, 'Error'); - - $results = $relation->getQuery()->find(); - $this->assertEquals(1, count($results)); - $this->assertEquals($children[0]->getObjectId(), $results[0]->getObjectId()); - - $relation->remove($children[0]); - $relation->add([$children[4], $children[5]]); - $parent->set('bar', 3); - $parent->save(); - - - $results = $relation->getQuery()->find(); - $this->assertEquals(2, count($results)); - $this->assertFalse($parent->isDirty()); - - $relation->remove($children[5]); - $relation->add([ + $parent = ParseObject::create('ParentObject'); + $relation = $parent->getRelation('children'); + $relation->add($children[0]); + $parent->set('foo', 1); + $parent->save(); + + $results = $relation->getQuery()->find(); + $this->assertEquals(1, count($results)); + $this->assertEquals($children[0]->getObjectId(), $results[0]->getObjectId()); + $this->assertFalse($parent->isDirty()); + + $parentAgain = (new ParseQuery('ParentObject'))->get($parent->getObjectId()); + $relationAgain = $parentAgain->get('children'); + $this->assertNotNull($relationAgain, 'Error'); + + $results = $relation->getQuery()->find(); + $this->assertEquals(1, count($results)); + $this->assertEquals($children[0]->getObjectId(), $results[0]->getObjectId()); + + $relation->remove($children[0]); + $relation->add([$children[4], $children[5]]); + $parent->set('bar', 3); + $parent->save(); + + $results = $relation->getQuery()->find(); + $this->assertEquals(2, count($results)); + $this->assertFalse($parent->isDirty()); + + $relation->remove($children[5]); + $relation->add([ $children[5], $children[6], $children[7], - $children[8] + $children[8], ]); - $parent->save(); - - $results = $relation->getQuery()->find(); - $this->assertEquals(5, count($results)); - $this->assertFalse($parent->isDirty()); - - $relation->remove($children[8]); - $parent->save(); - $results = $relation->getQuery()->find(); - $this->assertEquals(4, count($results)); - $this->assertFalse($parent->isDirty()); - - $query = $relation->getQuery(); - $query->lessThan('x', 5); - $results = $query->find(); - $this->assertEquals(1, count($results)); - $this->assertEquals($children[4]->getObjectId(), $results[0]->getObjectId()); - - } + $parent->save(); + + $results = $relation->getQuery()->find(); + $this->assertEquals(5, count($results)); + $this->assertFalse($parent->isDirty()); + + $relation->remove($children[8]); + $parent->save(); + $results = $relation->getQuery()->find(); + $this->assertEquals(4, count($results)); + $this->assertFalse($parent->isDirty()); + + $query = $relation->getQuery(); + $query->lessThan('x', 5); + $results = $query->find(); + $this->assertEquals(1, count($results)); + $this->assertEquals($children[4]->getObjectId(), $results[0]->getObjectId()); + } - public function testQueriesOnRelationFields() - { - $children = array(); - $this->saveObjects(10, function ($i) use (&$children) { + public function testQueriesOnRelationFields() + { + $children = []; + $this->saveObjects(10, function ($i) use (&$children) { $child = ParseObject::create('ChildObject'); $child->set('x', $i); $children[] = $child; + return $child; }); - $parent = ParseObject::create('ParentObject'); - $parent->set('x', 4); - $relation = $parent->getRelation('children'); - $relation->add([ + $parent = ParseObject::create('ParentObject'); + $parent->set('x', 4); + $relation = $parent->getRelation('children'); + $relation->add([ $children[0], $children[1], - $children[2] + $children[2], ]); - $parent->save(); - $parent2 = ParseObject::create('ParentObject'); - $parent2->set('x', 3); - $relation2 = $parent2->getRelation('children'); - $relation2->add([ + $parent->save(); + $parent2 = ParseObject::create('ParentObject'); + $parent2->set('x', 3); + $relation2 = $parent2->getRelation('children'); + $relation2->add([ $children[4], $children[5], - $children[6] + $children[6], ]); - $parent2->save(); - $query = new ParseQuery('ParentObject'); - $query->containedIn('children', [$children[4], $children[9]]); - $results = $query->find(); - $this->assertEquals(1, count($results)); - $this->assertEquals($results[0]->getObjectId(), $parent2->getObjectId()); - - } - + $parent2->save(); + $query = new ParseQuery('ParentObject'); + $query->containedIn('children', [$children[4], $children[9]]); + $results = $query->find(); + $this->assertEquals(1, count($results)); + $this->assertEquals($results[0]->getObjectId(), $parent2->getObjectId()); + } } diff --git a/tests/ParseRoleTest.php b/tests/ParseRoleTest.php index 26326343..92b166af 100644 --- a/tests/ParseRoleTest.php +++ b/tests/ParseRoleTest.php @@ -1,217 +1,220 @@ aclPublic()); - $role->save(); - $this->assertNotNull($role->getObjectId(), "Role should have objectId."); - } + public function setUp() + { + ParseTestHelper::clearClass("_User"); + ParseTestHelper::clearClass("_Role"); + ParseTestHelper::clearClass("Things"); + } - public function testRoleWithoutACLFails() - { - $role = new ParseRole(); - $role->setName("Admin"); - $this->setExpectedException('Parse\ParseException', 'ACL'); - $role->save(); - } + public function tearDown() + { + ParseTestHelper::tearDown(); + } - public function testNameValidation() - { - $role = ParseRole::createRole("Admin", $this->aclPublic()); - $this->assertEquals("Admin", $role->getName()); - $role->setName("Superuser"); - $this->assertEquals("Superuser", $role->getName()); - $role->setName("Super-Users"); - $this->assertEquals("Super-Users", $role->getName()); - $role->setName("A1234"); - $this->assertEquals("A1234", $role->getName()); - $role->save(); - $this->setExpectedException('Parse\ParseException', 'has been saved'); - $role->setName("Moderators"); - } + public function testCreateRole() + { + $role = ParseRole::createRole("Admin", $this->aclPublic()); + $role->save(); + $this->assertNotNull($role->getObjectId(), "Role should have objectId."); + } - public function testGetCreatedRole() - { - $role = ParseRole::createRole("Admin", $this->aclPublic()); - $role->save(); - $query = ParseRole::query(); - $obj = $query->get($role->getObjectId()); - $this->assertTrue($obj instanceof ParseRole); - $this->assertEquals($role->getObjectId(), $obj->getObjectId()); - } + public function testRoleWithoutACLFails() + { + $role = new ParseRole(); + $role->setName("Admin"); + $this->setExpectedException('Parse\ParseException', 'ACL'); + $role->save(); + } - public function testFindRolesByName() - { - $admin = ParseRole::createRole("Admin", $this->aclPublic()); - $mod = ParseRole::createRole("Moderator", $this->aclPublic()); - ParseObject::saveAll([$admin, $mod]); - $query1 = ParseRole::query(); - $query1->equalTo("name", "Admin"); - $this->assertEquals(1, $query1->count(), "Count should be 1."); - $query2 = ParseRole::query(); - $query2->equalTo("name", "Moderator"); - $this->assertEquals(1, $query2->count(), "Count should be 1."); - $query3 = ParseRole::query(); - $this->assertEquals(2, $query3->count()); - } + public function testNameValidation() + { + $role = ParseRole::createRole("Admin", $this->aclPublic()); + $this->assertEquals("Admin", $role->getName()); + $role->setName("Superuser"); + $this->assertEquals("Superuser", $role->getName()); + $role->setName("Super-Users"); + $this->assertEquals("Super-Users", $role->getName()); + $role->setName("A1234"); + $this->assertEquals("A1234", $role->getName()); + $role->save(); + $this->setExpectedException('Parse\ParseException', 'has been saved'); + $role->setName("Moderators"); + } - public function testRoleNameUnique() - { - $role = ParseRole::createRole("Admin", $this->aclPublic()); - $role->save(); - $role2 = ParseRole::createRole("Admin", $this->aclPublic()); - $this->setExpectedException('Parse\ParseException', 'duplicate'); - $role2->save(); - } + public function testGetCreatedRole() + { + $role = ParseRole::createRole("Admin", $this->aclPublic()); + $role->save(); + $query = ParseRole::query(); + $obj = $query->get($role->getObjectId()); + $this->assertTrue($obj instanceof ParseRole); + $this->assertEquals($role->getObjectId(), $obj->getObjectId()); + } - public function testExplicitRoleACL() - { - $eden = $this->createEden(); - ParseUser::logIn("adam", "adam"); - $query = new ParseQuery("Things"); - $apple = $query->get($eden['apple']->getObjectId()); - ParseUser::logIn("eve", "eve"); - $apple = $query->get($eden['apple']->getObjectId()); - ParseUser::logIn("snake", "snake"); - $this->setExpectedException('Parse\ParseException', 'not found'); - $apple = $query->get($eden['apple']->getObjectId()); - } + public function testFindRolesByName() + { + $admin = ParseRole::createRole("Admin", $this->aclPublic()); + $mod = ParseRole::createRole("Moderator", $this->aclPublic()); + ParseObject::saveAll([$admin, $mod]); + $query1 = ParseRole::query(); + $query1->equalTo("name", "Admin"); + $this->assertEquals(1, $query1->count(), "Count should be 1."); + $query2 = ParseRole::query(); + $query2->equalTo("name", "Moderator"); + $this->assertEquals(1, $query2->count(), "Count should be 1."); + $query3 = ParseRole::query(); + $this->assertEquals(2, $query3->count()); + } - public function testRoleHierarchyAndPropagation() - { - $eden = $this->createEden(); - ParseUser::logIn("adam", "adam"); - $query = new ParseQuery("Things"); - $garden = $query->get($eden['garden']->getObjectId()); - ParseUser::logIn("eve", "eve"); - $garden = $query->get($eden['garden']->getObjectId()); - ParseUser::logIn("snake", "snake"); - $garden = $query->get($eden['garden']->getObjectId()); - - $eden['edenkin']->getRoles()->remove($eden['humans']); - $eden['edenkin']->save(); - ParseUser::logIn("adam", "adam"); - try { - $query->get($eden['garden']->getObjectId()); - $this->fail("Get should have failed."); - } catch (\Parse\ParseException $ex) { - if ($ex->getMessage() != "Object not found.") throw $ex; + public function testRoleNameUnique() + { + $role = ParseRole::createRole("Admin", $this->aclPublic()); + $role->save(); + $role2 = ParseRole::createRole("Admin", $this->aclPublic()); + $this->setExpectedException('Parse\ParseException', 'duplicate'); + $role2->save(); } - ParseUser::logIn("eve", "eve"); - try { - $query->get($eden['garden']->getObjectId()); - $this->fail("Get should have failed."); - } catch (\Parse\ParseException $ex) { - if ($ex->getMessage() != "Object not found.") throw $ex; + + public function testExplicitRoleACL() + { + $eden = $this->createEden(); + ParseUser::logIn("adam", "adam"); + $query = new ParseQuery("Things"); + $apple = $query->get($eden['apple']->getObjectId()); + ParseUser::logIn("eve", "eve"); + $apple = $query->get($eden['apple']->getObjectId()); + ParseUser::logIn("snake", "snake"); + $this->setExpectedException('Parse\ParseException', 'not found'); + $apple = $query->get($eden['apple']->getObjectId()); } - ParseUser::logIn("snake", "snake"); - $query->get($eden['garden']->getObjectId()); - } - public function testAddUserAfterFetch() - { - $user = new ParseUser(); - $user->setUsername("bob"); - $user->setPassword("barker"); - $user->signUp(); - $role = ParseRole::createRole("MyRole", ParseACL::createACLWithUser($user)); - $role->save(); - $query = ParseRole::query(); - $roleAgain = $query->get($role->getObjectId()); - $roleAgain->getUsers()->add($user); - $roleAgain->save(); - } + public function testRoleHierarchyAndPropagation() + { + $eden = $this->createEden(); + ParseUser::logIn("adam", "adam"); + $query = new ParseQuery("Things"); + $garden = $query->get($eden['garden']->getObjectId()); + ParseUser::logIn("eve", "eve"); + $garden = $query->get($eden['garden']->getObjectId()); + ParseUser::logIn("snake", "snake"); + $garden = $query->get($eden['garden']->getObjectId()); + + $eden['edenkin']->getRoles()->remove($eden['humans']); + $eden['edenkin']->save(); + ParseUser::logIn("adam", "adam"); + try { + $query->get($eden['garden']->getObjectId()); + $this->fail("Get should have failed."); + } catch (\Parse\ParseException $ex) { + if ($ex->getMessage() != "Object not found.") { + throw $ex; + } + } + ParseUser::logIn("eve", "eve"); + try { + $query->get($eden['garden']->getObjectId()); + $this->fail("Get should have failed."); + } catch (\Parse\ParseException $ex) { + if ($ex->getMessage() != "Object not found.") { + throw $ex; + } + } + ParseUser::logIn("snake", "snake"); + $query->get($eden['garden']->getObjectId()); + } + public function testAddUserAfterFetch() + { + $user = new ParseUser(); + $user->setUsername("bob"); + $user->setPassword("barker"); + $user->signUp(); + $role = ParseRole::createRole("MyRole", ParseACL::createACLWithUser($user)); + $role->save(); + $query = ParseRole::query(); + $roleAgain = $query->get($role->getObjectId()); + $roleAgain->getUsers()->add($user); + $roleAgain->save(); + } /** - * Utilities + * Utilities. */ - public function aclPrivateTo($someone) { - $acl = new ParseACL(); - $acl->setReadAccess($someone, true); - $acl->setWriteAccess($someone, true); - return $acl; - } + $acl = new ParseACL(); + $acl->setReadAccess($someone, true); + $acl->setWriteAccess($someone, true); - public function aclPublic() - { - $acl = new ParseACL(); - $acl->setPublicReadAccess(true); - $acl->setPublicWriteAccess(true); - return $acl; + return $acl; } - public function createUser($username) - { - $user = new ParseUser(); - $user->setUsername($username); - $user->setPassword($username); - return $user; - } + public function aclPublic() + { + $acl = new ParseACL(); + $acl->setPublicReadAccess(true); + $acl->setPublicWriteAccess(true); - public function createEden() - { - $eden = array(); - $eden['adam'] = $this->createUser('adam'); - $eden['eve'] = $this->createUser('eve'); - $eden['snake'] = $this->createUser('snake'); - $eden['adam']->signUp(); - $eden['eve']->signUp(); - $eden['snake']->signUp(); - $eden['humans'] = ParseRole::createRole("humans", $this->aclPublic()); - $eden['humans']->getUsers()->add($eden['adam']); - $eden['humans']->getUsers()->add($eden['eve']); - $eden['creatures'] = ParseRole::createRole( - "creatures", $this->aclPublic() - ); - $eden['creatures']->getUsers()->add($eden['snake']); - ParseObject::saveAll([$eden['humans'], $eden['creatures']]); - $eden['edenkin'] = ParseRole::createRole("edenkin", $this->aclPublic()); - $eden['edenkin']->getRoles()->add($eden['humans']); - $eden['edenkin']->getRoles()->add($eden['creatures']); - $eden['edenkin']->save(); + return $acl; + } - $eden['apple'] = ParseObject::create("Things"); - $eden['apple']->set("name", "apple"); - $eden['apple']->set("ACL", $this->aclPrivateTo($eden['humans'])); + public function createUser($username) + { + $user = new ParseUser(); + $user->setUsername($username); + $user->setPassword($username); - $eden['garden'] = ParseObject::create("Things"); - $eden['garden']->set("name", "garden"); - $eden['garden']->set("ACL", $this->aclPrivateTo($eden['edenkin'])); + return $user; + } + + public function createEden() + { + $eden = []; + $eden['adam'] = $this->createUser('adam'); + $eden['eve'] = $this->createUser('eve'); + $eden['snake'] = $this->createUser('snake'); + $eden['adam']->signUp(); + $eden['eve']->signUp(); + $eden['snake']->signUp(); + $eden['humans'] = ParseRole::createRole("humans", $this->aclPublic()); + $eden['humans']->getUsers()->add($eden['adam']); + $eden['humans']->getUsers()->add($eden['eve']); + $eden['creatures'] = ParseRole::createRole( + "creatures", $this->aclPublic() + ); + $eden['creatures']->getUsers()->add($eden['snake']); + ParseObject::saveAll([$eden['humans'], $eden['creatures']]); + $eden['edenkin'] = ParseRole::createRole("edenkin", $this->aclPublic()); + $eden['edenkin']->getRoles()->add($eden['humans']); + $eden['edenkin']->getRoles()->add($eden['creatures']); + $eden['edenkin']->save(); - ParseObject::saveAll([$eden['apple'], $eden['garden']]); + $eden['apple'] = ParseObject::create("Things"); + $eden['apple']->set("name", "apple"); + $eden['apple']->set("ACL", $this->aclPrivateTo($eden['humans'])); - return $eden; + $eden['garden'] = ParseObject::create("Things"); + $eden['garden']->set("name", "garden"); + $eden['garden']->set("ACL", $this->aclPrivateTo($eden['edenkin'])); - } + ParseObject::saveAll([$eden['apple'], $eden['garden']]); + return $eden; + } } diff --git a/tests/ParseSessionStorageTest.php b/tests/ParseSessionStorageTest.php index a7cdbfbd..efa97639 100644 --- a/tests/ParseSessionStorageTest.php +++ b/tests/ParseSessionStorageTest.php @@ -1,76 +1,72 @@ clear(); - } + public static function setUpBeforeClass() + { + ParseClient::_unsetStorage(); + session_start(); + ParseTestHelper::setUp(); + self::$parseStorage = ParseClient::getStorage(); + } - public static function tearDownAfterClass() - { - session_destroy(); - } + public function tearDown() + { + ParseTestHelper::tearDown(); + self::$parseStorage->clear(); + } - public function testIsUsingParseSession() - { - $this->assertTrue(self::$parseStorage instanceof Parse\ParseSessionStorage); - } + public static function tearDownAfterClass() + { + session_destroy(); + } - public function testSetAndGet() - { - self::$parseStorage->set('foo', 'bar'); - $this->assertEquals('bar', self::$parseStorage->get('foo')); - } + public function testIsUsingParseSession() + { + $this->assertTrue(self::$parseStorage instanceof Parse\ParseSessionStorage); + } - public function testRemove() - { - self::$parseStorage->set('foo', 'bar'); - self::$parseStorage->remove('foo'); - $this->assertNull(self::$parseStorage->get('foo')); - } + public function testSetAndGet() + { + self::$parseStorage->set('foo', 'bar'); + $this->assertEquals('bar', self::$parseStorage->get('foo')); + } - public function testClear() - { - self::$parseStorage->set('foo', 'bar'); - self::$parseStorage->set('foo2', 'bar'); - self::$parseStorage->set('foo3', 'bar'); - self::$parseStorage->clear(); - $this->assertEmpty(self::$parseStorage->getKeys()); - } + public function testRemove() + { + self::$parseStorage->set('foo', 'bar'); + self::$parseStorage->remove('foo'); + $this->assertNull(self::$parseStorage->get('foo')); + } - public function testGetAll() - { - self::$parseStorage->set('foo', 'bar'); - self::$parseStorage->set('foo2', 'bar'); - self::$parseStorage->set('foo3', 'bar'); - $result = self::$parseStorage->getAll(); - $this->assertEquals('bar', $result['foo']); - $this->assertEquals('bar', $result['foo2']); - $this->assertEquals('bar', $result['foo3']); - $this->assertEquals(3, count($result)); - } + public function testClear() + { + self::$parseStorage->set('foo', 'bar'); + self::$parseStorage->set('foo2', 'bar'); + self::$parseStorage->set('foo3', 'bar'); + self::$parseStorage->clear(); + $this->assertEmpty(self::$parseStorage->getKeys()); + } + public function testGetAll() + { + self::$parseStorage->set('foo', 'bar'); + self::$parseStorage->set('foo2', 'bar'); + self::$parseStorage->set('foo3', 'bar'); + $result = self::$parseStorage->getAll(); + $this->assertEquals('bar', $result['foo']); + $this->assertEquals('bar', $result['foo2']); + $this->assertEquals('bar', $result['foo3']); + $this->assertEquals(3, count($result)); + } } diff --git a/tests/ParseSessionTest.php b/tests/ParseSessionTest.php index 42db1846..59afc240 100644 --- a/tests/ParseSessionTest.php +++ b/tests/ParseSessionTest.php @@ -1,61 +1,57 @@ setUsername("username"); - $user->setPassword("password"); - $user->signUp(); - $session = ParseSession::getCurrentSession(); - $this->assertEquals($user->getSessionToken(), $session->getSessionToken()); - $this->assertTrue($session->isCurrentSessionRevocable()); - - ParseUser::logOut(); - - ParseUser::logIn("username", "password"); - $session = ParseSession::getCurrentSession(); - $this->assertEquals(ParseUser::getCurrentUser()->getSessionToken(), $session->getSessionToken()); - $this->assertTrue($session->isCurrentSessionRevocable()); - - $sessionToken = $session->getSessionToken(); - - ParseUser::logOut(); - - $this->setExpectedException('Parse\ParseException', 'invalid session token'); - ParseUser::become($sessionToken); + ParseTestHelper::setUp(); + ParseTestHelper::clearClass(ParseUser::$parseClassName); + ParseTestHelper::clearClass(ParseSession::$parseClassName); } -} \ No newline at end of file + public function tearDown() + { + ParseTestHelper::tearDown(); + ParseUser::logOut(); + ParseTestHelper::clearClass(ParseUser::$parseClassName); + ParseTestHelper::clearClass(ParseSession::$parseClassName); + } + + public static function tearDownAfterClass() + { + ParseUser::_unregisterSubclass(); + ParseSession::_unregisterSubclass(); + } + + public function testRevocableSession() + { + ParseClient::enableRevocableSessions(); + $user = new ParseUser(); + $user->setUsername("username"); + $user->setPassword("password"); + $user->signUp(); + $session = ParseSession::getCurrentSession(); + $this->assertEquals($user->getSessionToken(), $session->getSessionToken()); + $this->assertTrue($session->isCurrentSessionRevocable()); + + ParseUser::logOut(); + + ParseUser::logIn("username", "password"); + $session = ParseSession::getCurrentSession(); + $this->assertEquals(ParseUser::getCurrentUser()->getSessionToken(), $session->getSessionToken()); + $this->assertTrue($session->isCurrentSessionRevocable()); + + $sessionToken = $session->getSessionToken(); + + ParseUser::logOut(); + + $this->setExpectedException('Parse\ParseException', 'invalid session token'); + ParseUser::become($sessionToken); + } +} diff --git a/tests/ParseSubclassTest.php b/tests/ParseSubclassTest.php index cf75b199..ecac3483 100644 --- a/tests/ParseSubclassTest.php +++ b/tests/ParseSubclassTest.php @@ -1,7 +1,5 @@ assertTrue($install instanceof ParseInstallation); - $this->assertTrue(is_subclass_of($install, 'Parse\ParseObject')); - } - - public function testCreateFromParseObject() - { - $install = ParseObject::create("_Installation"); - $this->assertTrue($install instanceof ParseInstallation); - $this->assertTrue(is_subclass_of($install, 'Parse\ParseObject')); + ParseTestHelper::setUp(); } -} \ No newline at end of file + public function tearDown() + { + ParseTestHelper::tearDown(); + } + + public function testCreateFromSubclass() + { + $install = new ParseInstallation(); + $this->assertTrue($install instanceof ParseInstallation); + $this->assertTrue(is_subclass_of($install, 'Parse\ParseObject')); + } + + public function testCreateFromParseObject() + { + $install = ParseObject::create("_Installation"); + $this->assertTrue($install instanceof ParseInstallation); + $this->assertTrue(is_subclass_of($install, 'Parse\ParseObject')); + } +} diff --git a/tests/ParseTestHelper.php b/tests/ParseTestHelper.php index fcba5823..e3eee7ab 100644 --- a/tests/ParseTestHelper.php +++ b/tests/ParseTestHelper.php @@ -1,35 +1,32 @@ each(function(ParseObject $obj) { + public static function clearClass($class) + { + $query = new ParseQuery($class); + $query->each(function (ParseObject $obj) { $obj->destroy(true); }, true); - } - -} \ No newline at end of file + } +} diff --git a/tests/ParseUserTest.php b/tests/ParseUserTest.php index aefad0b8..78e0ff4e 100644 --- a/tests/ParseUserTest.php +++ b/tests/ParseUserTest.php @@ -1,6 +1,5 @@ setUsername("asdf"); - $user->setPassword("zxcv"); - $user->signUp(); - $this->assertTrue($user->isAuthenticated()); - } + public function testUserSignUp() + { + $user = new ParseUser(); + $user->setUsername("asdf"); + $user->setPassword("zxcv"); + $user->signUp(); + $this->assertTrue($user->isAuthenticated()); + } - public function testLoginSuccess() - { - $this->testUserSignUp(); - $user = ParseUser::logIn("asdf", "zxcv"); - $this->assertTrue($user->isAuthenticated()); - $this->assertEquals("asdf", $user->get('username')); - } + public function testLoginSuccess() + { + $this->testUserSignUp(); + $user = ParseUser::logIn("asdf", "zxcv"); + $this->assertTrue($user->isAuthenticated()); + $this->assertEquals("asdf", $user->get('username')); + } - public function testLoginWrongUsername() - { - $this->setExpectedException('Parse\ParseException', 'invalid login'); - $user = ParseUser::logIn("non_existent_user", "bogus"); - } + public function testLoginWrongUsername() + { + $this->setExpectedException('Parse\ParseException', 'invalid login'); + $user = ParseUser::logIn("non_existent_user", "bogus"); + } - public function testLoginWrongPassword() - { - $this->testUserSignUp(); - $this->setExpectedException('Parse\ParseException', 'invalid login'); - $user = ParseUser::logIn("asdf", "bogus"); - } + public function testLoginWrongPassword() + { + $this->testUserSignUp(); + $this->setExpectedException('Parse\ParseException', 'invalid login'); + $user = ParseUser::logIn("asdf", "bogus"); + } - public function testBecome() - { - $user = new ParseUser(); - $user->setUsername("asdf"); - $user->setPassword("zxcv"); - $user->signUp(); - $this->assertEquals(ParseUser::getCurrentUser(), $user); + public function testBecome() + { + $user = new ParseUser(); + $user->setUsername("asdf"); + $user->setPassword("zxcv"); + $user->signUp(); + $this->assertEquals(ParseUser::getCurrentUser(), $user); - $sessionToken = $user->getSessionToken(); + $sessionToken = $user->getSessionToken(); - $newUser = ParseUser::become($sessionToken); - $this->assertEquals(ParseUser::getCurrentUser(), $newUser); - $this->assertEquals("asdf", $newUser->get('username')); + $newUser = ParseUser::become($sessionToken); + $this->assertEquals(ParseUser::getCurrentUser(), $newUser); + $this->assertEquals("asdf", $newUser->get('username')); - $this->setExpectedException('Parse\ParseException', 'invalid session'); - $failUser = ParseUser::become('garbage_token'); - } + $this->setExpectedException('Parse\ParseException', 'invalid session'); + $failUser = ParseUser::become('garbage_token'); + } - public function testCannotAlterOtherUser() - { - $user = new ParseUser(); - $user->setUsername("asdf"); - $user->setPassword("zxcv"); - $user->signUp(); + public function testCannotAlterOtherUser() + { + $user = new ParseUser(); + $user->setUsername("asdf"); + $user->setPassword("zxcv"); + $user->signUp(); - $otherUser = new ParseUser(); - $otherUser->setUsername("hacker"); - $otherUser->setPassword("password"); - $otherUser->signUp(); + $otherUser = new ParseUser(); + $otherUser->setUsername("hacker"); + $otherUser->setPassword("password"); + $otherUser->signUp(); - $this->assertEquals(ParseUser::getCurrentUser(), $otherUser); + $this->assertEquals(ParseUser::getCurrentUser(), $otherUser); - $this->setExpectedException( + $this->setExpectedException( 'Parse\ParseException', 'UserCannotBeAlteredWithoutSession' ); - $user->setUsername('changed'); - $user->save(); - } + $user->setUsername('changed'); + $user->save(); + } - public function testCannotDeleteOtherUser() - { - $user = new ParseUser(); - $user->setUsername("asdf"); - $user->setPassword("zxcv"); - $user->signUp(); + public function testCannotDeleteOtherUser() + { + $user = new ParseUser(); + $user->setUsername("asdf"); + $user->setPassword("zxcv"); + $user->signUp(); - $otherUser = new ParseUser(); - $otherUser->setUsername("hacker"); - $otherUser->setPassword("password"); - $otherUser->signUp(); + $otherUser = new ParseUser(); + $otherUser->setUsername("hacker"); + $otherUser->setPassword("password"); + $otherUser->signUp(); - $this->assertEquals(ParseUser::getCurrentUser(), $otherUser); + $this->assertEquals(ParseUser::getCurrentUser(), $otherUser); - $this->setExpectedException( + $this->setExpectedException( 'Parse\ParseException', 'UserCannotBeAlteredWithoutSession' ); - $user->destroy(); - } + $user->destroy(); + } - public function testCannotSaveAllWithOtherUser() - { - $user = new ParseUser(); - $user->setUsername("asdf"); - $user->setPassword("zxcv"); - $user->signUp(); - - $otherUser = new ParseUser(); - $otherUser->setUsername("hacker"); - $otherUser->setPassword("password"); - $otherUser->signUp(); - - $this->assertEquals(ParseUser::getCurrentUser(), $otherUser); - - $obj = ParseObject::create("TestObject"); - $obj->set('user', $otherUser); - $obj->save(); - - $item1 = ParseObject::create("TestObject"); - $item1->set('num', 0); - $item1->save(); - - $item1->set('num', 1); - $item2 = ParseObject::create("TestObject"); - $item2->set('num', 2); - $user->setUsername('changed'); - $this->setExpectedException( + public function testCannotSaveAllWithOtherUser() + { + $user = new ParseUser(); + $user->setUsername("asdf"); + $user->setPassword("zxcv"); + $user->signUp(); + + $otherUser = new ParseUser(); + $otherUser->setUsername("hacker"); + $otherUser->setPassword("password"); + $otherUser->signUp(); + + $this->assertEquals(ParseUser::getCurrentUser(), $otherUser); + + $obj = ParseObject::create("TestObject"); + $obj->set('user', $otherUser); + $obj->save(); + + $item1 = ParseObject::create("TestObject"); + $item1->set('num', 0); + $item1->save(); + + $item1->set('num', 1); + $item2 = ParseObject::create("TestObject"); + $item2->set('num', 2); + $user->setUsername('changed'); + $this->setExpectedException( 'Parse\ParseAggregateException', 'Errors during batch save.' ); - ParseObject::saveAll(array($item1, $item2, $user)); - } + ParseObject::saveAll([$item1, $item2, $user]); + } - public function testCurrentUser() - { - $user = new ParseUser(); - $user->setUsername("asdf"); - $user->setPassword("zxcv"); - $user->signUp(); + public function testCurrentUser() + { + $user = new ParseUser(); + $user->setUsername("asdf"); + $user->setPassword("zxcv"); + $user->signUp(); - $current = ParseUser::getCurrentUser(); - $this->assertEquals($current->getObjectId(), $user->getObjectId()); - $this->assertNotNull($user->getSessionToken()); + $current = ParseUser::getCurrentUser(); + $this->assertEquals($current->getObjectId(), $user->getObjectId()); + $this->assertNotNull($user->getSessionToken()); - $currentAgain = ParseUser::getCurrentUser(); - $this->assertEquals($current, $currentAgain); + $currentAgain = ParseUser::getCurrentUser(); + $this->assertEquals($current, $currentAgain); - ParseUser::logOut(); - $this->assertNull(ParseUser::getCurrentUser()); - } + ParseUser::logOut(); + $this->assertNull(ParseUser::getCurrentUser()); + } - public function testIsCurrent() - { - $user1 = new ParseUser(); - $user2 = new ParseUser(); - $user3 = new ParseUser(); - - $user1->setUsername('a'); - $user2->setUsername('b'); - $user3->setUsername('c'); - - $user1->setPassword('password'); - $user2->setPassword('password'); - $user3->setPassword('password'); - - $user1->signUp(); - $this->assertTrue($user1->isCurrent()); - $this->assertFalse($user2->isCurrent()); - $this->assertFalse($user3->isCurrent()); - - $user2->signUp(); - $this->assertTrue($user2->isCurrent()); - $this->assertFalse($user1->isCurrent()); - $this->assertFalse($user3->isCurrent()); - - $user3->signUp(); - $this->assertTrue($user3->isCurrent()); - $this->assertFalse($user1->isCurrent()); - $this->assertFalse($user2->isCurrent()); - - $user = ParseUser::logIn('a', 'password'); - $this->assertTrue($user1->isCurrent()); - $this->assertFalse($user2->isCurrent()); - $this->assertFalse($user3->isCurrent()); - - $user = ParseUser::logIn('b', 'password'); - $this->assertTrue($user2->isCurrent()); - $this->assertFalse($user1->isCurrent()); - $this->assertFalse($user3->isCurrent()); - - $user = ParseUser::logIn('c', 'password'); - $this->assertTrue($user3->isCurrent()); - $this->assertFalse($user1->isCurrent()); - $this->assertFalse($user2->isCurrent()); - - ParseUser::logOut(); - $this->assertFalse($user1->isCurrent()); - $this->assertFalse($user2->isCurrent()); - $this->assertFalse($user3->isCurrent()); - } + public function testIsCurrent() + { + $user1 = new ParseUser(); + $user2 = new ParseUser(); + $user3 = new ParseUser(); + + $user1->setUsername('a'); + $user2->setUsername('b'); + $user3->setUsername('c'); + + $user1->setPassword('password'); + $user2->setPassword('password'); + $user3->setPassword('password'); + + $user1->signUp(); + $this->assertTrue($user1->isCurrent()); + $this->assertFalse($user2->isCurrent()); + $this->assertFalse($user3->isCurrent()); + + $user2->signUp(); + $this->assertTrue($user2->isCurrent()); + $this->assertFalse($user1->isCurrent()); + $this->assertFalse($user3->isCurrent()); + + $user3->signUp(); + $this->assertTrue($user3->isCurrent()); + $this->assertFalse($user1->isCurrent()); + $this->assertFalse($user2->isCurrent()); + + $user = ParseUser::logIn('a', 'password'); + $this->assertTrue($user1->isCurrent()); + $this->assertFalse($user2->isCurrent()); + $this->assertFalse($user3->isCurrent()); + + $user = ParseUser::logIn('b', 'password'); + $this->assertTrue($user2->isCurrent()); + $this->assertFalse($user1->isCurrent()); + $this->assertFalse($user3->isCurrent()); + + $user = ParseUser::logIn('c', 'password'); + $this->assertTrue($user3->isCurrent()); + $this->assertFalse($user1->isCurrent()); + $this->assertFalse($user2->isCurrent()); + + ParseUser::logOut(); + $this->assertFalse($user1->isCurrent()); + $this->assertFalse($user2->isCurrent()); + $this->assertFalse($user3->isCurrent()); + } - public function testPasswordReset() - { - $user = new ParseUser(); - $user->setUsername('asdf'); - $user->setPassword('zxcv'); - $user->set('email', 'asdf@example.com'); - $user->signUp(); + public function testPasswordReset() + { + $user = new ParseUser(); + $user->setUsername('asdf'); + $user->setPassword('zxcv'); + $user->set('email', 'asdf@example.com'); + $user->signUp(); - ParseUser::requestPasswordReset('asdf@example.com'); - } + ParseUser::requestPasswordReset('asdf@example.com'); + } - public function testPasswordResetFails() - { - $this->setExpectedException( + public function testPasswordResetFails() + { + $this->setExpectedException( 'Parse\ParseException', 'no user found with email' ); - ParseUser::requestPasswordReset('non_existent@example.com'); - } + ParseUser::requestPasswordReset('non_existent@example.com'); + } - public function testUserAssociations() - { - $child = ParseObject::create("TestObject"); - $child->save(); - - $user = new ParseUser(); - $user->setUsername('asdf'); - $user->setPassword('zxcv'); - $user->set('child', $child); - $user->signUp(); - - $object = ParseObject::create("TestObject"); - $object->set('user', $user); - $object->save(); - - $query = new ParseQuery("TestObject"); - $objectAgain = $query->get($object->getObjectId()); - $userAgain = $objectAgain->get('user'); - $userAgain->fetch(); - - $this->assertEquals($userAgain->getObjectId(), $user->getObjectId()); - $this->assertEquals( - $userAgain->get('child')->getObjectId(), $child->getObjectId() - ); - } + public function testUserAssociations() + { + $child = ParseObject::create("TestObject"); + $child->save(); - public function testUserQueries() - { - ParseTestHelper::clearClass(ParseUser::$parseClassName); - $user = new ParseUser(); - $user->setUsername('asdf'); - $user->setPassword('zxcv'); - $user->set('email', 'asdf@example.com'); - $user->signUp(); - - $query = ParseUser::query(); - $users = $query->find(); - - $this->assertEquals(1, count($users)); - $this->assertEquals($user->getObjectId(), $users[0]->getObjectId()); - $this->assertEquals('asdf@example.com', $users[0]->get('email')); - } + $user = new ParseUser(); + $user->setUsername('asdf'); + $user->setPassword('zxcv'); + $user->set('child', $child); + $user->signUp(); - public function testContainedInUserArrayQueries() - { - ParseTestHelper::clearClass(ParseUser::$parseClassName); - ParseTestHelper::clearClass("TestObject"); - $userList = array(); - for ($i = 0; $i < 4; $i++) { - $user = new ParseUser(); - $user->setUsername('user_num_' . $i); - $user->setPassword('password'); - $user->set('email', 'asdf_' . $i . '@example.com'); - $user->signUp(); - $userList[] = $user; - } - $messageList = array(); - for ($i = 0; $i < 5; $i++) { - $message = ParseObject::create('TestObject'); - $toUser = ($i + 1) % 4; - $fromUser = $i % 4; - $message->set('to', $userList[$toUser]); - $message->set('from', $userList[$fromUser]); - $message->save(); - $messageList[] = $message; - } + $object = ParseObject::create("TestObject"); + $object->set('user', $user); + $object->save(); - $inList = array($userList[0], $userList[3], $userList[3]); - $query = new ParseQuery("TestObject"); - $query->containedIn('from', $inList); - $results = $query->find(); + $query = new ParseQuery("TestObject"); + $objectAgain = $query->get($object->getObjectId()); + $userAgain = $objectAgain->get('user'); + $userAgain->fetch(); - $this->assertEquals(3, count($results)); - } + $this->assertEquals($userAgain->getObjectId(), $user->getObjectId()); + $this->assertEquals( + $userAgain->get('child')->getObjectId(), $child->getObjectId() + ); + } - public function testSavingUserThrows() - { - $user = new ParseUser(); - $user->setUsername('asdf'); - $user->setPassword('zxcv'); - $this->setExpectedException('Parse\ParseException', 'You must call signUp'); - $user->save(); - } + public function testUserQueries() + { + ParseTestHelper::clearClass(ParseUser::$parseClassName); + $user = new ParseUser(); + $user->setUsername('asdf'); + $user->setPassword('zxcv'); + $user->set('email', 'asdf@example.com'); + $user->signUp(); + + $query = ParseUser::query(); + $users = $query->find(); + + $this->assertEquals(1, count($users)); + $this->assertEquals($user->getObjectId(), $users[0]->getObjectId()); + $this->assertEquals('asdf@example.com', $users[0]->get('email')); + } - public function testUserUpdates() - { - $user = new ParseUser(); - $user->setUsername('asdf'); - $user->setPassword('zxcv'); - $user->set('email', 'asdf@example.com'); - $user->signUp(); - $this->assertNotNull(ParseUser::getCurrentUser()); - $user->setUsername('test'); - $user->save(); - $this->assertNotNull($user->get('username')); - $this->assertNotNull($user->get('email')); - $user->destroy(); - - $query = ParseUser::query(); - $this->setExpectedException('Parse\ParseException', 'Object not found'); - $fail = $query->get($user->getObjectId()); - } + public function testContainedInUserArrayQueries() + { + ParseTestHelper::clearClass(ParseUser::$parseClassName); + ParseTestHelper::clearClass("TestObject"); + $userList = []; + for ($i = 0; $i < 4; $i++) { + $user = new ParseUser(); + $user->setUsername('user_num_'.$i); + $user->setPassword('password'); + $user->set('email', 'asdf_'.$i.'@example.com'); + $user->signUp(); + $userList[] = $user; + } + $messageList = []; + for ($i = 0; $i < 5; $i++) { + $message = ParseObject::create('TestObject'); + $toUser = ($i + 1) % 4; + $fromUser = $i % 4; + $message->set('to', $userList[$toUser]); + $message->set('from', $userList[$fromUser]); + $message->save(); + $messageList[] = $message; + } + + $inList = [$userList[0], $userList[3], $userList[3]]; + $query = new ParseQuery("TestObject"); + $query->containedIn('from', $inList); + $results = $query->find(); + + $this->assertEquals(3, count($results)); + } - public function testCountUsers() - { - ParseTestHelper::clearClass(ParseUser::$parseClassName); - $ilya = new ParseUser(); - $ilya->setUsername('ilya'); - $ilya->setPassword('password'); - $ilya->signUp(); - - $kevin = new ParseUser(); - $kevin->setUsername('kevin'); - $kevin->setPassword('password'); - $kevin->signUp(); - - $james = new ParseUser(); - $james->setUsername('james'); - $james->setPassword('password'); - $james->signUp(); - - $query = ParseUser::query(); - $result = $query->count(); - $this->assertEquals(3, $result); - } + public function testSavingUserThrows() + { + $user = new ParseUser(); + $user->setUsername('asdf'); + $user->setPassword('zxcv'); + $this->setExpectedException('Parse\ParseException', 'You must call signUp'); + $user->save(); + } - public function testUserLoadedFromStorageFromSignUp() - { - ParseTestHelper::clearClass(ParseUser::$parseClassName); - $fosco = new ParseUser(); - $fosco->setUsername('fosco'); - $fosco->setPassword('password'); - $fosco->signUp(); - $id = $fosco->getObjectId(); - $this->assertNotNull($id); - $current = ParseUser::getCurrentUser(); - $this->assertEquals($id, $current->getObjectId()); - ParseUser::_clearCurrentUserVariable(); - $current = ParseUser::getCurrentUser(); - $this->assertEquals($id, $current->getObjectId()); - } + public function testUserUpdates() + { + $user = new ParseUser(); + $user->setUsername('asdf'); + $user->setPassword('zxcv'); + $user->set('email', 'asdf@example.com'); + $user->signUp(); + $this->assertNotNull(ParseUser::getCurrentUser()); + $user->setUsername('test'); + $user->save(); + $this->assertNotNull($user->get('username')); + $this->assertNotNull($user->get('email')); + $user->destroy(); + + $query = ParseUser::query(); + $this->setExpectedException('Parse\ParseException', 'Object not found'); + $fail = $query->get($user->getObjectId()); + } - public function testUserLoadedFromStorageFromLogIn() - { - ParseTestHelper::clearClass(ParseUser::$parseClassName); - $fosco = new ParseUser(); - $fosco->setUsername('fosco'); - $fosco->setPassword('password'); - $fosco->signUp(); - $id = $fosco->getObjectId(); - $this->assertNotNull($id); - ParseUser::logOut(); - ParseUser::_clearCurrentUserVariable(); - $current = ParseUser::getCurrentUser(); - $this->assertNull($current); - ParseUser::logIn("fosco", "password"); - $current = ParseUser::getCurrentUser(); - $this->assertEquals($id, $current->getObjectId()); - ParseUser::_clearCurrentUserVariable(); - $current = ParseUser::getCurrentUser(); - $this->assertEquals($id, $current->getObjectId()); - } + public function testCountUsers() + { + ParseTestHelper::clearClass(ParseUser::$parseClassName); + $ilya = new ParseUser(); + $ilya->setUsername('ilya'); + $ilya->setPassword('password'); + $ilya->signUp(); + + $kevin = new ParseUser(); + $kevin->setUsername('kevin'); + $kevin->setPassword('password'); + $kevin->signUp(); + + $james = new ParseUser(); + $james->setUsername('james'); + $james->setPassword('password'); + $james->signUp(); + + $query = ParseUser::query(); + $result = $query->count(); + $this->assertEquals(3, $result); + } - public function testUserWithMissingUsername() - { - $user = new ParseUser(); - $user->setPassword('test'); - $this->setExpectedException('Parse\ParseException', 'empty name'); - $user->signUp(); - } + public function testUserLoadedFromStorageFromSignUp() + { + ParseTestHelper::clearClass(ParseUser::$parseClassName); + $fosco = new ParseUser(); + $fosco->setUsername('fosco'); + $fosco->setPassword('password'); + $fosco->signUp(); + $id = $fosco->getObjectId(); + $this->assertNotNull($id); + $current = ParseUser::getCurrentUser(); + $this->assertEquals($id, $current->getObjectId()); + ParseUser::_clearCurrentUserVariable(); + $current = ParseUser::getCurrentUser(); + $this->assertEquals($id, $current->getObjectId()); + } - public function testUserWithMissingPassword() - { - $user = new ParseUser(); - $user->setUsername('test'); - $this->setExpectedException('Parse\ParseException', 'empty password'); - $user->signUp(); - } + public function testUserLoadedFromStorageFromLogIn() + { + ParseTestHelper::clearClass(ParseUser::$parseClassName); + $fosco = new ParseUser(); + $fosco->setUsername('fosco'); + $fosco->setPassword('password'); + $fosco->signUp(); + $id = $fosco->getObjectId(); + $this->assertNotNull($id); + ParseUser::logOut(); + ParseUser::_clearCurrentUserVariable(); + $current = ParseUser::getCurrentUser(); + $this->assertNull($current); + ParseUser::logIn("fosco", "password"); + $current = ParseUser::getCurrentUser(); + $this->assertEquals($id, $current->getObjectId()); + ParseUser::_clearCurrentUserVariable(); + $current = ParseUser::getCurrentUser(); + $this->assertEquals($id, $current->getObjectId()); + } - public function testCurrentUserIsNotDirty() - { - $user = new ParseUser(); - $user->setUsername('asdf'); - $user->setPassword('zxcv'); - $user->set('bleep', 'bloop'); - $user->signUp(); - $this->assertFalse($user->isKeyDirty('bleep')); - $userAgain = ParseUser::getCurrentUser(); - $this->assertFalse($userAgain->isKeyDirty('bleep')); - } + public function testUserWithMissingUsername() + { + $user = new ParseUser(); + $user->setPassword('test'); + $this->setExpectedException('Parse\ParseException', 'empty name'); + $user->signUp(); + } -} \ No newline at end of file + public function testUserWithMissingPassword() + { + $user = new ParseUser(); + $user->setUsername('test'); + $this->setExpectedException('Parse\ParseException', 'empty password'); + $user->signUp(); + } + + public function testCurrentUserIsNotDirty() + { + $user = new ParseUser(); + $user->setUsername('asdf'); + $user->setPassword('zxcv'); + $user->set('bleep', 'bloop'); + $user->signUp(); + $this->assertFalse($user->isKeyDirty('bleep')); + $userAgain = ParseUser::getCurrentUser(); + $this->assertFalse($userAgain->isKeyDirty('bleep')); + } +} diff --git a/tests/phpunit.xml b/tests/phpunit.xml index c6d42c16..fe954497 100644 --- a/tests/phpunit.xml +++ b/tests/phpunit.xml @@ -5,4 +5,4 @@ tests - \ No newline at end of file +