From 08c0d5b8ada08c65b25b70bed8b571274a6b1cd3 Mon Sep 17 00:00:00 2001 From: Graham Campbell Date: Tue, 31 Mar 2015 23:30:22 +0100 Subject: [PATCH 1/4] Revert "Updated to full compliance with StyleCI" This reverts commit 4d814ba60b8cafd61a2252e8c1f3fffbce0a3121. --- 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, 5887 insertions(+), 5919 deletions(-) diff --git a/autoload.php b/autoload.php index 60e6cb69..a3ef6aa8 100755 --- a/autoload.php +++ b/autoload.php @@ -3,11 +3,12 @@ /** * 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 @@ -15,32 +16,33 @@ * @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 b8d810ef..9584f500 100755 --- a/src/Parse/Internal/AddOperation.php +++ b/src/Parse/Internal/AddOperation.php @@ -6,12 +6,14 @@ 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. */ @@ -26,10 +28,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; } /** @@ -39,7 +41,7 @@ public function __construct($objects) */ public function getValue() { - return $this->objects; + return $this->objects; } /** @@ -49,8 +51,8 @@ public function getValue() */ public function _encode() { - return ['__op' => 'Add', - 'objects' => ParseClient::_encode($this->objects, true), ]; + return array('__op' => 'Add', + 'objects' => ParseClient::_encode($this->objects, true)); } /** @@ -58,33 +60,30 @@ public function _encode() * * @param FieldOperation $previous Previous operation. * - * @throws ParseException - * * @return FieldOperation Merged operation. + * @throws ParseException */ 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.' ); } @@ -100,10 +99,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; + } + return array_merge((array)$oldValue, (array)$this->objects); } -} + +} \ No newline at end of file diff --git a/src/Parse/Internal/AddUniqueOperation.php b/src/Parse/Internal/AddUniqueOperation.php index 959ab2e3..c4666f31 100755 --- a/src/Parse/Internal/AddUniqueOperation.php +++ b/src/Parse/Internal/AddUniqueOperation.php @@ -8,10 +8,12 @@ /** * 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. */ @@ -26,10 +28,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; } /** @@ -39,7 +41,7 @@ public function __construct($objects) */ public function getValue() { - return $this->objects; + return $this->objects; } /** @@ -49,8 +51,8 @@ public function getValue() */ public function _encode() { - return ['__op' => 'AddUnique', - 'objects' => ParseClient::_encode($this->objects, true), ]; + return array('__op' => 'AddUnique', + 'objects' => ParseClient::_encode($this->objects, true)); } /** @@ -58,31 +60,28 @@ public function _encode() * * @param FieldOperation $previous Previous Operation. * - * @throws ParseException - * * @return FieldOperation Merged Operation. + * @throws ParseException */ 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.' ); } @@ -98,41 +97,40 @@ 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; - } - } elseif (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; + } + 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; + } } - - return $oldValue; + } + 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; + } } -} + return false; + } + +} \ No newline at end of file diff --git a/src/Parse/Internal/DeleteOperation.php b/src/Parse/Internal/DeleteOperation.php index 509c31cd..c55e0544 100755 --- a/src/Parse/Internal/DeleteOperation.php +++ b/src/Parse/Internal/DeleteOperation.php @@ -5,10 +5,12 @@ /** * 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. * @@ -16,7 +18,7 @@ class DeleteOperation implements FieldOperation */ public function _encode() { - return ['__op' => 'Delete']; + return array('__op' => 'Delete'); } /** @@ -30,7 +32,7 @@ public function _encode() */ public function _apply($oldValue, $object, $key) { - return; + return null; } /** @@ -42,6 +44,7 @@ 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 91a0a007..0236e8e3 100644 --- a/src/Parse/Internal/Encodable.php +++ b/src/Parse/Internal/Encodable.php @@ -6,14 +6,17 @@ * 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 d8b9b14e..5c3b8c94 100755 --- a/src/Parse/Internal/FieldOperation.php +++ b/src/Parse/Internal/FieldOperation.php @@ -5,10 +5,12 @@ /** * 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. * @@ -29,4 +31,5 @@ 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 ab429c72..d6fe3822 100755 --- a/src/Parse/Internal/IncrementOperation.php +++ b/src/Parse/Internal/IncrementOperation.php @@ -7,10 +7,12 @@ /** * Class IncrementOperation - Operation to increment numeric object key. * + * @package Parse * @author Fosco Marotto */ class IncrementOperation implements FieldOperation { + /** * @var int - Amount to increment by. */ @@ -23,7 +25,7 @@ class IncrementOperation implements FieldOperation */ public function __construct($value = 1) { - $this->value = $value; + $this->value = $value; } /** @@ -33,7 +35,7 @@ public function __construct($value = 1) */ public function getValue() { - return $this->value; + return $this->value; } /** @@ -43,7 +45,7 @@ public function getValue() */ public function _encode() { - return ['__op' => 'Increment', 'amount' => $this->value]; + return array('__op' => 'Increment', 'amount' => $this->value); } /** @@ -53,17 +55,15 @@ public function _encode() * @param mixed $object Value for this operation. * @param string $key Key to set Value on. * - * @throws ParseException - * * @return int New value after application. + * @throws ParseException */ 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. * - * @throws ParseException - * * @return FieldOperation + * @throws ParseException */ 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 e2c061eb..7f92a157 100644 --- a/src/Parse/Internal/ParseRelationOperation.php +++ b/src/Parse/Internal/ParseRelationOperation.php @@ -1,18 +1,19 @@ */ -class ParseRelationOperation implements FieldOperation -{ + +class ParseRelationOperation implements FieldOperation{ + /** * @var string - The className of the target objects. */ @@ -20,29 +21,29 @@ class ParseRelationOperation implements FieldOperation /** * @var array - Array of objects to add to this relation. */ - private $relationsToAdd = []; + private $relationsToAdd = array(); /** * @var array - Array of objects to remove from this relation. */ - private $relationsToRemove = []; + private $relationsToRemove = array(); - 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.'); - } + 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.'); + } + } /** * Helper function to check that all passed ParseObjects have same class name @@ -54,14 +55,14 @@ public function __construct($objectsToAdd, $objectsToRemove) */ private function checkAndAssignClassName($objects) { - 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.'); - } + 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.'); + } + } } /** @@ -73,16 +74,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; } + } } /** @@ -93,22 +94,23 @@ private function addObjects($objects, &$container) */ private function removeObjects($objects, &$container) { - 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 (!is_array($objects)) { + $objects = [$objects]; + } + $nullObjects = array(); + foreach ($objects as $object) { + if ($object->getObjectId() == null) { + $nullObjects[] = $object; + } else { + unset($container[$object->getObjectID()]); } + } + if (!empty($nullObjects)) { + self::removeElementsFromArray($nullObjects, $container['null']); + } } + /** * Applies the current operation and returns the result. * @@ -116,26 +118,25 @@ private function removeObjects($objects, &$container) * @param mixed $object Value for this operation. * @param string $key Key to perform this operation on. * - * @throws \Exception - * * @return mixed Result of the operation. + * + * @throws \Exception */ public function _apply($oldValue, $object, $key) { - if ($oldValue == null) { - return new ParseRelation($object, $key, $this->targetClassName); - } elseif ($oldValue instanceof ParseRelation) { - if ($this->targetClassName != null + if ($oldValue == null) { + return new ParseRelation($object, $key, $this->targetClassName); + } else if ($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.'); - } - - return $oldValue; - } else { - throw new \Exception("Operation is invalid after previous operation."); + 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."); + } } /** @@ -144,92 +145,91 @@ public function _apply($oldValue, $object, $key) * * @param FieldOperation $previous Previous operation. * - * @throws \Exception - * * @return FieldOperation Merged operation result. + * + * @throws \Exception */ 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. * - * @throws \Exception - * * @return mixed + * + * @throws \Exception */ public function _encode() { - $addRelation = []; - $removeRelation = []; - if (!empty($this->relationsToAdd)) { - $addRelation = [ - '__op' => 'AddRelation', + $addRelation = array(); + $removeRelation = array(); + if (!empty($this->relationsToAdd)) { + $addRelation = array( + '__op' => 'AddRelation', 'objects' => ParseClient::_encode( self::convertToOneDimensionalArray($this->relationsToAdd), true - ), - ]; - } - if (!empty($this->relationsToRemove)) { - $removeRelation = [ - '__op' => 'RemoveRelation', + ) + ); + } + if (!empty($this->relationsToRemove)) { + $removeRelation = array( + '__op' => 'RemoveRelation', 'objects' => ParseClient::_encode( self::convertToOneDimensionalArray($this->relationsToRemove), true - ), - ]; - } - if (!empty($addRelation) && !empty($removeRelation)) { - return [ + ) + ); + } + if (!empty($addRelation) && !empty($removeRelation)) { + return array( '__op' => 'Batch', - 'ops' => [$addRelation, $removeRelation], - ]; - } - - return empty($addRelation) ? $removeRelation : $addRelation; + 'ops' => [$addRelation, $removeRelation] + ); + } + return empty($addRelation) ? $removeRelation : $addRelation; } - public function _getTargetClass() - { - return $this->targetClassName; - } + 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]; + 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; + } } - $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]); - } + if ($exist) { + unset($array[$i]); } - $array = array_values($array); + } + $array = array_values($array); } /** @@ -267,15 +267,14 @@ public static function removeElementsFromArray($elements, &$array) */ public static function convertToOneDimensionalArray($array) { - $newArray = []; - if (is_array($array)) { - foreach ($array as $value) { - $newArray = array_merge($newArray, self::convertToOneDimensionalArray($value)); - } - } else { - $newArray[] = $array; + $newArray = array(); + if (is_array($array)) { + foreach ($array as $value) { + $newArray = array_merge($newArray, self::convertToOneDimensionalArray($value)); } - - return $newArray; + } else { + $newArray[] = $array; + } + return $newArray; } } diff --git a/src/Parse/Internal/RemoveOperation.php b/src/Parse/Internal/RemoveOperation.php index f3c180f5..0e44f11b 100644 --- a/src/Parse/Internal/RemoveOperation.php +++ b/src/Parse/Internal/RemoveOperation.php @@ -8,12 +8,14 @@ /** * 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. */ @@ -28,10 +30,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; } /** @@ -41,7 +43,7 @@ public function __construct($objects) */ public function getValue() { - return $this->objects; + return $this->objects; } /** @@ -51,8 +53,8 @@ public function getValue() */ public function _encode() { - return ['__op' => 'Remove', - 'objects' => ParseClient::_encode($this->objects, true), ]; + return array('__op' => 'Remove', + 'objects' => ParseClient::_encode($this->objects, true)); } /** @@ -60,31 +62,29 @@ public function _encode() * * @param FieldOperation $previous Previous operation. * - * @throws ParseException - * * @return FieldOperation Merged operation. + * @throws ParseException */ 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 []; - } - $newValue = []; - foreach ($oldValue as $oldObject) { - foreach ($this->objects as $newObject) { - if ($oldObject instanceof ParseObject) { - if ($newObject instanceof ParseObject + if (empty($oldValue)) { + return array(); + } + $newValue = array(); + 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; - } - } else { - if ($oldObject !== $newObject) { - $newValue[] = $oldObject; - } - } + // found the object, won't add it. + } else { + $newValue[] = $oldObject; } + } else { + if ($oldObject !== $newObject) { + $newValue[] = $oldObject; + } + } } - - return $newValue; + } + return $newValue; } -} + +} \ No newline at end of file diff --git a/src/Parse/Internal/SetOperation.php b/src/Parse/Internal/SetOperation.php index aea27255..df3b6099 100755 --- a/src/Parse/Internal/SetOperation.php +++ b/src/Parse/Internal/SetOperation.php @@ -7,10 +7,12 @@ /** * 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. */ @@ -29,8 +31,8 @@ class SetOperation implements FieldOperation */ public function __construct($value, $isAssociativeArray = false) { - $this->value = $value; - $this->isAssociativeArray = $isAssociativeArray; + $this->value = $value; + $this->isAssociativeArray = $isAssociativeArray; } /** @@ -40,7 +42,7 @@ public function __construct($value, $isAssociativeArray = false) */ public function getValue() { - return $this->value; + return $this->value; } /** @@ -50,16 +52,14 @@ public function getValue() */ public function _encode() { - if ($this->isAssociativeArray) { - $object = new \stdClass(); - foreach ($this->value as $key => $value) { - $object->$key = ParseClient::_encode($value, true); - } - - return ParseClient::_encode($object, true); + if ($this->isAssociativeArray) { + $object = new \stdClass(); + foreach ($this->value as $key => $value) { + $object->$key = ParseClient::_encode($value, true); } - - return ParseClient::_encode($this->value, true); + return ParseClient::_encode($object, 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,6 +86,7 @@ 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 f216098d..d56fc56b 100644 --- a/src/Parse/ParseACL.php +++ b/src/Parse/ParseACL.php @@ -12,10 +12,11 @@ * 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 */ @@ -23,7 +24,7 @@ class ParseACL implements Encodable /** * @var array - */ - private $permissionsById = []; + private $permissionsById = array(); /** * @var bool - */ @@ -54,11 +55,10 @@ 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,32 +66,30 @@ public static function createACLWithUser($user) * * @param array $data represents permissions. * - * @throws \Exception - * * @return ParseACL + * @throws \Exception * @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; } /** @@ -102,18 +100,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; } /** @@ -121,11 +119,10 @@ 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; } /** @@ -140,31 +137,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; } - 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]); - } + $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]); } + } } /** @@ -177,14 +174,13 @@ 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]; } /** @@ -197,10 +193,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); } /** @@ -211,17 +207,16 @@ public function setReadAccess($userId, $allowed) * * @param string $userId User id. * - * @throws \Exception - * * @return bool + * + * @throws \Exception */ 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); } /** @@ -234,10 +229,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); } /** @@ -248,19 +243,19 @@ public function setWriteAccess($userId, $allowed) * * @param string $userId User id. * - * @throws \Exception - * * @return bool + * + * @throws \Exception */ 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. * @@ -268,7 +263,7 @@ public function getWriteAccess($userId) */ public function setPublicReadAccess($allowed) { - $this->setReadAccess(self::PUBLIC_KEY, $allowed); + $this->setReadAccess(self::PUBLIC_KEY, $allowed); } /** @@ -278,7 +273,7 @@ public function setPublicReadAccess($allowed) */ public function getPublicReadAccess() { - return $this->getReadAccess(self::PUBLIC_KEY); + return $this->getReadAccess(self::PUBLIC_KEY); } /** @@ -288,7 +283,7 @@ public function getPublicReadAccess() */ public function setPublicWriteAccess($allowed) { - $this->setWriteAccess(self::PUBLIC_KEY, $allowed); + $this->setWriteAccess(self::PUBLIC_KEY, $allowed); } /** @@ -298,7 +293,7 @@ public function setPublicWriteAccess($allowed) */ public function getPublicWriteAccess() { - return $this->getWriteAccess(self::PUBLIC_KEY); + return $this->getWriteAccess(self::PUBLIC_KEY); } /** @@ -311,10 +306,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); } /** @@ -325,17 +320,16 @@ public function setUserReadAccess($user, $allowed) * * @param ParseUser $user * - * @throws \Exception - * * @return bool + * + * @throws \Exception */ 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()); } /** @@ -348,10 +342,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); } /** @@ -362,17 +356,16 @@ public function setUserWriteAccess($user, $allowed) * * @param ParseUser $user * - * @throws \Exception - * * @return bool + * + * @throws \Exception */ 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()); } /** @@ -386,7 +379,7 @@ public function getUserWriteAccess($user) */ public function getRoleReadAccessWithName($roleName) { - return $this->getReadAccess('role:'.$roleName); + return $this->getReadAccess('role:' . $roleName); } /** @@ -394,11 +387,12 @@ 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); } /** @@ -412,7 +406,7 @@ public function setRoleReadAccessWithName($roleName, $allowed) */ public function getRoleWriteAccessWithName($roleName) { - return $this->getWriteAccess('role:'.$roleName); + return $this->getWriteAccess('role:' . $roleName); } /** @@ -424,7 +418,7 @@ public function getRoleWriteAccessWithName($roleName) */ public function setRoleWriteAccessWithName($roleName, $allowed) { - $this->setWriteAccess('role:'.$roleName, $allowed); + $this->setWriteAccess('role:' . $roleName, $allowed); } /** @@ -436,10 +430,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."); - } + } } /** @@ -454,9 +448,8 @@ 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()); } /** @@ -469,8 +462,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); } /** @@ -485,9 +478,8 @@ 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()); } /** @@ -500,8 +492,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); } /** @@ -523,15 +515,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; + } } /** @@ -542,22 +534,21 @@ 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 ($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 (self::$defaultACLUsesCurrentUser && self::$defaultACL) { + $last = self::$lastCurrentUser ? clone self::$lastCurrentUser : null; + if (!ParseUser::getCurrentUser()) { + return self::$defaultACL; } - - 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; + } + return self::$defaultACL; } + } diff --git a/src/Parse/ParseAggregateException.php b/src/Parse/ParseAggregateException.php index caa16623..58410118 100644 --- a/src/Parse/ParseAggregateException.php +++ b/src/Parse/ParseAggregateException.php @@ -3,25 +3,27 @@ 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 = [], $previous = null) + public function __construct($message, $errors = array(), $previous = null) { - parent::__construct($message, 600, $previous); - $this->errors = $errors; + parent::__construct($message, 600, $previous); + $this->errors = $errors; } /** @@ -31,6 +33,7 @@ public function __construct($message, $errors = [], $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 40160958..8f40b22a 100644 --- a/src/Parse/ParseAnalytics.php +++ b/src/Parse/ParseAnalytics.php @@ -2,15 +2,17 @@ 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 @@ -37,24 +39,22 @@ class ParseAnalytics * @param array $dimensions The dictionary of segment information * * @throws \Exception - * * @return mixed */ - public static function track($name, $dimensions = []) + public static function track($name, $dimensions = array()) { - $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,11 +65,12 @@ public static function track($name, $dimensions = []) */ public static function _toSaveJSON($data) { - return json_encode( - [ - 'dimensions' => $data, - ], + return json_encode( + array( + 'dimensions' => $data + ), JSON_FORCE_OBJECT ); } -} + +} \ No newline at end of file diff --git a/src/Parse/ParseBytes.php b/src/Parse/ParseBytes.php index e2bd517b..506f72a4 100644 --- a/src/Parse/ParseBytes.php +++ b/src/Parse/ParseBytes.php @@ -5,10 +5,12 @@ /** * 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 */ @@ -23,14 +25,13 @@ 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 * @@ -38,39 +39,37 @@ 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); + return $bytes; } - private function setBase64Data($base64Data) - { - $byteArray = unpack('C*', base64_decode($base64Data)); - $this->setByteArray($byteArray); - } + private function setBase64Data($base64Data) + { + $byteArray = unpack('C*', base64_decode($base64Data)); + $this->setByteArray($byteArray); + } - private function setByteArray(array $byteArray) - { - $this->byteArray = $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 [ + $data = ""; + foreach ($this->byteArray as $byte) { + $data .= chr($byte); + } + return array( '__type' => 'Bytes', - 'base64' => base64_encode($data), - ]; + 'base64' => base64_encode($data) + ); } } diff --git a/src/Parse/ParseClient.php b/src/Parse/ParseClient.php index 5574c336..d85742a1 100755 --- a/src/Parse/ParseClient.php +++ b/src/Parse/ParseClient.php @@ -5,15 +5,16 @@ 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'; @@ -50,7 +51,6 @@ 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,45 +90,42 @@ 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 [ - '__type' => 'Date', 'iso' => self::getProperDateFormat($value), - ]; - } - - if ($value instanceof \stdClass) { - return $value; - } - - if ($value instanceof ParseObject) { - if (!$allowParseObjects) { - throw new \Exception('ParseObjects not allowed here.'); - } + if ($value instanceof \DateTime) { + return array( + '__type' => 'Date', 'iso' => self::getProperDateFormat($value) + ); + } - return $value->_toPointer(); - } + if ($value instanceof \stdClass) { + return $value; + } - if ($value instanceof Encodable) { - return $value->_encode(); + if ($value instanceof ParseObject) { + if (!$allowParseObjects) { + throw new \Exception('ParseObjects not allowed here.'); } + return $value->_toPointer(); + } - if (is_array($value)) { - return self::_encodeArray($value, $allowParseObjects); - } + if ($value instanceof Encodable) { + return $value->_encode(); + } - if (!is_scalar($value) && $value !== null) { - throw new \Exception('Invalid type encountered.'); - } + if (is_array($value)) { + return self::_encodeArray($value, $allowParseObjects); + } - return $value; + if (!is_scalar($value) && $value !== null) { + throw new \Exception('Invalid type encountered.'); + } + return $value; } /** @@ -141,62 +138,61 @@ 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)); - } - } - - if (!$data && !is_array($data)) { - return; + $tmp = (array)$data; + if (!empty($tmp)) { + return self::_decode(get_object_vars($data)); } + } - if (is_array($data)) { - $typeString = (isset($data['__type']) ? $data['__type'] : null); - - if ($typeString === 'Date') { - return new \DateTime($data['iso']); - } + if (!$data && !is_array($data)) { + return null; + } - if ($typeString === 'Bytes') { - return base64_decode($data['base64']); - } + if (is_array($data)) { + $typeString = (isset($data['__type']) ? $data['__type'] : null); - if ($typeString === 'Pointer') { - return ParseObject::create($data['className'], $data['objectId']); - } + if ($typeString === 'Date') { + return new \DateTime($data['iso']); + } - if ($typeString === 'File') { - return ParseFile::_createFromServer($data['name'], $data['url']); - } + if ($typeString === 'Bytes') { + return base64_decode($data['base64']); + } - if ($typeString === 'GeoPoint') { - return new ParseGeoPoint($data['latitude'], $data['longitude']); - } + if ($typeString === 'Pointer') { + return ParseObject::create($data['className'], $data['objectId']); + } - if ($typeString === 'Object') { - $output = ParseObject::create($data['className']); - $output->_mergeAfterFetch($data); + if ($typeString === 'File') { + return ParseFile::_createFromServer($data['name'], $data['url']); + } - return $output; - } + if ($typeString === 'GeoPoint') { + return new ParseGeoPoint($data['latitude'], $data['longitude']); + } - if ($typeString === 'Relation') { - return $data; - } + if ($typeString === 'Object') { + $output = ParseObject::create($data['className']); + $output->_mergeAfterFetch($data); + return $output; + } - $newDict = []; - foreach ($data as $key => $value) { - $newDict[$key] = static::_decode($value); - } + if ($typeString === 'Relation') { + return $data; + } - return $newDict; + $newDict = array(); + foreach ($data as $key => $value) { + $newDict[$key] = static::_decode($value); } + return $newDict; - return $data; + } + + return $data; } /** @@ -210,12 +206,11 @@ public static function _decode($data) */ public static function _encodeArray($value, $allowParseObjects) { - $output = []; - foreach ($value as $key => $item) { - $output[$key] = self::_encode($item, $allowParseObjects); - } - - return $output; + $output = array(); + foreach ($value as $key => $item) { + $output[$key] = self::_encode($item, $allowParseObjects); + } + return $output; } /** @@ -227,64 +222,63 @@ public static function _encodeArray($value, $allowParseObjects) * @param null $data Data to provide with the request. * @param bool $useMasterKey Whether to use the Master Key. * - * @throws \Exception - * * @return mixed Result from Parse API Call. + * @throws \Exception * @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; - } - } - curl_close($rest); - if (strpos($contentType, 'text/html') !== false) { - throw new ParseException('Bad Request', -1); + $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); + } - $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; } /** @@ -297,7 +291,7 @@ public static function _request($method, $relativeUrl, $sessionToken = null, */ public static function setStorage(ParseStorageInterface $storageObject) { - self::$storage = $storageObject; + self::$storage = $storageObject; } /** @@ -308,7 +302,7 @@ public static function setStorage(ParseStorageInterface $storageObject) */ public static function getStorage() { - return self::$storage; + return self::$storage; } /** @@ -322,17 +316,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 @@ -343,27 +337,26 @@ private static function assertParseInitialized() */ public static function _getRequestHeaders($sessionToken, $useMasterKey) { - $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'; - } - /* + $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'; + } + /** * 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; } /** @@ -378,11 +371,10 @@ 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; } /** @@ -397,10 +389,9 @@ 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; } /** @@ -412,6 +403,7 @@ 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 61274fc3..7891191b 100644 --- a/src/Parse/ParseCloud.php +++ b/src/Parse/ParseCloud.php @@ -3,14 +3,16 @@ 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 @@ -18,20 +20,20 @@ class ParseCloud * * @return mixed */ - public static function run($name, $data = [], $useMasterKey = false) + public static function run($name, $data = array(), $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']); + return ParseClient::_decode($response['result']); } -} + +} \ No newline at end of file diff --git a/src/Parse/ParseConfig.php b/src/Parse/ParseConfig.php index 963b0cc9..674d3461 100644 --- a/src/Parse/ParseConfig.php +++ b/src/Parse/ParseConfig.php @@ -3,43 +3,39 @@ 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; + public function get($key) { + if (isset($this->currentConfig[$key])) { + return $this->currentConfig[$key]; } + return null; + } - public function escape($key) - { - if (isset($this->currentConfig[$key])) { - return htmlentities($this->currentConfig[$key]); - } - - return; + public function escape($key) { + if (isset($this->currentConfig[$key])) { + return htmlentities($this->currentConfig[$key]); } + return null; + } - protected function setConfig($config) - { - $this->currentConfig = $config; - } -} + protected function setConfig($config) { + $this->currentConfig = $config; + } + +} \ No newline at end of file diff --git a/src/Parse/ParseException.php b/src/Parse/ParseException.php index acca6526..b10499a6 100644 --- a/src/Parse/ParseException.php +++ b/src/Parse/ParseException.php @@ -3,14 +3,16 @@ 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. @@ -19,6 +21,7 @@ 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 9cf90920..a03c441f 100755 --- a/src/Parse/ParseFile.php +++ b/src/Parse/ParseFile.php @@ -5,10 +5,12 @@ /** * ParseFile - Representation of a Parse File object. * + * @package Parse * @author Fosco Marotto */ class ParseFile implements \Parse\Internal\Encodable { + /** * @var - Filename */ @@ -29,21 +31,20 @@ class ParseFile implements \Parse\Internal\Encodable /** * Return the data for the file, downloading it if not already present. * - * @throws ParseException - * * @return mixed + * + * @throws ParseException */ public function getData() { - if ($this->data) { - return $this->data; - } - if (!$this->url) { - throw new ParseException("Cannot retrieve data for unsaved ParseFile."); - } - $this->data = $this->download(); - + 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; } /** @@ -53,7 +54,7 @@ public function getData() */ public function getURL() { - return $this->url; + return $this->url; } /** @@ -64,33 +65,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); } /** @@ -100,12 +101,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 @@ -115,18 +116,17 @@ 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,9 +136,8 @@ 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); } /** @@ -152,11 +151,10 @@ 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; } /** @@ -167,11 +165,11 @@ public static function _createFromServer($name, $url) */ public function _encode() { - return [ + return array( '__type' => 'File', - 'url' => $this->url, - 'name' => $this->name, - ]; + 'url' => $this->url, + 'name' => $this->name + ); } /** @@ -181,269 +179,267 @@ 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); + } - return $response; + 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); + return $response; + } - 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", + 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", "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 300a07e7..11bef9f8 100755 --- a/src/Parse/ParseGeoPoint.php +++ b/src/Parse/ParseGeoPoint.php @@ -5,10 +5,12 @@ /** * ParseGeoPoint - Representation of a Parse GeoPoint object. * + * @package Parse * @author Fosco Marotto */ class ParseGeoPoint implements \Parse\Internal\Encodable { + /** * @var - Float value for latitude. */ @@ -26,8 +28,8 @@ class ParseGeoPoint implements \Parse\Internal\Encodable */ public function __construct($lat, $lon) { - $this->setLatitude($lat); - $this->setLongitude($lon); + $this->setLatitude($lat); + $this->setLongitude($lon); } /** @@ -37,7 +39,7 @@ public function __construct($lat, $lon) */ public function getLatitude() { - return $this->latitude; + return $this->latitude; } /** @@ -49,10 +51,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; } /** @@ -62,7 +64,7 @@ public function setLatitude($lat) */ public function getLongitude() { - return $this->longitude; + return $this->longitude; } /** @@ -74,26 +76,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 [ - '__type' => 'GeoPoint', - 'latitude' => $this->latitude, - 'longitude' => $this->longitude, - ]; + return array( + '__type' => 'GeoPoint', + 'latitude' => $this->latitude, + 'longitude' => $this->longitude + ); } } diff --git a/src/Parse/ParseInstallation.php b/src/Parse/ParseInstallation.php index 0ba5a0d6..10c61cd0 100644 --- a/src/Parse/ParseInstallation.php +++ b/src/Parse/ParseInstallation.php @@ -2,12 +2,17 @@ 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 4c4983d6..57b449fe 100644 --- a/src/Parse/ParseMemoryStorage.php +++ b/src/Parse/ParseMemoryStorage.php @@ -6,52 +6,54 @@ * 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 = []; - - 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]; - } - - return; + 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]; } + return null; + } - public function clear() - { - $this->storage = []; - } + public function clear() + { + $this->storage = array(); + } - public function save() - { - // No action required. + public function save() + { + // No action required. return; - } + } - public function getKeys() - { - return array_keys($this->storage); - } + public function getKeys() + { + return array_keys($this->storage); + } - public function getAll() - { - return $this->storage; - } -} + public function getAll() + { + return $this->storage; + } + +} \ No newline at end of file diff --git a/src/Parse/ParseObject.php b/src/Parse/ParseObject.php index 2eca2467..d701eeb9 100755 --- a/src/Parse/ParseObject.php +++ b/src/Parse/ParseObject.php @@ -2,23 +2,26 @@ namespace Parse; -use Exception; -use Parse\Internal\AddOperation; -use Parse\Internal\AddUniqueOperation; -use Parse\Internal\DeleteOperation; use Parse\Internal\Encodable; -use Parse\Internal\FieldOperation; -use Parse\Internal\IncrementOperation; use Parse\Internal\RemoveOperation; +use Parse\Internal\FieldOperation; use Parse\Internal\SetOperation; +use Parse\Internal\AddOperation; +use Parse\Internal\AddUniqueOperation; +use Parse\Internal\IncrementOperation; +use Parse\Internal\DeleteOperation; + +use \Exception; /** * 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. */ @@ -59,10 +62,10 @@ class ParseObject implements Encodable /** * @var array - Holds the registered subclasses and Parse class names. */ - private static $registeredSubclasses = []; + private static $registeredSubclasses = array(); /** - * Create a Parse Object. + * Create a Parse Object * * Creates a pointer object if an objectId is provided, * otherwise creates a new object. @@ -76,36 +79,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 = []; - $this->operationSet = []; - $this->estimatedData = []; - $this->dataAvailability = []; - if ($objectId || $isPointer) { - $this->objectId = $objectId; - $this->hasBeenFetched = false; - } else { - $this->hasBeenFetched = true; - } + $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; + } } /** @@ -113,7 +116,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); } /** @@ -122,22 +125,21 @@ private static function getSubclass() * @param string $key Key to set a value on. * @param mixed $value Value to assign. * - * @throws Exception - * * @return null + * @throws Exception * @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.'); + } } /** @@ -150,7 +152,7 @@ public function __set($key, $value) */ public function __get($key) { - return $this->get($key); + return $this->get($key); } /** @@ -158,25 +160,24 @@ public function __get($key) * * @param string $key Key to retrieve from the estimatedData array. * - * @throws \Exception - * * @return mixed + * + * @throws \Exception */ 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; + } + if (isset($this->estimatedData[$key])) { + return $this->estimatedData[$key]; + } + return null; } /** - * Check if the object has a given key. + * Check if the object has a given key * * @param string $key Key to check * @@ -184,7 +185,7 @@ public function get($key) */ public function has($key) { - return isset($this->estimatedData[$key]); + return isset($this->estimatedData[$key]); } /** @@ -192,12 +193,11 @@ 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,24 +221,23 @@ 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. @@ -246,44 +245,42 @@ private function hasDirtyChildren() * @param string $key Key to set a value for on the object. * @param mixed $value Value to set on the key. * - * @throws Exception - * * @return null + * @throws Exception */ 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. - * - * @throws Exception - * + * * @return null + * @throws Exception */ 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)); } /** @@ -292,21 +289,20 @@ 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. * - * @throws Exception - * * @return null + * @throws Exception */ 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)); } /** @@ -315,19 +311,18 @@ 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. * - * @throws Exception - * * @return null + * @throws Exception */ 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)); } /** @@ -337,8 +332,8 @@ public function remove($key, $value) */ public function revert() { - $this->operationSet = []; - $this->rebuildEstimatedData(); + $this->operationSet = array(); + $this->rebuildEstimatedData(); } /** @@ -349,9 +344,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); + } } /** @@ -365,25 +360,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; - } elseif (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; + } else if (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; } /** @@ -393,7 +388,7 @@ public function _performOperation($key, FieldOperation $operation) */ public function getClassName() { - return $this->className; + return $this->className; } /** @@ -403,7 +398,7 @@ public function getClassName() */ public function getObjectId() { - return $this->objectId; + return $this->objectId; } /** @@ -413,7 +408,7 @@ public function getObjectId() */ public function getCreatedAt() { - return $this->createdAt; + return $this->createdAt; } /** @@ -423,13 +418,14 @@ 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. @@ -438,7 +434,7 @@ private function _isDataAvailable($key) */ public function getUpdatedAt() { - return $this->updatedAt; + return $this->updatedAt; } /** @@ -454,13 +450,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); + } } /** @@ -472,16 +468,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); } /** @@ -495,17 +491,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 = []; - $this->dataAvailability = []; - $this->mergeFromServer($result, $completeData); - $this->rebuildEstimatedData(); + $this->serverData = array(); + $this->dataAvailability = array(); + $this->mergeFromServer($result, $completeData); + $this->rebuildEstimatedData(); } /** @@ -514,16 +510,15 @@ 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; + } } /** @@ -536,32 +531,33 @@ 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; - } + $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); - $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 (is_array($decodedValue)) { + if (isset($decodedValue['__type'])) { + if ($decodedValue['__type'] === 'Relation') { + $className = $decodedValue['className']; + $decodedValue = new ParseRelation($this, $key, $className); } - $this->serverData[$key] = $decodedValue; - $this->dataAvailability[$key] = true; - } - if (!$this->updatedAt && $this->createdAt) { - $this->updatedAt = $this->createdAt; + } + if ($key == 'ACL') { + $decodedValue = ParseACL::_createACLFromJSON($decodedValue); + } } + $this->serverData[$key] = $decodedValue; + $this->dataAvailability[$key] = true; + + } + if (!$this->updatedAt && $this->createdAt) { + $this->updatedAt = $this->createdAt; + } } /** @@ -573,23 +569,24 @@ 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']); + } + } /** @@ -600,15 +597,15 @@ public function _mergeMagicFields(&$data) */ protected function rebuildEstimatedData() { - $this->estimatedData = []; - foreach ($this->serverData as $key => $value) { - $this->estimatedData[$key] = $value; - } - $this->applyOperations($this->operationSet, $this->estimatedData); + $this->estimatedData = array(); + 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. @@ -617,19 +614,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; } + } } /** @@ -641,16 +638,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 ); } @@ -661,72 +658,69 @@ 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; + $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); $currentBatch = []; $currentcount = 0; - 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( + } + } + if (count($errors)) { + throw new ParseAggregateException( "Errors during batch destroy.", $errors ); - } } - - return; + } + return null; } - private static function destroyBatch(array $objects, $useMasterKey = false) - { - $data = []; - $errors = []; - foreach ($objects as $object) { - $data[] = [ + private static function destroyBatch(array $objects, $useMasterKey = false) + { + $data = []; + $errors = []; + foreach ($objects as $object) { + $data[] = array( "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(["requests" => $data]), + json_encode(array("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[] = [ + $errors[] = array( 'error' => $error, - 'code' => $code, - ]; - } - } - - return $errors; + 'code' => $code + ); + } } + return $errors; + } /** * Increment a numeric key by a certain value. @@ -738,7 +732,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)); } /** @@ -751,7 +745,7 @@ public function increment($key, $value = 1) */ public function add($key, $value) { - $this->_performOperation($key, new AddOperation($value)); + $this->_performOperation($key, new AddOperation($value)); } /** @@ -764,7 +758,7 @@ public function add($key, $value) */ public function addUnique($key, $value) { - $this->_performOperation($key, new AddUniqueOperation($value)); + $this->_performOperation($key, new AddUniqueOperation($value)); } /** @@ -776,7 +770,7 @@ public function addUnique($key, $value) */ public function delete($key) { - $this->_performOperation($key, new DeleteOperation()); + $this->_performOperation($key, new DeleteOperation()); } /** @@ -787,37 +781,36 @@ public function delete($key) */ public function _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; - } - } + $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(); } else { - $out[$key] = $value; + $out[$key][] = $item; } + } + } else { + $out[$key] = $value; } - - return json_encode($out); + } + return json_encode($out); } /** @@ -827,11 +820,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. * @@ -839,14 +832,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. @@ -855,7 +848,7 @@ public function save($useMasterKey = false) */ public static function saveAll($list, $useMasterKey = false) { - static::deepSave($list, $useMasterKey); + static::deepSave($list, $useMasterKey); } /** @@ -864,108 +857,109 @@ public static function saveAll($list, $useMasterKey = false) * @param $target * @param bool $useMasterKey Whether to use the Master Key. * - * @throws ParseException - * * @return null + * + * @throws ParseException */ private static function deepSave($target, $useMasterKey = false) { - $unsavedChildren = []; - $unsavedFiles = []; - static::findUnsavedChildren($target, $unsavedChildren, $unsavedFiles); - $sessionToken = null; - if (ParseUser::getCurrentUser()) { - $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); - } + $unsavedChildren = array(); + $unsavedFiles = array(); + 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 = []; + $objects = array(); // Get the set of unique objects among the children. foreach ($unsavedChildren as &$obj) { - if (!in_array($obj, $objects, true)) { - $objects[] = $obj; - } + if (!in_array($obj, $objects, true)) { + $objects[] = $obj; + } } - $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; + $remaining = $objects; - if (count($batch) === 0) { - throw new Exception("Tried to save a batch with a cycle."); - } + while (count($remaining) > 0) { - $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, - ]; - } + $batch = array(); + $newRemaining = array(); + + 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."); + } + + $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 + ); + } - 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(["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']) ? + $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[] = [ - 'error' => $error, - 'code' => $code, - 'object' => $obj, - ]; - } else { - $errorCollection[] = [ - 'error' => 'Unknown error in batch save.', - 'code' => -1, - 'object' => $obj, - ]; - } - } - if (count($errorCollection)) { - throw new ParseAggregateException( + $errorCollection[] = array( + 'error' => $error, + 'code' => $code, + 'object' => $obj + ); + } else { + $errorCollection[] = array( + 'error' => 'Unknown error in batch save.', + 'code' => -1, + 'object' => $obj + ); + } + } + if (count($errorCollection)) { + throw new ParseAggregateException( "Errors during batch save.", $errorCollection ); - } - } + } } + } } /** @@ -978,18 +972,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; - } - } elseif ($obj instanceof ParseFile) { - if (!$obj->getURL()) { - $unsavedFiles[] = $obj; - } + if ($obj->_isDirty(false)) { + $unsavedChildren[] = $obj; + } + } else if ($obj instanceof ParseFile) { + if (!$obj->getURL()) { + $unsavedFiles[] = $obj; + } } }); @@ -1006,33 +1000,30 @@ private static function findUnsavedChildren($object, * @return mixed The result of calling mapFunction on the root object. */ private static function traverse($deep, &$object, $mapFunction, - $seen = []) + $seen = array()) { - if ($object instanceof ParseObject) { - if (in_array($object, $seen, true)) { - return; - } - $seen[] = $object; - if ($deep) { - self::traverse( + if ($object instanceof ParseObject) { + if (in_array($object, $seen, true)) { + return null; + } + $seen[] = $object; + if ($deep) { + self::traverse( $deep, $object->estimatedData, $mapFunction, $seen ); - } - - 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); - } - - 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); } - return $mapFunction($object); + } + return $mapFunction($object); } /** @@ -1042,7 +1033,7 @@ private static function traverse($deep, &$object, $mapFunction, */ private function canBeSerialized() { - return self::canBeSerializedAsValue($this->estimatedData); + return self::canBeSerializedAsValue($this->estimatedData); } /** @@ -1055,23 +1046,21 @@ 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; } /** @@ -1083,52 +1072,48 @@ private static function canBeSerializedAsValue($object) */ private function mergeAfterSave($result) { - $this->applyOperations($this->operationSet, $this->serverData); - $this->mergeFromServer($result); - $this->operationSet = []; - $this->rebuildEstimatedData(); + $this->applyOperations($this->operationSet, $this->serverData); + $this->mergeFromServer($result); + $this->operationSet = array(); + $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 [ - '__type' => "Pointer", + if (!$this->objectId) { + throw new \Exception("Can't serialize an unsaved Parse.Object"); + } + return array( + '__type' => "Pointer", 'className' => $this->className, - 'objectId' => $this->objectId, ]; + 'objectId' => $this->objectId); } /** @@ -1138,7 +1123,7 @@ public function _toPointer() */ public function setACL($acl) { - $this->_performOperation('ACL', new SetOperation($acl)); + $this->_performOperation('ACL', new SetOperation($acl)); } /** @@ -1148,71 +1133,69 @@ 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; - } - $acl = $this->estimatedData['ACL']; - if ($mayCopy && $acl->_isShared()) { - return clone $acl; - } - - return $acl; + private function getACLWithCopy($mayCopy) + { + if (!isset($this->estimatedData['ACL'])) { + return null; + } + $acl = $this->estimatedData['ACL']; + if ($mayCopy && $acl->_isShared()) { + return clone $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. * - * @throws \Exception - * * @return ParseQuery + * + * @throws \Exception */ 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 43c9c385..59638d1c 100644 --- a/src/Parse/ParsePush.php +++ b/src/Parse/ParsePush.php @@ -3,12 +3,14 @@ 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. * @@ -25,38 +27,36 @@ 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,4 +64,5 @@ 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 d8c824fd..2e080685 100755 --- a/src/Parse/ParseQuery.php +++ b/src/Parse/ParseQuery.php @@ -3,12 +3,14 @@ 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. */ @@ -16,19 +18,19 @@ class ParseQuery /** * @var array - Where constraints. */ - private $where = []; + private $where = array(); /** * @var array - Order By keys. */ - private $orderBy = []; + private $orderBy = array(); /** * @var array - Include nested objects. */ - private $includes = []; + private $includes = array(); /** * @var array - Include certain keys only. */ - private $selectedKeys = []; + private $selectedKeys = array(); /** * @var int - Skip from the beginning of the search results. */ @@ -49,28 +51,27 @@ 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 * - * @throws ParseException - * * @return array + * + * @throws ParseException */ 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; } /** @@ -83,13 +84,12 @@ 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] = []; - } - $this->where[$key][$condition] = ParseClient::_encode($value, true); + if (!isset($this->where[$key])) { + $this->where[$key] = array(); + } + $this->where[$key][$condition] = ParseClient::_encode($value, true); } /** @@ -114,9 +114,8 @@ 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; } /** @@ -130,9 +129,8 @@ public function notEqualTo($key, $value) */ public function lessThan($key, $value) { - $this->addCondition($key, '$lt', $value); - - return $this; + $this->addCondition($key, '$lt', $value); + return $this; } /** @@ -146,9 +144,8 @@ public function lessThan($key, $value) */ public function greaterThan($key, $value) { - $this->addCondition($key, '$gt', $value); - - return $this; + $this->addCondition($key, '$gt', $value); + return $this; } /** @@ -162,9 +159,8 @@ public function greaterThan($key, $value) */ public function greaterThanOrEqualTo($key, $value) { - $this->addCondition($key, '$gte', $value); - - return $this; + $this->addCondition($key, '$gte', $value); + return $this; } /** @@ -178,19 +174,17 @@ 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"; } /** @@ -204,9 +198,8 @@ 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; } /** @@ -217,30 +210,29 @@ public function startsWith($key, $value) */ public function _getOptions() { - $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; + $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; } /** @@ -252,30 +244,28 @@ public function _getOptions() */ public function first($useMasterKey = false) { - $this->limit = 1; - $result = $this->find($useMasterKey); - if (count($result)) { - return $result[0]; - } else { - return []; - } + $this->limit = 1; + $result = $this->find($useMasterKey); + if (count($result)) { + return $result[0]; + } else { + return array(); + } } /** * 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); } /** @@ -287,14 +277,13 @@ 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']; } /** @@ -306,22 +295,21 @@ 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 = []; - 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 = array(); + foreach ($result['results'] as $row) { + $obj = ParseObject::create($this->className, $row['objectId']); + $obj->_mergeAfterFetchWithSelectedKeys($row, $this->selectedKeys); + $output[] = $obj; + } + return $output; } /** @@ -333,13 +321,12 @@ 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. * @@ -347,24 +334,21 @@ 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 = []; - - return $this->addAscending($key); + $this->orderBy = array(); + return $this->addAscending($key); } /** @@ -377,28 +361,25 @@ 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 = []; - - return $this->addDescending($key); + $this->orderBy = array(); + return $this->addDescending($key); } /** @@ -411,16 +392,15 @@ 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; } /** @@ -434,9 +414,8 @@ public function addDescending($key) */ public function near($key, $point) { - $this->addCondition($key, '$nearSphere', $point); - - return $this; + $this->addCondition($key, '$nearSphere', $point); + return $this; } /** @@ -451,10 +430,9 @@ 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; } /** @@ -470,10 +448,9 @@ 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; } /** @@ -489,10 +466,9 @@ 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; } /** @@ -508,10 +484,9 @@ 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; } /** @@ -525,9 +500,8 @@ 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; } /** @@ -544,29 +518,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]); } - $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; - } + if ($length == $query->limit) { + $query->greaterThan("objectId", $results[$length - 1]->getObjectId()); + } else { + $finished = true; } + } } /** @@ -580,9 +554,8 @@ 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; } /** @@ -597,11 +570,10 @@ 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; } /** @@ -616,11 +588,10 @@ 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; } /** @@ -637,12 +608,11 @@ 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; } /** @@ -659,12 +629,11 @@ 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; } /** @@ -673,26 +642,25 @@ public function doesNotMatchKeyInQuery($key, $queryKey, $query) * * @param array $queryObjects Array of ParseQuery objects to OR. * - * @throws \Exception If all queries don't have same class. - * * @return ParseQuery The query that is the OR of the passed in queries. + * + * @throws \Exception If all queries don't have same class. */ 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; } - $query = new ParseQuery($className); - $query->_or($queryObjects); - - return $query; + 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; } /** @@ -705,13 +673,12 @@ public static function orQueries($queryObjects) */ private function _or($queries) { - $this->where['$or'] = []; - $length = count($queries); - for ($i = 0; $i < $length; $i++) { - $this->where['$or'][] = $queries[$i]->where; - } - - return $this; + $this->where['$or'] = array(); + $length = count($queries); + for ($i = 0; $i < $length; $i++) { + $this->where['$or'][] = $queries[$i]->where; + } + return $this; } /** @@ -725,9 +692,8 @@ private function _or($queries) */ public function containsAll($key, $values) { - $this->addCondition($key, '$all', $values); - - return $this; + $this->addCondition($key, '$all', $values); + return $this; } /** @@ -739,9 +705,8 @@ public function containsAll($key, $values) */ public function exists($key) { - $this->addCondition($key, '$exists', true); - - return $this; + $this->addCondition($key, '$exists', true); + return $this; } /** @@ -753,9 +718,8 @@ public function exists($key) */ public function doesNotExist($key) { - $this->addCondition($key, '$exists', false); - - return $this; + $this->addCondition($key, '$exists', false); + return $this; } /** @@ -770,13 +734,12 @@ 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; } /** @@ -790,18 +753,16 @@ 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 * @@ -809,8 +770,7 @@ 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 31df589e..e3a00210 100644 --- a/src/Parse/ParseRelation.php +++ b/src/Parse/ParseRelation.php @@ -1,17 +1,18 @@ */ -class ParseRelation -{ + +class ParseRelation { + /** * @var ParseObject - The parent of this relation. */ @@ -34,9 +35,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; } /** @@ -49,18 +50,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.'); + } } /** @@ -70,12 +71,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); } /** @@ -85,12 +86,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); } /** @@ -100,7 +101,7 @@ public function remove($objects) */ public function getTargetClass() { - return $this->targetClassName; + return $this->targetClassName; } /** @@ -110,7 +111,7 @@ public function getTargetClass() */ public function setTargetClass($className) { - $this->targetClassName = $className; + $this->targetClassName = $className; } /** @@ -118,9 +119,8 @@ public function setTargetClass($className) * * @param $parent */ - public function setParent($parent) - { - $this->parent = $parent; + public function setParent($parent) { + $this->parent = $parent; } /** @@ -130,10 +130,9 @@ 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 97dbdbc6..dd780195 100644 --- a/src/Parse/ParseRole.php +++ b/src/Parse/ParseRole.php @@ -2,13 +2,17 @@ namespace Parse; +use Parse\ParseObject; + /** * ParseRole - Representation of an access Role. * + * @package Parse * @author Fosco Marotto */ class ParseRole extends ParseObject { + public static $parseClassName = "_Role"; /** @@ -21,11 +25,10 @@ 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; } /** @@ -35,7 +38,7 @@ public static function createRole($name, ParseACL $acl) */ public function getName() { - return $this->get("name"); + return $this->get("name"); } /** @@ -47,18 +50,17 @@ 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); } /** @@ -70,7 +72,7 @@ public function setName($name) */ public function getUsers() { - return $this->getRelation("users"); + return $this->getRelation("users"); } /** @@ -82,22 +84,24 @@ 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); } -} + return parent::save($useMasterKey); + } + + + +} \ No newline at end of file diff --git a/src/Parse/ParseSession.php b/src/Parse/ParseSession.php index 8fa8f41f..2c93f8c2 100644 --- a/src/Parse/ParseSession.php +++ b/src/Parse/ParseSession.php @@ -2,16 +2,21 @@ 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. @@ -20,7 +25,7 @@ class ParseSession extends ParseObject */ public function getSessionToken() { - return $this->_sessionToken; + return $this->_sessionToken; } /** @@ -32,15 +37,15 @@ 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. * This method is useful for migrating an existing app to use @@ -50,10 +55,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()); + } } /** @@ -65,7 +70,7 @@ public static function isCurrentSessionRevocable() */ public static function _isRevocable($token) { - return strpos($token, "r:") === 0; + return strpos($token, "r:") === 0; } /** @@ -75,10 +80,11 @@ 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 7aec9c1a..2d38ee11 100644 --- a/src/Parse/ParseSessionStorage.php +++ b/src/Parse/ParseSessionStorage.php @@ -5,64 +5,66 @@ /** * 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] = []; - } } - - public function set($key, $value) - { - $_SESSION[$this->storageKey][$key] = $value; + if (!isset($_SESSION[$this->storageKey])) { + $_SESSION[$this->storageKey] = array(); } + } - public function remove($key) - { - unset($_SESSION[$this->storageKey][$key]); - } + public function set($key, $value) + { + $_SESSION[$this->storageKey][$key] = $value; + } - public function get($key) - { - if (isset($_SESSION[$this->storageKey][$key])) { - return $_SESSION[$this->storageKey][$key]; - } + public function remove($key) + { + unset($_SESSION[$this->storageKey][$key]); + } - return; + public function get($key) + { + if (isset($_SESSION[$this->storageKey][$key])) { + return $_SESSION[$this->storageKey][$key]; } + return null; + } - public function clear() - { - $_SESSION[$this->storageKey] = []; - } + public function clear() + { + $_SESSION[$this->storageKey] = array(); + } - 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 getKeys() + { + return array_keys($_SESSION[$this->storageKey]); + } - public function getAll() - { - return $_SESSION[$this->storageKey]; - } -} + public function getAll() + { + return $_SESSION[$this->storageKey]; + } + +} \ No newline at end of file diff --git a/src/Parse/ParseStorageInterface.php b/src/Parse/ParseStorageInterface.php index 0f24c178..c3700048 100644 --- a/src/Parse/ParseStorageInterface.php +++ b/src/Parse/ParseStorageInterface.php @@ -5,10 +5,12 @@ /** * ParseStorageInterface - Specifies an interface for implementing persistence. * + * @package Parse * @author Fosco Marotto */ interface ParseStorageInterface { + /** * Sets a key-value pair in storage. * @@ -66,4 +68,5 @@ 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 5dfb6b5e..f2f4d72c 100644 --- a/src/Parse/ParseUser.php +++ b/src/Parse/ParseUser.php @@ -5,10 +5,12 @@ /** * ParseUser - Representation of a user object stored on Parse. * + * @package Parse * @author Fosco Marotto */ class ParseUser extends ParseObject { + public static $parseClassName = "_User"; /** @@ -28,7 +30,7 @@ class ParseUser extends ParseObject */ public function getUsername() { - return $this->get("username"); + return $this->get("username"); } /** @@ -40,7 +42,7 @@ public function getUsername() */ public function setUsername($username) { - return $this->set("username", $username); + return $this->set("username", $username); } /** @@ -52,7 +54,7 @@ public function setUsername($username) */ public function setPassword($password) { - return $this->set("password", $password); + return $this->set("password", $password); } /** @@ -62,7 +64,7 @@ public function setPassword($password) */ public function getEmail() { - return $this->get("email"); + return $this->get("email"); } /** @@ -74,7 +76,7 @@ public function getEmail() */ public function setEmail($email) { - return $this->set("email", $email); + return $this->set("email", $email); } /** @@ -84,31 +86,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); } /** @@ -117,28 +119,27 @@ public function signUp() * @param string $username * @param string $password * - * @throws ParseException - * * @return ParseUser + * + * @throws ParseException */ 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 = ["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 = 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; } /** @@ -151,34 +152,33 @@ 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. - } - static::$currentUser = null; + $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. } - ParseClient::getStorage()->remove('user'); + static::$currentUser = null; + } + 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,31 +212,28 @@ 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 (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 (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; + $user->_opSetQueue = array(); + static::$currentUser = $user; + return $user; + } + return null; } /** @@ -246,18 +243,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; } /** @@ -267,31 +264,30 @@ 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. * - * @throws ParseException - * * @return null + * + * @throws ParseException */ 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." ); - } + } } /** @@ -305,8 +301,8 @@ public function save($useMasterKey = false) */ public static function requestPasswordReset($email) { - $json = json_encode(['email' => $email]); - ParseClient::_request('POST', '/1/requestPasswordReset', null, $json); + $json = json_encode(array('email' => $email)); + ParseClient::_request('POST', '/1/requestPasswordReset', null, $json); } /** @@ -314,6 +310,7 @@ 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 c1ef34f8..5f5650db 100644 --- a/tests/IncrementTest.php +++ b/tests/IncrementTest.php @@ -1,7 +1,8 @@ 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(); - } -} + $objAgain->save(); + } +} \ No newline at end of file diff --git a/tests/ParseACLTest.php b/tests/ParseACLTest.php index ae3425b6..683e77f3 100644 --- a/tests/ParseACLTest.php +++ b/tests/ParseACLTest.php @@ -1,384 +1,391 @@ 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 tearDown() - { - ParseTestHelper::tearDown(); + $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 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(); + try { + $object->destroy(); + $this->fail('delete 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) { - } + 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 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(); + try { + $object->destroy(); + $this->fail('delete should fail with object not found'); + } 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(); + 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 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'); + + $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 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()); + $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 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) { - } + try { + $object->destroy(); + $this->fail('delete should fail with object not found'); + } catch (\Parse\ParseException $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()); + 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 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()); + $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 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 309f7dc1..877cca3c 100644 --- a/tests/ParseAnalyticsTest.php +++ b/tests/ParseAnalyticsTest.php @@ -1,5 +1,6 @@ assertEquals($expectedJSON, $json); - ParseAnalytics::track($event, $params ?: []); - } + $json = ParseAnalytics::_toSaveJSON($params ?: array()); + $this->assertEquals($expectedJSON, $json); + ParseAnalytics::track($event, $params ?: array()); + } - 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 = [ + 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( 'foo' => 'bar', 'bar' => 'baz', - ]; - $this->assertAnalyticsValidation('testDimensions', $params, $expected); + 'someDate' => $date + ); + $this->assertAnalyticsValidation('testDate', $params, $expected); + } - $date = date(DATE_RFC3339); - $expected = '{"dimensions":{"foo":"bar","bar":"baz","someDate":"'. - $date.'"}}'; - $params = [ - 'foo' => 'bar', - 'bar' => 'baz', - 'someDate' => $date, - ]; - $this->assertAnalyticsValidation('testDate', $params, $expected); - } -} +} \ No newline at end of file diff --git a/tests/ParseBytesTest.php b/tests/ParseBytesTest.php index 88773d8f..00975754 100644 --- a/tests/ParseBytesTest.php +++ b/tests/ParseBytesTest.php @@ -1,50 +1,51 @@ 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")); } - 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")); - } -} +} \ No newline at end of file diff --git a/tests/ParseCloudTest.php b/tests/ParseCloudTest.php index 0ce9b824..04dc573e 100644 --- a/tests/ParseCloudTest.php +++ b/tests/ParseCloudTest.php @@ -1,39 +1,41 @@ 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); } - 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); - } -} +} \ No newline at end of file diff --git a/tests/ParseConfigTest.php b/tests/ParseConfigTest.php index 8b6939c0..b48066c2 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 9532459a..00869c0f 100644 --- a/tests/ParseFileTest.php +++ b/tests/ParseFileTest.php @@ -6,136 +6,137 @@ require_once 'ParseTestHelper.php'; -class ParseFileTest extends \PHPUnit_Framework_TestCase -{ +class ParseFileTest extends \PHPUnit_Framework_TestCase { + public static function setUpBeforeClass() { - ParseTestHelper::setUp(); + ParseTestHelper::setUp(); + } + + public function tearDown() + { + ParseTestHelper::tearDown(); + ParseTestHelper::clearClass("TestFileObject"); } - 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", + 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 93622d39..cc79d1e9 100644 --- a/tests/ParseGeoBoxTest.php +++ b/tests/ParseGeoBoxTest.php @@ -1,153 +1,156 @@ 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 04be1421..e68f488b 100644 --- a/tests/ParseGeoPointTest.php +++ b/tests/ParseGeoPointTest.php @@ -1,144 +1,147 @@ 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)); - } + $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'); - $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 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(); } - 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(); - } + $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); @@ -146,59 +149,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 9e6c4f5f..113ba3ac 100644 --- a/tests/ParseMemoryStorageTest.php +++ b/tests/ParseMemoryStorageTest.php @@ -1,67 +1,71 @@ 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 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 testRemove() - { - self::$parseStorage->set('foo', 'bar'); - self::$parseStorage->remove('foo'); - $this->assertNull(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 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)); + } - 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)); - } -} +} \ No newline at end of file diff --git a/tests/ParseObjectTest.php b/tests/ParseObjectTest.php index 96158a24..2262d5a0 100644 --- a/tests/ParseObjectTest.php +++ b/tests/ParseObjectTest.php @@ -1,926 +1,929 @@ 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 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 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 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 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 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 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 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 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 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 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 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 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 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 testFetchRemovesOldFields() + { + $obj = ParseObject::create('SimpleObject'); + $obj->set('foo', 'bar'); + $obj->set('test', 'foo'); + $obj->save(); - public function testCreatedAtAndUpdatedAtExposed() - { - $obj = ParseObject::create('TestObject'); - $obj->save(); - $this->assertNotNull($obj->getObjectId()); - $this->assertNotNull($obj->getCreatedAt()); - $this->assertNotNull($obj->getUpdatedAt()); - } + $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 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(); - } + $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 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.'); - 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.'); - } + $query = new ParseQuery("TestObject"); + $result = $query->get($obj->getObjectId()); + $this->assertFalse($result->has('foo'), 'foo was not removed.'); + } - 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 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 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 testDeletedKeysGetCleared() + { + $obj = ParseObject::create('TestObject'); + $obj->set('foo', 'bar'); + $obj->delete('foo'); + $obj->save(); + $obj->set('foo', 'baz'); + $obj->save(); - 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->assertEquals('baz', $result->get('foo')); + } - 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 testSettingAfterDeleting() + { + $obj = ParseObject::create('TestObject'); + $obj->set('foo', 'bar'); + $obj->save(); + $obj->delete('foo'); + $obj->set('foo', 'baz'); + $obj->save(); - 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->assertEquals('baz', $result->get('foo')); + } - 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 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 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')); - } + 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')); - 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')); - } + $query = new ParseQuery('TestObject'); + $result = $query->get($obj->getObjectId()); + $this->assertFalse($result->has('x')); + $this->assertNull($result->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')); - } + 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')); - 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')); - } + $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')); - - $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')); - 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')); - } + $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')); - - $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')); - 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')); - } + $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')); - - $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')); - 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')); - } + $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 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')); + } + + 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 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')); + } + + 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 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')); + } + + 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 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 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 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 testNewKeyIsDirtyAfterSave() + { + $obj = ParseObject::create("TestObject"); + $obj->save(); + $obj->set('content', 'x'); + $obj->fetch(); + $this->assertTrue($obj->isKeyDirty('content')); + } - 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( + public function testAddWithAnObject() + { + $parent = ParseObject::create("Person"); + $child = ParseObject::create("Person"); + $child->save(); + $parent->add("children", array($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'))); - 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)); - } + $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 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 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 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 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 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 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 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 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 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')), + 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')), 'Value was not stored as an array.'); - $this->assertEquals(0, count($returnedObject->get('baz'))); - } + $this->assertEquals(0, count($returnedObject->get('baz'))); + } - public function testArraySetAndAdd() - { - $obj = ParseObject::create('TestObject'); - $obj->setArray('arrayfield', ['a', 'b']); - $obj->save(); - $obj->add('arrayfield', ['c', 'd', 'e']); - $obj->save(); - } + 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()); + + $obj->set($key2, $value2); + $this->assertTrue($obj->isKeyDirty($key2)); + $this->assertFalse($obj->isKeyDirty($key1)); + $this->assertTrue($obj->isDirty()); - 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); + $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, [$value1, $value2, $value1]); - $this->assertTrue($obj->isDirty()); - - $obj->save(); - $this->assertFalse($obj->isDirty()); - } + $obj->add($key3, array($value1, $value2, $value1)); + $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'); - - $child->set('randomKey', 'randomValue'); - $this->assertTrue($child->isDirty()); + $obj->save(); + $this->assertFalse($obj->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'); + + $child->set('randomKey', 'randomValue'); + $this->assertTrue($child->isDirty()); + + $obj->set($key, $value); + $this->assertTrue($obj->isDirty()); - $obj->save(); - $this->assertFalse($obj->isDirty()); + $obj->save(); + $this->assertFalse($obj->isDirty()); - $obj->set($childKey, $child); - $this->assertTrue($obj->isKeyDirty($childKey)); - $this->assertTrue($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', [$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', 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()); // 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 = []; - 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 = 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 testEmptyObjectsAndArrays() - { - $obj = ParseObject::create('TestObject'); - $obj->setArray('arr', []); - $obj->setAssociativeArray('obj', []); - $saveOpArray = new SetOperation([]); - $saveOpAssoc = new SetOperation([], true); - $this->assertTrue( + 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( 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', [ + $obj->save(); + $obj->setAssociativeArray('obj', array( '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']); - } + '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()); - } + 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']); - } + 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 3582461a..d58066e0 100644 --- a/tests/ParsePushTest.php +++ b/tests/ParsePushTest.php @@ -1,47 +1,49 @@ array(''), + 'data' => array('alert' => 'sample message') + )); } - 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(), + 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(), 'expiration_time' => new DateTime(), - 'channels' => [], - ]); - } -} + 'channels' => array() + )); + } +} \ No newline at end of file diff --git a/tests/ParseQueryTest.php b/tests/ParseQueryTest.php index f714af03..71a23e73 100644 --- a/tests/ParseQueryTest.php +++ b/tests/ParseQueryTest.php @@ -1,28 +1,30 @@ 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 = []; - $this->saveObjects(5, function ($i) use (&$boxedNumberArray) { + public function testObjectIdEqualTo() + { + ParseTestHelper::clearClass("BoxedNumber"); + $boxedNumberArray = array(); + $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 = []; - $this->saveObjects(2, function ($i) use (&$items) { + public function testNotEqualToObject() + { + ParseTestHelper::clearClass("Container"); + ParseTestHelper::clearClass("Item"); + $items = array(); + $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 = []; - $query->each(function ($obj) use (&$values) { + $values = array(); + $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 = [ + public function testContainsAllDateArrayQueries() + { + ParseTestHelper::clearClass("DateSet"); + $dates1 = array( 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 = [ + new DateTime("2013-02-04T00:00:00Z") + ); + $dates2 = array( 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", [ + 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-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 = []; - $this->saveObjects(4, function ($i) use (&$messageList) { + public function testContainsAllObjectArrayQueries() + { + ParseTestHelper::clearClass("MessageSet"); + $messageList = array(); + $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", - [$messageList[0], $messageList[1], $messageList[3]] + $messageSet1 = ParseObject::create("MessageSet"); + $messageSet1->setArray("messages", $messageList); + $messageSet1->save(); + $messageSet2 = ParseObject::create("MessageSet"); + $messageSet2->setArray("message", + array($messageList[0], $messageList[1], $messageList[3]) ); - $messageSet2->save(); + $messageSet2->save(); - $query = new ParseQuery("MessageSet"); - $query->containsAll("messages", [$messageList[0], $messageList[2]]); - $results = $query->find(); - $this->assertEquals(1, count($results), + $query = new ParseQuery("MessageSet"); + $query->containsAll("messages", array($messageList[0], $messageList[2])); + $results = $query->find(); + $this->assertEquals(1, count($results), 'Did not return correct number of objects.'); - } + } - public function testContainedInObjectArrayQueries() - { - $messageList = []; - $this->saveObjects(4, function ($i) use (&$messageList) { + public function testContainedInObjectArrayQueries() + { + $messageList = array(); + $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", [$messageList[0], $messageList[2]]); - $results = $query->find(); - $this->assertEquals(2, count($results), + $query = new ParseQuery("TestObject"); + $query->containedIn("prior", array($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 = []; - $this->saveObjects(5, function ($i) use (&$objects) { + public function testObjectIdContainedInQueries() + { + ParseTestHelper::clearClass("BoxedNumber"); + $objects = array(); + $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 = []; - $this->saveObjects(3, function ($i) use ($numbers, &$objects) { + public function testOrderByUpdatedAtAsc() + { + $numbers = [3, 1, 2]; + $objects = array(); + $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 = []; - $this->saveObjects(3, function ($i) use ($numbers, &$objects) { + public function testOrderByUpdatedAtDesc() + { + $numbers = [3, 1, 2]; + $objects = array(); + $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 = []; - $this->saveObjects(5, function ($i) use (&$children) { + public function testIncludeArrayRelation() + { + ParseTestHelper::clearClass("Child"); + ParseTestHelper::clearClass("Parent"); + $children = array(); + $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 = []; - $this->saveObjects(2, function ($i) use (&$items) { + public function testEqualToObject() + { + ParseTestHelper::clearClass("Item"); + ParseTestHelper::clearClass("Container"); + $items = array(); + $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 = []; - $this->saveObjects(3, function ($i) use (&$items) { + public function provideTimeTestObjects() + { + ParseTestHelper::clearClass("TimeObject"); + $items = array(); + $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; + } - 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), + 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(); + 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()); + } - $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); + } - 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 c0aad55d..c19a1b17 100644 --- a/tests/ParseRelationTest.php +++ b/tests/ParseRelationTest.php @@ -2,20 +2,18 @@ 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. @@ -26,110 +24,112 @@ public function tearDown() */ public function saveObjects($numberOfObjects, $callback) { - $allObjects = []; - for ($i = 0; $i < $numberOfObjects; $i++) { - $allObjects[] = $callback($i); - } - ParseObject::saveAll($allObjects); + $allObjects = array(); + for ($i = 0; $i < $numberOfObjects; $i++) { + $allObjects[] = $callback($i); + } + ParseObject::saveAll($allObjects); } - public function testParseRelations() - { - $children = []; - $this->saveObjects(10, function ($i) use (&$children) { + public function testParseRelations() + { + $children = array(); + $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 = []; - $this->saveObjects(10, function ($i) use (&$children) { + } + + public function testQueriesOnRelationFields() + { + $children = array(); + $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 92b166af..26326343 100644 --- a/tests/ParseRoleTest.php +++ b/tests/ParseRoleTest.php @@ -1,220 +1,217 @@ aclPublic()); - $role->save(); - $this->assertNotNull($role->getObjectId(), "Role should have objectId."); - } + public function testCreateRole() + { + $role = ParseRole::createRole("Admin", $this->aclPublic()); + $role->save(); + $this->assertNotNull($role->getObjectId(), "Role should have objectId."); + } - public function testRoleWithoutACLFails() - { - $role = new ParseRole(); - $role->setName("Admin"); - $this->setExpectedException('Parse\ParseException', 'ACL'); - $role->save(); - } + public function testRoleWithoutACLFails() + { + $role = new ParseRole(); + $role->setName("Admin"); + $this->setExpectedException('Parse\ParseException', 'ACL'); + $role->save(); + } - 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 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 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 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 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 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 testRoleNameUnique() - { - $role = ParseRole::createRole("Admin", $this->aclPublic()); - $role->save(); - $role2 = ParseRole::createRole("Admin", $this->aclPublic()); - $this->setExpectedException('Parse\ParseException', 'duplicate'); - $role2->save(); - } + 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 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 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 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 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 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(); + 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); + return $acl; } - public function aclPublic() - { - $acl = new ParseACL(); - $acl->setPublicReadAccess(true); - $acl->setPublicWriteAccess(true); - - return $acl; - } - - public function createUser($username) - { - $user = new ParseUser(); - $user->setUsername($username); - $user->setPassword($username); + public function aclPublic() + { + $acl = new ParseACL(); + $acl->setPublicReadAccess(true); + $acl->setPublicWriteAccess(true); + return $acl; + } - return $user; - } + public function createUser($username) + { + $user = new ParseUser(); + $user->setUsername($username); + $user->setPassword($username); + 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( + 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(); + $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(); - $eden['apple'] = ParseObject::create("Things"); - $eden['apple']->set("name", "apple"); - $eden['apple']->set("ACL", $this->aclPrivateTo($eden['humans'])); + $eden['apple'] = ParseObject::create("Things"); + $eden['apple']->set("name", "apple"); + $eden['apple']->set("ACL", $this->aclPrivateTo($eden['humans'])); - $eden['garden'] = ParseObject::create("Things"); - $eden['garden']->set("name", "garden"); - $eden['garden']->set("ACL", $this->aclPrivateTo($eden['edenkin'])); + $eden['garden'] = ParseObject::create("Things"); + $eden['garden']->set("name", "garden"); + $eden['garden']->set("ACL", $this->aclPrivateTo($eden['edenkin'])); - ParseObject::saveAll([$eden['apple'], $eden['garden']]); + ParseObject::saveAll([$eden['apple'], $eden['garden']]); + + return $eden; + + } - return $eden; - } } diff --git a/tests/ParseSessionStorageTest.php b/tests/ParseSessionStorageTest.php index efa97639..a7cdbfbd 100644 --- a/tests/ParseSessionStorageTest.php +++ b/tests/ParseSessionStorageTest.php @@ -1,72 +1,76 @@ clear(); + } - public function tearDown() - { - ParseTestHelper::tearDown(); - self::$parseStorage->clear(); - } + public static function tearDownAfterClass() + { + session_destroy(); + } - public static function tearDownAfterClass() - { - session_destroy(); - } + public function testIsUsingParseSession() + { + $this->assertTrue(self::$parseStorage instanceof Parse\ParseSessionStorage); + } - public function testIsUsingParseSession() - { - $this->assertTrue(self::$parseStorage instanceof Parse\ParseSessionStorage); - } + public function testSetAndGet() + { + self::$parseStorage->set('foo', 'bar'); + $this->assertEquals('bar', self::$parseStorage->get('foo')); + } - 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 testRemove() - { - self::$parseStorage->set('foo', 'bar'); - self::$parseStorage->remove('foo'); - $this->assertNull(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 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)); + } - 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 59afc240..42db1846 100644 --- a/tests/ParseSessionTest.php +++ b/tests/ParseSessionTest.php @@ -1,57 +1,61 @@ 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); } - 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); - } -} +} \ No newline at end of file diff --git a/tests/ParseSubclassTest.php b/tests/ParseSubclassTest.php index ecac3483..cf75b199 100644 --- a/tests/ParseSubclassTest.php +++ b/tests/ParseSubclassTest.php @@ -1,5 +1,7 @@ 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')); } - 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')); - } -} +} \ No newline at end of file diff --git a/tests/ParseTestHelper.php b/tests/ParseTestHelper.php index e3eee7ab..fcba5823 100644 --- a/tests/ParseTestHelper.php +++ b/tests/ParseTestHelper.php @@ -1,32 +1,35 @@ 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 78e0ff4e..aefad0b8 100644 --- a/tests/ParseUserTest.php +++ b/tests/ParseUserTest.php @@ -1,5 +1,6 @@ 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([$item1, $item2, $user]); - } + ParseObject::saveAll(array($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'); - } - - 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(); + ParseUser::requestPasswordReset('non_existent@example.com'); + } - $this->assertEquals($userAgain->getObjectId(), $user->getObjectId()); - $this->assertEquals( + 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 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 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 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 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; } - - public function testSavingUserThrows() - { - $user = new ParseUser(); - $user->setUsername('asdf'); - $user->setPassword('zxcv'); - $this->setExpectedException('Parse\ParseException', 'You must call signUp'); - $user->save(); + $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; } - 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()); - } + $inList = array($userList[0], $userList[3], $userList[3]); + $query = new ParseQuery("TestObject"); + $query->containedIn('from', $inList); + $results = $query->find(); - 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); - } + $this->assertEquals(3, count($results)); + } - 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 testSavingUserThrows() + { + $user = new ParseUser(); + $user->setUsername('asdf'); + $user->setPassword('zxcv'); + $this->setExpectedException('Parse\ParseException', 'You must call signUp'); + $user->save(); + } - 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 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 testUserWithMissingUsername() - { - $user = new ParseUser(); - $user->setPassword('test'); - $this->setExpectedException('Parse\ParseException', 'empty name'); - $user->signUp(); - } + 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 testUserWithMissingPassword() - { - $user = new ParseUser(); - $user->setUsername('test'); - $this->setExpectedException('Parse\ParseException', 'empty password'); - $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 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 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 testUserWithMissingUsername() + { + $user = new ParseUser(); + $user->setPassword('test'); + $this->setExpectedException('Parse\ParseException', 'empty name'); + $user->signUp(); + } + + 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')); + } + +} \ No newline at end of file diff --git a/tests/phpunit.xml b/tests/phpunit.xml index fe954497..c6d42c16 100644 --- a/tests/phpunit.xml +++ b/tests/phpunit.xml @@ -5,4 +5,4 @@ tests - + \ No newline at end of file From 9c5a5929882b30660e121bad29d097275730d320 Mon Sep 17 00:00:00 2001 From: Graham Campbell Date: Tue, 31 Mar 2015 23:33:17 +0100 Subject: [PATCH 2/4] Fixes --- .gitignore | 2 +- CONTRIBUTING.md | 6 ++--- README.md | 38 ++++++++++++++-------------- autoload.php | 67 +++++++++++++++++++++++-------------------------- 4 files changed, 55 insertions(+), 58 deletions(-) diff --git a/.gitignore b/.gitignore index 157ff0c5..82cfc4e9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,3 @@ .idea -vendor/ composer.lock +vendor diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fe9db8f4..30e9a513 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -5,13 +5,13 @@ For us to accept contributions you will have to first have signed the [Contributor License Agreement]. When committing, keep all lines to less than 80 characters, and try to -follow the existing style. Before creating a pull request, squash your commits +follow the existing style. Before creating a pull request, squash your commits into a single commit. Please provide ample explanation in the commit message. Installation ------------ -Testing the Parse PHP SDK involves some set-up. You'll need to create a Parse +Testing the Parse PHP SDK involves some set-up. You'll need to create a Parse App just for testing, and deploy some cloud code to it. * [Get Composer], the PHP package manager. @@ -31,4 +31,4 @@ At present the full suite of tests takes around 20 minutes. [Get Composer]: https://getcomposer.org/download/ [Contributor License Agreement]: https://developers.facebook.com/opensource/cla -[Create Parse App]: https://parse.com/apps/new \ No newline at end of file +[Create Parse App]: https://parse.com/apps/new diff --git a/README.md b/README.md index 514e7b6d..6a9135cc 100644 --- a/README.md +++ b/README.md @@ -7,14 +7,14 @@ from your PHP app or script. Installation ------------ -[Get Composer], the PHP package manager. Then create a composer.json file in +[Get Composer], the PHP package manager. Then create a composer.json file in your projects root folder, containing: ```json { - "require": { - "parse/php-sdk" : "1.1.*" - } + "require": { + "parse/php-sdk" : "1.1.*" + } } ``` @@ -51,7 +51,7 @@ Usage Check out the [Parse PHP Guide] for the full documentation. -Add the "use" declarations where you'll be using the classes. For all of the +Add the "use" declarations where you'll be using the classes. For all of the sample code in this file: ```php @@ -80,7 +80,7 @@ $object->set("elephant", "php"); $object->set("today", new DateTime()); $object->setArray("mylist", [1, 2, 3]); $object->setAssociativeArray( - "languageTypes", array("php" => "awesome", "ruby" => "wtf") + "languageTypes", array("php" => "awesome", "ruby" => "wtf") ); // Save: @@ -95,16 +95,16 @@ $user = new ParseUser(); $user->setUsername("foo"); $user->setPassword("Q2w#4!o)df"); try { - $user->signUp(); + $user->signUp(); } catch (ParseException $ex) { - // error in $ex->getMessage(); + // error in $ex->getMessage(); } // Login try { - $user = ParseUser::logIn("foo", "Q2w#4!o)df"); + $user = ParseUser::logIn("foo", "Q2w#4!o)df"); } catch(ParseException $ex) { - // error in $ex->getMessage(); + // error in $ex->getMessage(); } // Current user @@ -147,7 +147,7 @@ $first = $query->first(); // Process ALL (without limit) results with "each". // Will throw if sort, skip, or limit is used. $query->each(function($obj) { - echo $obj->getObjectId(); + echo $obj->getObjectId(); }); ``` @@ -161,8 +161,8 @@ Analytics: ```php ParseAnalytics::track("logoReaction", array( - "saw" => "elephant", - "said" => "cute" + "saw" => "elephant", + "said" => "cute" )); ``` @@ -178,7 +178,7 @@ $contents = $file->getData(); // Upload from a local file: $file = ParseFile::createFromFile( - "/tmp/foo.bar", "Parse.txt", "text/plain" + "/tmp/foo.bar", "Parse.txt", "text/plain" ); // Upload from variable contents (string, binary) @@ -192,16 +192,16 @@ $data = array("alert" => "Hi!"); // Push to Channels ParsePush::send(array( - "channels" => ["PHPFans"], - "data" => $data + "channels" => ["PHPFans"], + "data" => $data )); // Push to Query $query = ParseInstallation::query(); $query->equalTo("design", "rad"); ParsePush::send(array( - "where" => $query, - "data" => $data + "where" => $query, + "data" => $data )); ``` @@ -209,7 +209,7 @@ Contributing / Testing ---------------------- See the CONTRIBUTORS.md file for information on testing and contributing to -the Parse PHP SDK. We welcome fixes and enhancements. +the Parse PHP SDK. We welcome fixes and enhancements. [Get Composer]: https://getcomposer.org/download/ [Parse PHP Guide]: https://www.parse.com/docs/php_guide diff --git a/autoload.php b/autoload.php index a3ef6aa8..190bd15a 100755 --- a/autoload.php +++ b/autoload.php @@ -1,48 +1,45 @@ '; - - // if the file exists, require it - if ( file_exists( $file ) ) { - require $file; - } -}); \ No newline at end of file + // Parse class prefix + $prefix = 'Parse\\'; + + // base directory for the namespace prefix + $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 + return; + } + + // get the relative class name + $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'; + + // if the file exists, require it + if ( file_exists( $file ) ) { + require $file; + } +}); From f624470338d1cd97949b7448afa852463d0fa409 Mon Sep 17 00:00:00 2001 From: Graham Campbell Date: Tue, 31 Mar 2015 23:33:24 +0100 Subject: [PATCH 3/4] Fixed indentation --- src/Parse/Internal/AddOperation.php | 170 +- src/Parse/Internal/AddUniqueOperation.php | 214 +- src/Parse/Internal/DeleteOperation.php | 72 +- src/Parse/Internal/Encodable.php | 18 +- src/Parse/Internal/FieldOperation.php | 44 +- src/Parse/Internal/IncrementOperation.php | 154 +- src/Parse/Internal/ParseRelationOperation.php | 482 +-- src/Parse/Internal/RemoveOperation.php | 202 +- src/Parse/Internal/SetOperation.php | 142 +- src/Parse/ParseACL.php | 1024 +++--- src/Parse/ParseAggregateException.php | 50 +- src/Parse/ParseAnalytics.php | 120 +- src/Parse/ParseBytes.php | 114 +- src/Parse/ParseClient.php | 732 ++-- src/Parse/ParseCloud.php | 52 +- src/Parse/ParseConfig.php | 48 +- src/Parse/ParseException.php | 30 +- src/Parse/ParseFile.php | 816 ++--- src/Parse/ParseGeoPoint.php | 162 +- src/Parse/ParseInstallation.php | 8 +- src/Parse/ParseMemoryStorage.php | 92 +- src/Parse/ParseObject.php | 2212 ++++++------ src/Parse/ParsePush.php | 108 +- src/Parse/ParseQuery.php | 1528 ++++----- src/Parse/ParseRelation.php | 226 +- src/Parse/ParseRole.php | 166 +- src/Parse/ParseSession.php | 132 +- src/Parse/ParseSessionStorage.php | 96 +- src/Parse/ParseStorageInterface.php | 108 +- src/Parse/ParseUser.php | 554 +-- tests/IncrementTest.php | 448 +-- tests/ParseACLTest.php | 716 ++-- tests/ParseAnalyticsTest.php | 122 +- tests/ParseBytesTest.php | 82 +- tests/ParseCloudTest.php | 60 +- tests/ParseConfigTest.php | 20 +- tests/ParseFileTest.php | 260 +- tests/ParseGeoBoxTest.php | 266 +- tests/ParseGeoPointTest.php | 380 +-- tests/ParseMemoryStorageTest.php | 102 +- tests/ParseObjectTest.php | 1830 +++++----- tests/ParsePushTest.php | 76 +- tests/ParseQueryTest.php | 3008 ++++++++--------- tests/ParseRelationTest.php | 250 +- tests/ParseRoleTest.php | 406 +-- tests/ParseSessionStorageTest.php | 108 +- tests/ParseSessionTest.php | 96 +- tests/ParseSubclassTest.php | 50 +- tests/ParseTestHelper.php | 44 +- tests/ParseUserTest.php | 830 ++--- tests/bootstrap.php | 7 +- tests/cloudcode/cloud/main.js | 76 +- tests/phpunit.xml | 2 +- 53 files changed, 9556 insertions(+), 9559 deletions(-) diff --git a/src/Parse/Internal/AddOperation.php b/src/Parse/Internal/AddOperation.php index 9584f500..96c565f5 100755 --- a/src/Parse/Internal/AddOperation.php +++ b/src/Parse/Internal/AddOperation.php @@ -8,101 +8,101 @@ /** * Class AddOperation - FieldOperation for adding object(s) to array fields * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ class AddOperation implements FieldOperation { - /** - * @var - Array with objects to add. - */ - private $objects; + /** + * @var - Array with objects to add. + */ + private $objects; - /** - * Creates an AddOperation with the provided objects. - * - * @param array $objects Objects to add. - * - * @throws ParseException - */ - public function __construct($objects) - { - if (!is_array($objects)) { - throw new ParseException("AddOperation requires an array."); + /** + * Creates an AddOperation with the provided objects. + * + * @param array $objects Objects to add. + * + * @throws ParseException + */ + public function __construct($objects) + { + if (!is_array($objects)) { + throw new ParseException("AddOperation requires an array."); + } + $this->objects = $objects; } - $this->objects = $objects; - } - /** - * Gets the objects for this operation. - * - * @return mixed - */ - public function getValue() - { - return $this->objects; - } - - /** - * Returns associative array representing encoded operation. - * - * @return array - */ - public function _encode() - { - return array('__op' => 'Add', - 'objects' => ParseClient::_encode($this->objects, true)); - } - - /** - * Takes a previous operation and returns a merged operation to replace it. - * - * @param FieldOperation $previous Previous operation. - * - * @return FieldOperation Merged operation. - * @throws ParseException - */ - public function _mergeWithPrevious($previous) - { - if (!$previous) { - return $this; - } - if ($previous instanceof DeleteOperation) { - return new SetOperation($this->objects); + /** + * Gets the objects for this operation. + * + * @return mixed + */ + public function getValue() + { + return $this->objects; } - if ($previous instanceof SetOperation) { - $oldList = $previous->getValue(); - return new SetOperation( - array_merge((array)$oldList, (array)$this->objects) - ); + + /** + * Returns associative array representing encoded operation. + * + * @return array + */ + public function _encode() + { + return array('__op' => 'Add', + 'objects' => ParseClient::_encode($this->objects, true)); } - if ($previous instanceof AddOperation) { - $oldList = $previous->getValue(); - return new SetOperation( - array_merge((array)$oldList, (array)$this->objects) - ); + + /** + * Takes a previous operation and returns a merged operation to replace it. + * + * @param FieldOperation $previous Previous operation. + * + * @return FieldOperation Merged operation. + * @throws ParseException + */ + 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 instanceof AddOperation) { + $oldList = $previous->getValue(); + return new SetOperation( + array_merge((array)$oldList, (array)$this->objects) + ); + } + throw new ParseException( + 'Operation is invalid after previous operation.' + ); } - throw new ParseException( - 'Operation is invalid after previous operation.' - ); - } - /** - * Applies current operation, returns resulting value. - * - * @param mixed $oldValue Value prior to this operation. - * @param mixed $obj Value being applied. - * @param string $key Key this operation affects. - * - * @return array - */ - public function _apply($oldValue, $obj, $key) - { - if (!$oldValue) { - return $this->objects; + /** + * Applies current operation, returns resulting value. + * + * @param mixed $oldValue Value prior to this operation. + * @param mixed $obj Value being applied. + * @param string $key Key this operation affects. + * + * @return array + */ + public function _apply($oldValue, $obj, $key) + { + if (!$oldValue) { + return $this->objects; + } + return array_merge((array)$oldValue, (array)$this->objects); } - return array_merge((array)$oldValue, (array)$this->objects); - } -} \ No newline at end of file +} diff --git a/src/Parse/Internal/AddUniqueOperation.php b/src/Parse/Internal/AddUniqueOperation.php index c4666f31..66f68f85 100755 --- a/src/Parse/Internal/AddUniqueOperation.php +++ b/src/Parse/Internal/AddUniqueOperation.php @@ -8,129 +8,129 @@ /** * Class AddUniqueOperation - Operation to add unique objects to an array key. * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ class AddUniqueOperation implements FieldOperation { - /** - * @var - Array containing objects to add. - */ - private $objects; + /** + * @var - Array containing objects to add. + */ + private $objects; - /** - * Creates an operation for adding unique values to an array key. - * - * @param array $objects Objects to add. - * - * @throws ParseException - */ - public function __construct($objects) - { - if (!is_array($objects)) { - throw new ParseException("AddUniqueOperation requires an array."); + /** + * Creates an operation for adding unique values to an array key. + * + * @param array $objects Objects to add. + * + * @throws ParseException + */ + public function __construct($objects) + { + if (!is_array($objects)) { + throw new ParseException("AddUniqueOperation requires an array."); + } + $this->objects = $objects; } - $this->objects = $objects; - } - - /** - * Returns the values for this operation. - * - * @return mixed - */ - public function getValue() - { - return $this->objects; - } - - /** - * Returns an associative array encoding of this operation. - * - * @return array - */ - public function _encode() - { - return array('__op' => 'AddUnique', - 'objects' => ParseClient::_encode($this->objects, true)); - } - /** - * Merge this operation with the previous operation and return the result. - * - * @param FieldOperation $previous Previous Operation. - * - * @return FieldOperation Merged Operation. - * @throws ParseException - */ - 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); + /** + * Returns the values for this operation. + * + * @return mixed + */ + public function getValue() + { + return $this->objects; } - throw new ParseException( - 'Operation is invalid after previous operation.' - ); - } - /** - * Apply the current operation and return the result. - * - * @param mixed $oldValue Value prior to this operation. - * @param array $obj Value being applied. - * @param string $key Key this operation affects. - * - * @return array - */ - public function _apply($oldValue, $obj, $key) - { - if (!$oldValue) { - return $this->objects; + /** + * Returns an associative array encoding of this operation. + * + * @return array + */ + public function _encode() + { + return array('__op' => 'AddUnique', + 'objects' => ParseClient::_encode($this->objects, true)); } - if (!is_array($oldValue)) { - $oldValue = (array)$oldValue; + + /** + * Merge this operation with the previous operation and return the result. + * + * @param FieldOperation $previous Previous Operation. + * + * @return FieldOperation Merged Operation. + * @throws ParseException + */ + 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( + 'Operation is invalid after previous operation.' + ); } - foreach ($this->objects as $object) { - if ($object instanceof ParseObject && $object->getObjectId()) { - if (!$this->isParseObjectInArray($object, $oldValue)) { - $oldValue[] = $object; + + /** + * Apply the current operation and return the result. + * + * @param mixed $oldValue Value prior to this operation. + * @param array $obj Value being applied. + * @param string $key Key this operation affects. + * + * @return array + */ + public function _apply($oldValue, $obj, $key) + { + if (!$oldValue) { + return $this->objects; } - } else if (is_object($object)) { - if (!in_array($object, $oldValue, true)) { - $oldValue[] = $object; + if (!is_array($oldValue)) { + $oldValue = (array)$oldValue; } - } else { - if (!in_array($object, $oldValue, true)) { - $oldValue[] = $object; + 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; + } + } } - } + return $oldValue; } - 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; } - return false; - } -} \ No newline at end of file +} diff --git a/src/Parse/Internal/DeleteOperation.php b/src/Parse/Internal/DeleteOperation.php index c55e0544..7aaee5f0 100755 --- a/src/Parse/Internal/DeleteOperation.php +++ b/src/Parse/Internal/DeleteOperation.php @@ -5,46 +5,46 @@ /** * Class DeleteOperation - FieldOperation to remove a key from an object. * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ class DeleteOperation implements FieldOperation { - /** - * Returns an associative array encoding of the current operation. - * - * @return array Associative array encoding the operation. - */ - public function _encode() - { - return array('__op' => 'Delete'); - } + /** + * Returns an associative array encoding of the current operation. + * + * @return array Associative array encoding the operation. + */ + public function _encode() + { + return array('__op' => 'Delete'); + } - /** - * Applies the current operation and returns the result. - * - * @param mixed $oldValue Value prior to this operation. - * @param mixed $object Unused for this operation type. - * @param string $key Key to remove from the target object. - * - * @return null - */ - public function _apply($oldValue, $object, $key) - { - return null; - } + /** + * Applies the current operation and returns the result. + * + * @param mixed $oldValue Value prior to this operation. + * @param mixed $object Unused for this operation type. + * @param string $key Key to remove from the target object. + * + * @return null + */ + public function _apply($oldValue, $object, $key) + { + return null; + } - /** - * Merge this operation with a previous operation and return the result. - * - * @param FieldOperation $previous Previous operation. - * - * @return FieldOperation Always returns the current operation. - */ - public function _mergeWithPrevious($previous) - { - return $this; - } + /** + * Merge this operation with a previous operation and return the result. + * + * @param FieldOperation $previous Previous operation. + * + * @return FieldOperation Always returns the current operation. + */ + public function _mergeWithPrevious($previous) + { + return $this; + } -} \ No newline at end of file +} diff --git a/src/Parse/Internal/Encodable.php b/src/Parse/Internal/Encodable.php index 0236e8e3..0a6aa6a9 100644 --- a/src/Parse/Internal/Encodable.php +++ b/src/Parse/Internal/Encodable.php @@ -6,17 +6,17 @@ * Class Encodable - Interface for Parse Classes which provide an encode * method. * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ interface Encodable { - /** - * Returns an associate array encoding of the implementing class. - * - * @return mixed - */ - public function _encode(); + /** + * 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..13bf1112 100755 --- a/src/Parse/Internal/FieldOperation.php +++ b/src/Parse/Internal/FieldOperation.php @@ -5,31 +5,31 @@ /** * Class FieldOperation - Interface for all Parse Field Operations. * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ interface FieldOperation extends Encodable { - /** - * Applies the current operation and returns the result. - * - * @param mixed $oldValue Value prior to this operation. - * @param mixed $object Value for this operation. - * @param string $key Key to perform this operation on. - * - * @return mixed Result of the operation. - */ - public function _apply($oldValue, $object, $key); + /** + * Applies the current operation and returns the result. + * + * @param mixed $oldValue Value prior to this operation. + * @param mixed $object Value for this operation. + * @param string $key Key to perform this operation on. + * + * @return mixed Result of the operation. + */ + public function _apply($oldValue, $object, $key); - /** - * Merge this operation with a previous operation and return the new - * operation. - * - * @param FieldOperation $previous Previous operation. - * - * @return FieldOperation Merged operation result. - */ - public function _mergeWithPrevious($previous); + /** + * Merge this operation with a previous operation and return the new + * operation. + * + * @param FieldOperation $previous Previous operation. + * + * @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..41818049 100755 --- a/src/Parse/Internal/IncrementOperation.php +++ b/src/Parse/Internal/IncrementOperation.php @@ -7,93 +7,93 @@ /** * Class IncrementOperation - Operation to increment numeric object key. * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ class IncrementOperation implements FieldOperation { - /** - * @var int - Amount to increment by. - */ - private $value; + /** + * @var int - Amount to increment by. + */ + private $value; - /** - * Creates an IncrementOperation object. - * - * @param int $value Amount to increment by. - */ - public function __construct($value = 1) - { - $this->value = $value; - } - - /** - * Get the value for this operation. - * - * @return int - */ - public function getValue() - { - return $this->value; - } - - /** - * Get an associative array encoding for this operation. - * - * @return array - */ - public function _encode() - { - return array('__op' => 'Increment', 'amount' => $this->value); - } - - /** - * Apply the current operation and return the result. - * - * @param mixed $oldValue Value prior to this operation. - * @param mixed $object Value for this operation. - * @param string $key Key to set Value on. - * - * @return int New value after application. - * @throws ParseException - */ - public function _apply($oldValue, $object, $key) - { - if ($oldValue && !is_numeric($oldValue)) { - throw new ParseException('Cannot increment a non-number type.'); + /** + * Creates an IncrementOperation object. + * + * @param int $value Amount to increment by. + */ + public function __construct($value = 1) + { + $this->value = $value; } - return $oldValue + $this->value; - } - /** - * Merge this operation with a previous operation and return the - * resulting operation. - * - * @param FieldOperation $previous Previous Operation. - * - * @return FieldOperation - * @throws ParseException - */ - public function _mergeWithPrevious($previous) - { - if (!$previous) { - return $this; + /** + * Get the value for this operation. + * + * @return int + */ + public function getValue() + { + return $this->value; } - if ($previous instanceof DeleteOperation) { - return new SetOperation($this->value); + + /** + * Get an associative array encoding for this operation. + * + * @return array + */ + public function _encode() + { + return array('__op' => 'Increment', 'amount' => $this->value); } - if ($previous instanceof SetOperation) { - return new SetOperation($previous->getValue() + $this->value); + + /** + * Apply the current operation and return the result. + * + * @param mixed $oldValue Value prior to this operation. + * @param mixed $object Value for this operation. + * @param string $key Key to set Value on. + * + * @return int New value after application. + * @throws ParseException + */ + 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 ($previous instanceof IncrementOperation) { - return new IncrementOperation( - $previous->getValue() + $this->value - ); + + /** + * Merge this operation with a previous operation and return the + * resulting operation. + * + * @param FieldOperation $previous Previous Operation. + * + * @return FieldOperation + * @throws ParseException + */ + 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( + $previous->getValue() + $this->value + ); + } + throw new ParseException( + 'Operation is invalid after previous operation.' + ); } - 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..6a1c80e8 100644 --- a/src/Parse/Internal/ParseRelationOperation.php +++ b/src/Parse/Internal/ParseRelationOperation.php @@ -8,273 +8,273 @@ /** * ParseRelationOperation - A class that is used to manage ParseRelation changes such as object add or remove. * - * @package Parse - * @author Mohamed Madbouli + * @package Parse + * @author Mohamed Madbouli */ -class ParseRelationOperation implements FieldOperation{ +class ParseRelationOperation implements FieldOperation{ - /** - * @var string - The className of the target objects. - */ - private $targetClassName; - /** - * @var array - Array of objects to add to this relation. - */ - private $relationsToAdd = array(); - /** - * @var array - Array of objects to remove from this relation. - */ - private $relationsToRemove = array(); + /** + * @var string - The className of the target objects. + */ + private $targetClassName; + /** + * @var array - Array of objects to add to this relation. + */ + private $relationsToAdd = array(); + /** + * @var array - Array of objects to remove from this relation. + */ + private $relationsToRemove = array(); - 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'] = 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.'); + } } - } - /** - * Helper function to check that all passed ParseObjects have same class name - * and assign targetClassName variable. - * - * @param array $objects ParseObject array. - * - * @throws \Exception - */ - private function checkAndAssignClassName($objects) - { - 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.'); - } + /** + * Helper function to check that all passed ParseObjects have same class name + * and assign targetClassName variable. + * + * @param array $objects ParseObject array. + * + * @throws \Exception + */ + private function checkAndAssignClassName($objects) + { + 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.'); + } + } } - } - /** - * Adds an object or array of objects to the array, replacing any - * existing instance of the same object. - * - * @param array $objects Array of ParseObjects to add. - * @param array $container Array to contain new ParseObjects. - */ - 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; - } + /** + * Adds an object or array of objects to the array, replacing any + * existing instance of the same object. + * + * @param array $objects Array of ParseObjects to add. + * @param array $container Array to contain new ParseObjects. + */ + 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; + } + } } - } - /** - * Removes an object (and any duplicate instances of that object) from the array. - * - * @param array $objects Array of ParseObjects to remove. - * @param array $container Array to remove from it ParseObjects. - */ - 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 (!empty($nullObjects)) { - self::removeElementsFromArray($nullObjects, $container['null']); + /** + * Removes an object (and any duplicate instances of that object) from the array. + * + * @param array $objects Array of ParseObjects to remove. + * @param array $container Array to remove from it ParseObjects. + */ + 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 (!empty($nullObjects)) { + self::removeElementsFromArray($nullObjects, $container['null']); + } } - } - /** - * Applies the current operation and returns the result. - * - * @param mixed $oldValue Value prior to this operation. - * @param mixed $object Value for this operation. - * @param string $key Key to perform this operation on. - * - * @return mixed Result of the operation. - * - * @throws \Exception - */ - 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 - && $oldValue->getTargetClass() !== $this->targetClassName) { - 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."); + /** + * Applies the current operation and returns the result. + * + * @param mixed $oldValue Value prior to this operation. + * @param mixed $object Value for this operation. + * @param string $key Key to perform this operation on. + * + * @return mixed Result of the operation. + * + * @throws \Exception + */ + 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 + && $oldValue->getTargetClass() !== $this->targetClassName) { + 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."); + } } - } - /** - * Merge this operation with a previous operation and return the new - * operation. - * - * @param FieldOperation $previous Previous operation. - * - * @return FieldOperation Merged operation result. - * - * @throws \Exception - */ - public function _mergeWithPrevious($previous) - { - 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( - $this->relationsToAdd); - $newRelationToRemove = self::convertToOneDimensionalArray( - $this->relationsToRemove); + /** + * Merge this operation with a previous operation and return the new + * operation. + * + * @param FieldOperation $previous Previous operation. + * + * @return FieldOperation Merged operation result. + * + * @throws \Exception + */ + public function _mergeWithPrevious($previous) + { + 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( + $this->relationsToAdd); + $newRelationToRemove = self::convertToOneDimensionalArray( + $this->relationsToRemove); - $previous->addObjects($newRelationToAdd, - $previous->relationsToAdd); - $previous->removeObjects($newRelationToAdd, - $previous->relationsToRemove); + $previous->addObjects($newRelationToAdd, + $previous->relationsToAdd); + $previous->removeObjects($newRelationToAdd, + $previous->relationsToRemove); - $previous->removeObjects($newRelationToRemove, - $previous->relationsToAdd); - $previous->addObjects($newRelationToRemove, - $previous->relationsToRemove); + $previous->removeObjects($newRelationToRemove, + $previous->relationsToAdd); + $previous->addObjects($newRelationToRemove, + $previous->relationsToRemove); - $newRelationToAdd = self::convertToOneDimensionalArray( - $previous->relationsToAdd); - $newRelationToRemove = self::convertToOneDimensionalArray( - $previous->relationsToRemove); + $newRelationToAdd = self::convertToOneDimensionalArray( + $previous->relationsToAdd); + $newRelationToRemove = self::convertToOneDimensionalArray( + $previous->relationsToRemove); - return new ParseRelationOperation($newRelationToAdd, - $newRelationToRemove); + 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 - */ - public function _encode() - { - $addRelation = array(); - $removeRelation = array(); - if (!empty($this->relationsToAdd)) { - $addRelation = array( - '__op' => 'AddRelation', - 'objects' => ParseClient::_encode( - self::convertToOneDimensionalArray($this->relationsToAdd), - true - ) - ); - } - if (!empty($this->relationsToRemove)) { - $removeRelation = array( - '__op' => 'RemoveRelation', - 'objects' => ParseClient::_encode( - self::convertToOneDimensionalArray($this->relationsToRemove), - true - ) - ); - } - if (!empty($addRelation) && !empty($removeRelation)) { - return array( - '__op' => 'Batch', - 'ops' => [$addRelation, $removeRelation] - ); + /** + * Returns an associative array encoding of the current operation. + * + * @return mixed + * + * @throws \Exception + */ + public function _encode() + { + $addRelation = array(); + $removeRelation = array(); + if (!empty($this->relationsToAdd)) { + $addRelation = array( + '__op' => 'AddRelation', + 'objects' => ParseClient::_encode( + self::convertToOneDimensionalArray($this->relationsToAdd), + true + ) + ); + } + if (!empty($this->relationsToRemove)) { + $removeRelation = array( + '__op' => 'RemoveRelation', + 'objects' => ParseClient::_encode( + self::convertToOneDimensionalArray($this->relationsToRemove), + true + ) + ); + } + if (!empty($addRelation) && !empty($removeRelation)) { + return array( + '__op' => 'Batch', + 'ops' => [$addRelation, $removeRelation] + ); + } + return empty($addRelation) ? $removeRelation : $addRelation; } - return empty($addRelation) ? $removeRelation : $addRelation; - } - - public function _getTargetClass() - { - return $this->targetClassName; - } - /** - * Remove element or array of elements from one dimensional array. - * - * @param mixed $elements - * @param array $array - */ - public static function removeElementsFromArray($elements, &$array) - { - if (!is_array($elements)) { - $elements = [$elements]; + public function _getTargetClass() + { + return $this->targetClassName; } - $length = count($array); - for ($i = 0; $i < $length; $i++) { - $exist = false; - foreach ($elements as $element) { - if ($array[$i] == $element) { - $exist = true; - break; + + /** + * Remove element or array of elements from one dimensional array. + * + * @param mixed $elements + * @param array $array + */ + 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 ($exist) { + unset($array[$i]); + } } - } - if ($exist) { - unset($array[$i]); - } + $array = array_values($array); } - $array = array_values($array); - } - /** - * Convert any array to one dimensional array. - * - * @param array $array - * - * @return array - */ - public static function convertToOneDimensionalArray($array) - { - $newArray = array(); - if (is_array($array)) { - foreach ($array as $value) { - $newArray = array_merge($newArray, self::convertToOneDimensionalArray($value)); - } - } else { - $newArray[] = $array; + /** + * Convert any array to one dimensional array. + * + * @param array $array + * + * @return array + */ + public static function convertToOneDimensionalArray($array) + { + $newArray = array(); + if (is_array($array)) { + foreach ($array as $value) { + $newArray = array_merge($newArray, self::convertToOneDimensionalArray($value)); + } + } else { + $newArray[] = $array; + } + return $newArray; } - return $newArray; - } } diff --git a/src/Parse/Internal/RemoveOperation.php b/src/Parse/Internal/RemoveOperation.php index 0e44f11b..16cbac6b 100644 --- a/src/Parse/Internal/RemoveOperation.php +++ b/src/Parse/Internal/RemoveOperation.php @@ -10,118 +10,118 @@ * Class RemoveOperation - FieldOperation for removing object(s) from array * fields * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ class RemoveOperation implements FieldOperation { - /** - * @var - Array with objects to remove. - */ - private $objects; + /** + * @var - Array with objects to remove. + */ + private $objects; - /** - * Creates an RemoveOperation with the provided objects. - * - * @param array $objects Objects to remove. - * - * @throws ParseException - */ - public function __construct($objects) - { - if (!is_array($objects)) { - throw new ParseException("RemoveOperation requires an array."); + /** + * Creates an RemoveOperation with the provided objects. + * + * @param array $objects Objects to remove. + * + * @throws ParseException + */ + public function __construct($objects) + { + if (!is_array($objects)) { + throw new ParseException("RemoveOperation requires an array."); + } + $this->objects = $objects; } - $this->objects = $objects; - } - - /** - * Gets the objects for this operation. - * - * @return mixed - */ - public function getValue() - { - return $this->objects; - } - - /** - * Returns associative array representing encoded operation. - * - * @return array - */ - public function _encode() - { - return array('__op' => 'Remove', - 'objects' => ParseClient::_encode($this->objects, true)); - } - /** - * Takes a previous operation and returns a merged operation to replace it. - * - * @param FieldOperation $previous Previous operation. - * - * @return FieldOperation Merged operation. - * @throws ParseException - */ - public function _mergeWithPrevious($previous) - { - if (!$previous) { - return $this; + /** + * Gets the objects for this operation. + * + * @return mixed + */ + public function getValue() + { + return $this->objects; } - 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) - ); + + /** + * Returns associative array representing encoded operation. + * + * @return array + */ + public function _encode() + { + return array('__op' => 'Remove', + 'objects' => ParseClient::_encode($this->objects, true)); } - throw new ParseException( - 'Operation is invalid after previous operation.' - ); - } - /** - * Applies current operation, returns resulting value. - * - * @param mixed $oldValue Value prior to this operation. - * @param mixed $obj Value being applied. - * @param string $key Key this operation affects. - * - * @return array - */ - public function _apply($oldValue, $obj, $key) - { - if (empty($oldValue)) { - return array(); + /** + * Takes a previous operation and returns a merged operation to replace it. + * + * @param FieldOperation $previous Previous operation. + * + * @return FieldOperation Merged operation. + * @throws ParseException + */ + public function _mergeWithPrevious($previous) + { + 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) + ); + } + throw new ParseException( + 'Operation is invalid after previous operation.' + ); } - $newValue = array(); - 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; - } - } else { - if ($oldObject !== $newObject) { - $newValue[] = $oldObject; - } + + /** + * Applies current operation, returns resulting value. + * + * @param mixed $oldValue Value prior to this operation. + * @param mixed $obj Value being applied. + * @param string $key Key this operation affects. + * + * @return array + */ + 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 + && !$oldObject->isDirty() + && $oldObject->getObjectId() == $newObject->getObjectId()) { + // found the object, won't add it. + } else { + $newValue[] = $oldObject; + } + } else { + if ($oldObject !== $newObject) { + $newValue[] = $oldObject; + } + } + } } - } + return $newValue; } - return $newValue; - } -} \ No newline at end of file +} diff --git a/src/Parse/Internal/SetOperation.php b/src/Parse/Internal/SetOperation.php index df3b6099..0f31fc55 100755 --- a/src/Parse/Internal/SetOperation.php +++ b/src/Parse/Internal/SetOperation.php @@ -7,86 +7,86 @@ /** * Class SetOperation - Operation to set a value for an object key. * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ class SetOperation implements FieldOperation { - /** - * @var - Value to set for this operation. - */ - private $value; + /** + * @var - Value to set for this operation. + */ + private $value; - /** - * @var - If the value should be forced as object. - */ - private $isAssociativeArray; + /** + * @var - If the value should be forced as object. + */ + private $isAssociativeArray; - /** - * Create a SetOperation with a value. - * - * @param mixed $value Value to set for this operation. - * @param bool $isAssociativeArray If the value should be forced as object. - */ - public function __construct($value, $isAssociativeArray = false) - { - $this->value = $value; - $this->isAssociativeArray = $isAssociativeArray; - } + /** + * Create a SetOperation with a value. + * + * @param mixed $value Value to set for this operation. + * @param bool $isAssociativeArray If the value should be forced as object. + */ + public function __construct($value, $isAssociativeArray = false) + { + $this->value = $value; + $this->isAssociativeArray = $isAssociativeArray; + } - /** - * Get the value for this operation. - * - * @return mixed Value. - */ - public function getValue() - { - return $this->value; - } + /** + * Get the value for this operation. + * + * @return mixed Value. + */ + public function getValue() + { + return $this->value; + } - /** - * Returns an associative array encoding of the current operation. - * - * @return mixed - */ - public function _encode() - { - if ($this->isAssociativeArray) { - $object = new \stdClass(); - foreach ($this->value as $key => $value) { - $object->$key = ParseClient::_encode($value, true); - } - return ParseClient::_encode($object, true); + /** + * Returns an associative array encoding of the current operation. + * + * @return mixed + */ + public function _encode() + { + 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($this->value, true); } - return ParseClient::_encode($this->value, true); - } - /** - * Apply the current operation and return the result. - * - * @param mixed $oldValue Value prior to this operation. - * @param mixed $object Value for this operation. - * @param string $key Key to set this value on. - * - * @return mixed - */ - public function _apply($oldValue, $object, $key) - { - return $this->value; - } + /** + * Apply the current operation and return the result. + * + * @param mixed $oldValue Value prior to this operation. + * @param mixed $object Value for this operation. + * @param string $key Key to set this value on. + * + * @return mixed + */ + public function _apply($oldValue, $object, $key) + { + return $this->value; + } - /** - * Merge this operation with a previous operation and return the - * resulting operation. - * - * @param FieldOperation $previous Previous operation. - * - * @return FieldOperation - */ - public function _mergeWithPrevious($previous) - { - return $this; - } + /** + * Merge this operation with a previous operation and return the + * resulting operation. + * + * @param FieldOperation $previous Previous operation. + * + * @return FieldOperation + */ + public function _mergeWithPrevious($previous) + { + return $this; + } -} \ No newline at end of file +} diff --git a/src/Parse/ParseACL.php b/src/Parse/ParseACL.php index d56fc56b..7f849c90 100644 --- a/src/Parse/ParseACL.php +++ b/src/Parse/ParseACL.php @@ -12,543 +12,543 @@ * 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 + * @package Parse + * @author Mohamed Madbouli */ class ParseACL implements Encodable{ - /* - * @ignore - */ - const PUBLIC_KEY = '*'; - /** - * @var array - - */ - private $permissionsById = array(); - /** - * @var bool - - */ - private $shared = false; - /** - * @var ParseUser - - */ - private static $lastCurrentUser = null; - /** - * @var ParseACL - - */ - private static $defaultACLWithCurrentUser = null; - /** - * @var ParseACL - - */ - private static $defaultACL = null; - /** - * @var bool - - */ - private static $defaultACLUsesCurrentUser = false; - - /** - * Create new ParseACL with read and write access for the given user. - * - * @param ParseUser $user - * - * @return ParseACL - */ - public static function createACLWithUser($user) - { - $acl = new ParseACL(); - $acl->setUserReadAccess($user, true); - $acl->setUserWriteAccess($user, true); - return $acl; - } - - /** - * Create new ParseACL from existing permissions. - * - * @param array $data represents permissions. - * - * @return ParseACL - * @throws \Exception - * @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( - 'Tried to create an ACL with an invalid permission type.'); + /* + * @ignore + */ + const PUBLIC_KEY = '*'; + /** + * @var array - + */ + private $permissionsById = array(); + /** + * @var bool - + */ + private $shared = false; + /** + * @var ParseUser - + */ + private static $lastCurrentUser = null; + /** + * @var ParseACL - + */ + private static $defaultACLWithCurrentUser = null; + /** + * @var ParseACL - + */ + private static $defaultACL = null; + /** + * @var bool - + */ + private static $defaultACLUsesCurrentUser = false; + + /** + * Create new ParseACL with read and write access for the given user. + * + * @param ParseUser $user + * + * @return ParseACL + */ + public static function createACLWithUser($user) + { + $acl = new ParseACL(); + $acl->setUserReadAccess($user, true); + $acl->setUserWriteAccess($user, true); + return $acl; + } + + /** + * Create new ParseACL from existing permissions. + * + * @param array $data represents permissions. + * + * @return ParseACL + * @throws \Exception + * @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( + 'Tried to create an ACL with an invalid permission type.'); + } + if (!is_bool($value)) { + throw new \Exception( + 'Tried to create an ACL with an invalid permission value.'); + } + $acl->setAccess($accessType, $id, $value); + } + } + return $acl; + } + + /** + * Return if ParseACL shared or not. + * + * @return bool + * @ignore + */ + public function _isShared() + { + return $this->shared; + } + + /** + * Set shared for ParseACL + * + * @param bool $shared + * @ignore + */ + public function _setShared($shared) + { + $this->shared = $shared; + } + + /** + * @ignore + */ + public function _encode() + { + if (empty($this->permissionsById)) { + return new \stdClass(); + } + return $this->permissionsById; + } + + /** + * Set access permission with access name, user id and if + * the user has permission for accessing or not. + * + * @param string $accessType Access name. + * @param string $userId User id. + * @param bool $allowed If user allowed to access or not. + * + * @throws ParseException + */ + 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( + "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]); + } + } + } + + /** + * Get if the given userId has a permission for the given access type or not. + * + * @param string $accessType Access name. + * @param string $userId User id. + * + * @return bool + */ + 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]; + } + + /** + * Set whether the given user id is allowed to read this object. + * + * @param string $userId User id. + * @param bool $allowed If user allowed to read or not. + * + * @throws \Exception + */ + public function setReadAccess($userId, $allowed) + { + if (!$userId) { + throw new \Exception("cannot setReadAccess for null userId"); + } + $this->setAccess('read', $userId, $allowed); + } + + /** + * Get whether the given user id is *explicitly* allowed to read this + * object. Even if this returns false, the user may still be able to + * access it if getPublicReadAccess returns true or a role that the + * user belongs to has read access. + * + * @param string $userId User id. + * + * @return bool + * + * @throws \Exception + */ + public function getReadAccess($userId) + { + if (!$userId) { + throw new \Exception("cannot getReadAccess for null userId"); + } + return $this->getAccess('read', $userId); + } + + /** + * Set whether the given user id is allowed to write this object. + * + * @param string $userId User id. + * @param bool $allowed If user allowed to write or not. + * + * @throws \Exception + */ + public function setWriteAccess($userId, $allowed) + { + if (!$userId) { + throw new \Exception("cannot setWriteAccess for null userId"); } - if (!is_bool($value)) { - throw new \Exception( - 'Tried to create an ACL with an invalid permission value.'); + $this->setAccess('write', $userId, $allowed); + } + + /** + * Get whether the given user id is *explicitly* allowed to write this + * object. Even if this returns false, the user may still be able to + * access it if getPublicWriteAccess returns true or a role that the + * user belongs to has write access. + * + * @param string $userId User id. + * + * @return bool + * + * @throws \Exception + */ + public function getWriteAccess($userId) + { + if (!$userId) { + throw new \Exception("cannot getWriteAccess for null userId"); } - $acl->setAccess($accessType, $id, $value); - } + return $this->getAccess('write', $userId); } - return $acl; - } - - /** - * Return if ParseACL shared or not. - * - * @return bool - * @ignore - */ - public function _isShared() - { - return $this->shared; - } - - /** - * Set shared for ParseACL - * - * @param bool $shared - * @ignore - */ - public function _setShared($shared) - { - $this->shared = $shared; - } - - /** - * @ignore - */ - public function _encode() - { - if (empty($this->permissionsById)) { - return new \stdClass(); + + + /** + * Set whether the public is allowed to read this object. + * + * @param bool $allowed + */ + public function setPublicReadAccess($allowed) + { + $this->setReadAccess(self::PUBLIC_KEY, $allowed); } - return $this->permissionsById; - } - - /** - * Set access permission with access name, user id and if - * the user has permission for accessing or not. - * - * @param string $accessType Access name. - * @param string $userId User id. - * @param bool $allowed If user allowed to access or not. - * - * @throws ParseException - */ - private function setAccess($accessType, $userId, $allowed) - { - if ($userId instanceof ParseUser) { - $userId = $userId->getObjectId(); + + /** + * Get whether the public is allowed to read this object. + * + * @return bool + */ + public function getPublicReadAccess() + { + return $this->getReadAccess(self::PUBLIC_KEY); } - if ($userId instanceof ParseRole) { - $userId = "role:" . $userId->getName(); + + /** + * Set whether the public is allowed to write this object. + * + * @param bool $allowed + */ + public function setPublicWriteAccess($allowed) + { + $this->setWriteAccess(self::PUBLIC_KEY, $allowed); } - if (!is_string($userId)) { - throw new ParseException( - "Invalid target for access control." - ); + + /** + * Get whether the public is allowed to write this object. + * + * @return bool + */ + public function getPublicWriteAccess() + { + return $this->getWriteAccess(self::PUBLIC_KEY); } - if (!isset($this->permissionsById[$userId])) { - if (!$allowed) { - return; - } - $this->permissionsById[$userId] = array(); + + /** + * Set whether the given user is allowed to read this object. + * + * @param ParseUser $user + * @param bool $allowed + * + * @throws \Exception + */ + 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 ($allowed) { - $this->permissionsById[$userId][$accessType] = true; - } else { - unset($this->permissionsById[$userId][$accessType]); - if (empty($this->permissionsById[$userId])) { - unset($this->permissionsById[$userId]); - } + + /** + * Get whether the given user is *explicitly* allowed to read this object. + * Even if this returns false, the user may still be able to access it if + * getPublicReadAccess returns true or a role that the user belongs to has + * read access. + * + * @param ParseUser $user + * + * @return bool + * + * @throws \Exception + */ + public function getUserReadAccess($user) + { + if (!$user->getObjectId()) { + throw new \Exception("cannot getReadAccess for a user with null id"); + } + return $this->getReadAccess($user->getObjectId()); } - } - - /** - * Get if the given userId has a permission for the given access type or not. - * - * @param string $accessType Access name. - * @param string $userId User id. - * - * @return bool - */ - private function getAccess($accessType, $userId) - { - if (!isset($this->permissionsById[$userId])) { - return false; + + /** + * Set whether the given user is allowed to write this object. + * + * @param ParseUser $user + * @param bool $allowed + * + * @throws \Exception + */ + 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 (!isset($this->permissionsById[$userId][$accessType])) { - return false; + + /** + * Get whether the given user is *explicitly* allowed to write this object. + * Even if this returns false, the user may still be able to access it if + * getPublicWriteAccess returns true or a role that the user belongs to has + * write access. + * + * @param ParseUser $user + * + * @return bool + * + * @throws \Exception + */ + public function getUserWriteAccess($user) + { + if (!$user->getObjectId()) { + throw new \Exception("cannot getWriteAccess for a user with null id"); + } + return $this->getWriteAccess($user->getObjectId()); } - return $this->permissionsById[$userId][$accessType]; - } - - /** - * Set whether the given user id is allowed to read this object. - * - * @param string $userId User id. - * @param bool $allowed If user allowed to read or not. - * - * @throws \Exception - */ - public function setReadAccess($userId, $allowed) - { - if (!$userId) { - throw new \Exception("cannot setReadAccess for null userId"); + + /** + * Get whether users belonging to the role with the given roleName are + * allowed to read this object. Even if this returns false, the role may + * still be able to read it if a parent role has read access. + * + * @param string $roleName The name of the role. + * + * @return bool + */ + public function getRoleReadAccessWithName($roleName) + { + return $this->getReadAccess('role:' . $roleName); } - $this->setAccess('read', $userId, $allowed); - } - - /** - * Get whether the given user id is *explicitly* allowed to read this - * object. Even if this returns false, the user may still be able to - * access it if getPublicReadAccess returns true or a role that the - * user belongs to has read access. - * - * @param string $userId User id. - * - * @return bool - * - * @throws \Exception - */ - public function getReadAccess($userId) - { - if (!$userId) { - throw new \Exception("cannot getReadAccess for null userId"); + + /** + * Set whether users belonging to the role with the given 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); } - return $this->getAccess('read', $userId); - } - - /** - * Set whether the given user id is allowed to write this object. - * - * @param string $userId User id. - * @param bool $allowed If user allowed to write or not. - * - * @throws \Exception - */ - public function setWriteAccess($userId, $allowed) - { - if (!$userId) { - throw new \Exception("cannot setWriteAccess for null userId"); + + /** + * Get whether users belonging to the role with the given roleName are + * allowed to write this object. Even if this returns false, the role may + * still be able to write it if a parent role has write access. + * + * @param string $roleName The name of the role. + * + * @return bool + */ + public function getRoleWriteAccessWithName($roleName) + { + return $this->getWriteAccess('role:' . $roleName); } - $this->setAccess('write', $userId, $allowed); - } - - /** - * Get whether the given user id is *explicitly* allowed to write this - * object. Even if this returns false, the user may still be able to - * access it if getPublicWriteAccess returns true or a role that the - * user belongs to has write access. - * - * @param string $userId User id. - * - * @return bool - * - * @throws \Exception - */ - public function getWriteAccess($userId) - { - if (!$userId) { - throw new \Exception("cannot getWriteAccess for null userId"); + + /** + * Set whether users belonging to the role with the given roleName + * are allowed to write this object. + * + * @param string $roleName The name of the role. + * @param bool $allowed Whether the given role can write this object. + */ + public function setRoleWriteAccessWithName($roleName, $allowed) + { + $this->setWriteAccess('role:' . $roleName, $allowed); } - return $this->getAccess('write', $userId); - } - - - /** - * Set whether the public is allowed to read this object. - * - * @param bool $allowed - */ - public function setPublicReadAccess($allowed) - { - $this->setReadAccess(self::PUBLIC_KEY, $allowed); - } - - /** - * Get whether the public is allowed to read this object. - * - * @return bool - */ - public function getPublicReadAccess() - { - return $this->getReadAccess(self::PUBLIC_KEY); - } - - /** - * Set whether the public is allowed to write this object. - * - * @param bool $allowed - */ - public function setPublicWriteAccess($allowed) - { - $this->setWriteAccess(self::PUBLIC_KEY, $allowed); - } - - /** - * Get whether the public is allowed to write this object. - * - * @return bool - */ - public function getPublicWriteAccess() - { - return $this->getWriteAccess(self::PUBLIC_KEY); - } - - /** - * Set whether the given user is allowed to read this object. - * - * @param ParseUser $user - * @param bool $allowed - * - * @throws \Exception - */ - public function setUserReadAccess($user, $allowed) - { - if (!$user->getObjectId()) { - throw new \Exception("cannot setReadAccess for a user with null id"); + + /** + * Check whether the role is valid or not. + * + * @param ParseRole $role + * + * @throws \Exception + */ + private static function validateRoleState($role) + { + if (!$role->getObjectId()) { + throw new \Exception( + "Roles must be saved to the server before they can be used in an ACL."); + } } - $this->setReadAccess($user->getObjectId(), $allowed); - } - - /** - * Get whether the given user is *explicitly* allowed to read this object. - * Even if this returns false, the user may still be able to access it if - * getPublicReadAccess returns true or a role that the user belongs to has - * read access. - * - * @param ParseUser $user - * - * @return bool - * - * @throws \Exception - */ - public function getUserReadAccess($user) - { - if (!$user->getObjectId()) { - throw new \Exception("cannot getReadAccess for a user with null id"); + + /** + * Get whether users belonging to the given role are allowed to read this + * object. Even if this returns false, the role may still be able to read + * it if a parent role has read access. The role must already be saved on + * the server and its data must have been fetched in order to use this method. + * + * @param ParseRole $role The role to check for access. + * + * @return bool + */ + public function getRoleReadAccess($role) + { + $this->validateRoleState($role); + return $this->getRoleReadAccessWithName($role->getName()); } - return $this->getReadAccess($user->getObjectId()); - } - - /** - * Set whether the given user is allowed to write this object. - * - * @param ParseUser $user - * @param bool $allowed - * - * @throws \Exception - */ - public function setUserWriteAccess($user, $allowed) - { - if (!$user->getObjectId()) { - throw new \Exception("cannot setWriteAccess for a user with null id"); + + /** + * Set whether users belonging to the given role are allowed to read this + * object. The role must already be saved on the server and its data must + * have been fetched in order to use this method. + * + * @param ParseRole $role The role to assign access. + * @param bool $allowed Whether the given role can read this object. + */ + public function setRoleReadAccess($role, $allowed) + { + $this->validateRoleState($role); + $this->setRoleReadAccessWithName($role->getName(), $allowed); } - $this->setWriteAccess($user->getObjectId(), $allowed); - } - - /** - * Get whether the given user is *explicitly* allowed to write this object. - * Even if this returns false, the user may still be able to access it if - * getPublicWriteAccess returns true or a role that the user belongs to has - * write access. - * - * @param ParseUser $user - * - * @return bool - * - * @throws \Exception - */ - public function getUserWriteAccess($user) - { - if (!$user->getObjectId()) { - throw new \Exception("cannot getWriteAccess for a user with null id"); + + /** + * Get whether users belonging to the given role are allowed to write this + * object. Even if this returns false, the role may still be able to write + * it if a parent role has write access. The role must already be saved on + * the server and its data must have been fetched in order to use this method. + * + * @param ParseRole $role The role to check for access. + * + * @return bool + */ + public function getRoleWriteAccess($role) + { + $this->validateRoleState($role); + return $this->getRoleWriteAccessWithName($role->getName()); } - return $this->getWriteAccess($user->getObjectId()); - } - - /** - * Get whether users belonging to the role with the given roleName are - * allowed to read this object. Even if this returns false, the role may - * still be able to read it if a parent role has read access. - * - * @param string $roleName The name of the role. - * - * @return bool - */ - public function getRoleReadAccessWithName($roleName) - { - return $this->getReadAccess('role:' . $roleName); - } - - /** - * Set whether users belonging to the role with the given 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); - } - - /** - * Get whether users belonging to the role with the given roleName are - * allowed to write this object. Even if this returns false, the role may - * still be able to write it if a parent role has write access. - * - * @param string $roleName The name of the role. - * - * @return bool - */ - public function getRoleWriteAccessWithName($roleName) - { - return $this->getWriteAccess('role:' . $roleName); - } - - /** - * Set whether users belonging to the role with the given roleName - * are allowed to write this object. - * - * @param string $roleName The name of the role. - * @param bool $allowed Whether the given role can write this object. - */ - public function setRoleWriteAccessWithName($roleName, $allowed) - { - $this->setWriteAccess('role:' . $roleName, $allowed); - } - - /** - * Check whether the role is valid or not. - * - * @param ParseRole $role - * - * @throws \Exception - */ - private static function validateRoleState($role) - { - if (!$role->getObjectId()) { - throw new \Exception( - "Roles must be saved to the server before they can be used in an ACL."); + + /** + * Set whether users belonging to the given role are allowed to write this + * object. The role must already be saved on the server and its data must + * have been fetched in order to use this method. + * + * @param ParseRole $role The role to assign access. + * @param bool $allowed Whether the given role can read this object. + */ + public function setRoleWriteAccess($role, $allowed) + { + $this->validateRoleState($role); + $this->setRoleWriteAccessWithName($role->getName(), $allowed); } - } - - /** - * Get whether users belonging to the given role are allowed to read this - * object. Even if this returns false, the role may still be able to read - * it if a parent role has read access. The role must already be saved on - * the server and its data must have been fetched in order to use this method. - * - * @param ParseRole $role The role to check for access. - * - * @return bool - */ - public function getRoleReadAccess($role) - { - $this->validateRoleState($role); - return $this->getRoleReadAccessWithName($role->getName()); - } - - /** - * Set whether users belonging to the given role are allowed to read this - * object. The role must already be saved on the server and its data must - * have been fetched in order to use this method. - * - * @param ParseRole $role The role to assign access. - * @param bool $allowed Whether the given role can read this object. - */ - public function setRoleReadAccess($role, $allowed) - { - $this->validateRoleState($role); - $this->setRoleReadAccessWithName($role->getName(), $allowed); - } - - /** - * Get whether users belonging to the given role are allowed to write this - * object. Even if this returns false, the role may still be able to write - * it if a parent role has write access. The role must already be saved on - * the server and its data must have been fetched in order to use this method. - * - * @param ParseRole $role The role to check for access. - * - * @return bool - */ - public function getRoleWriteAccess($role) - { - $this->validateRoleState($role); - return $this->getRoleWriteAccessWithName($role->getName()); - } - - /** - * Set whether users belonging to the given role are allowed to write this - * object. The role must already be saved on the server and its data must - * have been fetched in order to use this method. - * - * @param ParseRole $role The role to assign access. - * @param bool $allowed Whether the given role can read this object. - */ - public function setRoleWriteAccess($role, $allowed) - { - $this->validateRoleState($role); - $this->setRoleWriteAccessWithName($role->getName(), $allowed); - } - - /** - * Sets a default ACL that will be applied to all ParseObjects when they - * are created. - * - * @param ParseACL $acl The ACL to use as a template for all ParseObjects - * created after setDefaultACL has been called. This - * value will be copied and used as a template for the - * creation of new ACLs, so changes to the instance - * after setDefaultACL() has been called will not be - * reflected in new ParseObjects. - * @param bool $withAccessForCurrentUser If true, the ParseACL that is applied to - * newly-created ParseObjects will provide read - * and write access to the ParseUser#getCurrentUser() - * at the time of creation. If false, the provided - * ACL will be used without modification. If acl is - * null, this value is ignored. - */ - 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; + + /** + * Sets a default ACL that will be applied to all ParseObjects when they + * are created. + * + * @param ParseACL $acl The ACL to use as a template for all ParseObjects + * created after setDefaultACL has been called. This + * value will be copied and used as a template for the + * creation of new ACLs, so changes to the instance + * after setDefaultACL() has been called will not be + * reflected in new ParseObjects. + * @param bool $withAccessForCurrentUser If true, the ParseACL that is applied to + * newly-created ParseObjects will provide read + * and write access to the ParseUser#getCurrentUser() + * at the time of creation. If false, the provided + * ACL will be used without modification. If acl is + * null, this value is ignored. + */ + 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; + } } - } - - /** - * Get the defaultACL. - * - * @return ParseACL - * @ignore - */ - public static function _getDefaultACL() - { - if (self::$defaultACLUsesCurrentUser && self::$defaultACL) { - $last = self::$lastCurrentUser ? clone self::$lastCurrentUser : null; - if (!ParseUser::getCurrentUser()) { + + /** + * Get the defaultACL. + * + * @return ParseACL + * @ignore + */ + public static function _getDefaultACL() + { + 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; + } 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; } - return self::$defaultACL; - } } diff --git a/src/Parse/ParseAggregateException.php b/src/Parse/ParseAggregateException.php index 58410118..6e3f3303 100644 --- a/src/Parse/ParseAggregateException.php +++ b/src/Parse/ParseAggregateException.php @@ -5,35 +5,35 @@ /** * ParseAggregateException - Multiple error condition * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ class ParseAggregateException extends ParseException { - private $errors; + private $errors; - /** - * 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) - { - parent::__construct($message, 600, $previous); - $this->errors = $errors; - } + /** + * 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) + { + parent::__construct($message, 600, $previous); + $this->errors = $errors; + } - /** - * Return the aggregated errors that were thrown. - * - * @return array - */ - public function getErrors() - { - return $this->errors; - } + /** + * Return the aggregated errors that were thrown. + * + * @return array + */ + public function getErrors() + { + return $this->errors; + } -} \ No newline at end of file +} diff --git a/src/Parse/ParseAnalytics.php b/src/Parse/ParseAnalytics.php index 8f40b22a..de936d7d 100644 --- a/src/Parse/ParseAnalytics.php +++ b/src/Parse/ParseAnalytics.php @@ -7,70 +7,70 @@ /** * ParseAnalytics - Handles sending app-open and custom analytics events * - * @package Parse - * @author Fosco Marotto + * @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 - * event name. - * - * Dimensions will allow segmentation of the occurrences of this custom - * event. Keys and values should be strings, and will throw - * otherwise. - * - * To track a user signup along with additional metadata, consider the - * following: - *
-   * $dimensions = array(
-   *  'gender' => 'm',
-   *  'source' => 'web',
-   *  'dayType' => 'weekend'
-   * );
-   * ParseAnalytics::track('signup', $dimensions);
-   * 
- * - * There is a default limit of 4 dimensions per event tracked. - * - * @param string $name The name of the custom event - * @param array $dimensions The dictionary of segment information - * - * @throws \Exception - * @return mixed - */ - public static function track($name, $dimensions = array()) - { - $name = trim($name); - if (strlen($name) === 0) { - throw new Exception('A name for the custom event must be provided.'); + /** + * Tracks the occurrence of a custom event with additional dimensions. + * Parse will store a data point at the time of invocation with the given + * event name. + * + * Dimensions will allow segmentation of the occurrences of this custom + * event. Keys and values should be strings, and will throw + * otherwise. + * + * To track a user signup along with additional metadata, consider the + * following: + *
+     * $dimensions = array(
+     *    'gender' => 'm',
+     *    'source' => 'web',
+     *    'dayType' => 'weekend'
+     * );
+     * ParseAnalytics::track('signup', $dimensions);
+     * 
+ * + * There is a default limit of 4 dimensions per event tracked. + * + * @param string $name The name of the custom event + * @param array $dimensions The dictionary of segment information + * + * @throws \Exception + * @return mixed + */ + public static function track($name, $dimensions = array()) + { + $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( + 'POST', + '/1/events/' . $name, + null, + static::_toSaveJSON($dimensions) + ); } - foreach ($dimensions as $key => $value) { - if (!is_string($key) || !is_string($value)) { - throw new Exception('Dimensions expected string keys and values.'); - } - } - return ParseClient::_request( - 'POST', - '/1/events/' . $name, - null, - static::_toSaveJSON($dimensions) - ); - } - /** - * @ignore - */ - public static function _toSaveJSON($data) - { - return json_encode( - array( - 'dimensions' => $data - ), - JSON_FORCE_OBJECT - ); - } + /** + * @ignore + */ + public static function _toSaveJSON($data) + { + return json_encode( + array( + '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..2463a80b 100644 --- a/src/Parse/ParseBytes.php +++ b/src/Parse/ParseBytes.php @@ -5,71 +5,71 @@ /** * ParseBytes - Representation of a Byte array for storage on a Parse Object. * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ class ParseBytes implements Internal\Encodable { - /** - * @var - byte array - */ - private $byteArray; + /** + * @var - byte array + */ + private $byteArray; - /** - * Create a ParseBytes object with a given byte array. - * - * @param array $byteArray - * - * @return ParseBytes - */ - public static function createFromByteArray(array $byteArray) - { - $bytes = new ParseBytes(); - $bytes->setByteArray($byteArray); - return $bytes; - } + /** + * Create a ParseBytes object with a given byte array. + * + * @param array $byteArray + * + * @return ParseBytes + */ + public static function createFromByteArray(array $byteArray) + { + $bytes = new ParseBytes(); + $bytes->setByteArray($byteArray); + return $bytes; + } - /** - * Create a ParseBytes object with a given base 64 encoded data string - * - * @param string $base64Data - * - * @return ParseBytes - */ - public static function createFromBase64Data($base64Data) - { - $bytes = new ParseBytes(); - $bytes->setBase64Data($base64Data); - return $bytes; - } + /** + * Create a ParseBytes object with a given base 64 encoded data string + * + * @param string $base64Data + * + * @return ParseBytes + */ + public static function createFromBase64Data($base64Data) + { + $bytes = new ParseBytes(); + $bytes->setBase64Data($base64Data); + return $bytes; + } - private function setBase64Data($base64Data) - { - $byteArray = unpack('C*', base64_decode($base64Data)); - $this->setByteArray($byteArray); - } + private function setBase64Data($base64Data) + { + $byteArray = unpack('C*', base64_decode($base64Data)); + $this->setByteArray($byteArray); + } - private function setByteArray(array $byteArray) - { - $this->byteArray = $byteArray; - } + private function setByteArray(array $byteArray) + { + $this->byteArray = $byteArray; + } - /** - * Encode to associative array representation - * - * @return array - * @ignore - */ - public function _encode() - { - $data = ""; - foreach ($this->byteArray as $byte) { - $data .= chr($byte); + /** + * Encode to associative array representation + * + * @return array + * @ignore + */ + public function _encode() + { + $data = ""; + foreach ($this->byteArray as $byte) { + $data .= chr($byte); + } + return array( + '__type' => 'Bytes', + 'base64' => base64_encode($data) + ); } - return array( - '__type' => 'Bytes', - 'base64' => base64_encode($data) - ); - } } diff --git a/src/Parse/ParseClient.php b/src/Parse/ParseClient.php index d85742a1..5d692f8f 100755 --- a/src/Parse/ParseClient.php +++ b/src/Parse/ParseClient.php @@ -7,403 +7,403 @@ /** * ParseClient - Main class for Parse initialization and communication * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ final class ParseClient { - /** - * Constant for the API Server Host Address. - * @ignore - */ - const HOST_NAME = 'https://api.parse.com'; - - /** - * @var - String for applicationId. - */ - private static $applicationId; - - /** - * @var - String for REST API Key. - */ - private static $restKey; - - /** - * @var - String for Master Key. - */ - private static $masterKey; - - /** - * @var - Boolean for Enable/Disable curl exceptions. - */ - private static $enableCurlExceptions; - - /** - * @var ParseStorageInterface Object for managing persistence - */ - private static $storage; - - /** - * @var - Boolean for enabling revocable sessions. - */ - private static $forceRevocableSession = false; - - /** - * Constant for version string to include with requests. - * @ignore - */ - const VERSION_STRING = 'php1.1.0'; - - /** - * Parse\Client::initialize, must be called before using Parse features. - * - * @param string $app_id Parse Application ID - * @param string $rest_key Parse REST API Key - * @param string $master_key Parse Master Key - * @param boolean $enableCurlExceptions Enable or disable Parse curl exceptions - * - * @return null - */ - 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()); - } - } - } - - /** - * ParseClient::_encode, internal method for encoding object values. - * - * @param mixed $value Value to encode - * @param bool $allowParseObjects Allow nested objects - * - * @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 \stdClass) { - return $value; - } + /** + * Constant for the API Server Host Address. + * @ignore + */ + const HOST_NAME = 'https://api.parse.com'; - if ($value instanceof ParseObject) { - if (!$allowParseObjects) { - throw new \Exception('ParseObjects not allowed here.'); - } - return $value->_toPointer(); - } + /** + * @var - String for applicationId. + */ + private static $applicationId; - if ($value instanceof Encodable) { - return $value->_encode(); - } + /** + * @var - String for REST API Key. + */ + private static $restKey; - if (is_array($value)) { - return self::_encodeArray($value, $allowParseObjects); - } + /** + * @var - String for Master Key. + */ + private static $masterKey; - if (!is_scalar($value) && $value !== null) { - throw new \Exception('Invalid type encountered.'); - } - return $value; - } - - /** - * ParseClient::_decode, internal method for decoding server responses. - * - * @param mixed $data The value to decode - * - * @return mixed - * @ignore - */ - public static function _decode($data) - { - // 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)); - } - } + /** + * @var - Boolean for Enable/Disable curl exceptions. + */ + private static $enableCurlExceptions; - if (!$data && !is_array($data)) { - return null; - } + /** + * @var ParseStorageInterface Object for managing persistence + */ + private static $storage; - if (is_array($data)) { - $typeString = (isset($data['__type']) ? $data['__type'] : null); + /** + * @var - Boolean for enabling revocable sessions. + */ + private static $forceRevocableSession = false; - if ($typeString === 'Date') { - return new \DateTime($data['iso']); - } + /** + * Constant for version string to include with requests. + * @ignore + */ + const VERSION_STRING = 'php1.1.0'; - if ($typeString === 'Bytes') { - return base64_decode($data['base64']); - } + /** + * Parse\Client::initialize, must be called before using Parse features. + * + * @param string $app_id Parse Application ID + * @param string $rest_key Parse REST API Key + * @param string $master_key Parse Master Key + * @param boolean $enableCurlExceptions Enable or disable Parse curl exceptions + * + * @return null + */ + 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()); + } + } + } - if ($typeString === 'Pointer') { - return ParseObject::create($data['className'], $data['objectId']); - } + /** + * ParseClient::_encode, internal method for encoding object values. + * + * @param mixed $value Value to encode + * @param bool $allowParseObjects Allow nested objects + * + * @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 \stdClass) { + return $value; + } + + if ($value instanceof ParseObject) { + if (!$allowParseObjects) { + throw new \Exception('ParseObjects not allowed here.'); + } + return $value->_toPointer(); + } + + if ($value instanceof Encodable) { + return $value->_encode(); + } + + if (is_array($value)) { + return self::_encodeArray($value, $allowParseObjects); + } + + if (!is_scalar($value) && $value !== null) { + throw new \Exception('Invalid type encountered.'); + } + return $value; + } - if ($typeString === 'File') { - return ParseFile::_createFromServer($data['name'], $data['url']); - } + /** + * ParseClient::_decode, internal method for decoding server responses. + * + * @param mixed $data The value to decode + * + * @return mixed + * @ignore + */ + public static function _decode($data) + { + // 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)); + } + } + + if (!$data && !is_array($data)) { + return null; + } + + if (is_array($data)) { + $typeString = (isset($data['__type']) ? $data['__type'] : null); + + if ($typeString === 'Date') { + return new \DateTime($data['iso']); + } + + if ($typeString === 'Bytes') { + return base64_decode($data['base64']); + } + + if ($typeString === 'Pointer') { + return ParseObject::create($data['className'], $data['objectId']); + } + + if ($typeString === 'File') { + return ParseFile::_createFromServer($data['name'], $data['url']); + } + + 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 === 'Relation') { + return $data; + } + + $newDict = array(); + foreach ($data as $key => $value) { + $newDict[$key] = static::_decode($value); + } + return $newDict; + + } - if ($typeString === 'GeoPoint') { - return new ParseGeoPoint($data['latitude'], $data['longitude']); - } + return $data; + } - if ($typeString === 'Object') { - $output = ParseObject::create($data['className']); - $output->_mergeAfterFetch($data); + /** + * ParseClient::_encodeArray, internal method for encoding arrays. + * + * @param array $value Array to encode. + * @param bool $allowParseObjects Allow nested objects. + * + * @return array Encoded results. + * @ignore + */ + public static function _encodeArray($value, $allowParseObjects) + { + $output = array(); + foreach ($value as $key => $item) { + $output[$key] = self::_encode($item, $allowParseObjects); + } return $output; - } - - if ($typeString === 'Relation') { - return $data; - } + } - $newDict = array(); - foreach ($data as $key => $value) { - $newDict[$key] = static::_decode($value); - } - return $newDict; + /** + * Parse\Client::_request, internal method for communicating with Parse. + * + * @param string $method HTTP Method for this request. + * @param string $relativeUrl REST API Path. + * @param null $sessionToken Session Token. + * @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 + * @ignore + */ + public static function _request($method, $relativeUrl, $sessionToken = null, + $data = null, $useMasterKey = false) + { + 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; + } + } + 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'], + isset($decoded['code']) ? $decoded['code'] : 0 + ); + } + return $decoded; } - return $data; - } - - /** - * ParseClient::_encodeArray, internal method for encoding arrays. - * - * @param array $value Array to encode. - * @param bool $allowParseObjects Allow nested objects. - * - * @return array Encoded results. - * @ignore - */ - public static function _encodeArray($value, $allowParseObjects) - { - $output = array(); - foreach ($value as $key => $item) { - $output[$key] = self::_encode($item, $allowParseObjects); - } - return $output; - } - - /** - * Parse\Client::_request, internal method for communicating with Parse. - * - * @param string $method HTTP Method for this request. - * @param string $relativeUrl REST API Path. - * @param null $sessionToken Session Token. - * @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 - * @ignore - */ - public static function _request($method, $relativeUrl, $sessionToken = null, - $data = null, $useMasterKey = false) - { - if ($data === '[]') { - $data = '{}'; + /** + * ParseClient::setStorage, will update the storage object used for + * persistence. + * + * @param ParseStorageInterface $storageObject + * + * @return null + */ + public static function setStorage(ParseStorageInterface $storageObject) + { + self::$storage = $storageObject; } - 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; - } - } - curl_close($rest); - if (strpos($contentType, 'text/html') !== false) { - throw new ParseException('Bad Request', -1); + /** + * ParseClient::getStorage, will return the storage object used for + * persistence. + * + * @return ParseStorageInterface + */ + public static function getStorage() + { + return self::$storage; } - $decoded = json_decode($response, true); - if (isset($decoded['error'])) { - throw new ParseException($decoded['error'], - isset($decoded['code']) ? $decoded['code'] : 0 - ); + /** + * ParseClient::_unsetStorage, will null the storage object. + * + * Without some ability to clear the storage objects, all test cases would + * use the first assigned storage object. + * + * @return null + * @ignore + */ + public static function _unsetStorage() + { + self::$storage = null; } - return $decoded; - - } - - /** - * ParseClient::setStorage, will update the storage object used for - * persistence. - * - * @param ParseStorageInterface $storageObject - * - * @return null - */ - public static function setStorage(ParseStorageInterface $storageObject) - { - self::$storage = $storageObject; - } - - /** - * ParseClient::getStorage, will return the storage object used for - * persistence. - * - * @return ParseStorageInterface - */ - public static function getStorage() - { - return self::$storage; - } - - /** - * ParseClient::_unsetStorage, will null the storage object. - * - * Without some ability to clear the storage objects, all test cases would - * use the first assigned storage object. - * - * @return null - * @ignore - */ - public static function _unsetStorage() - { - self::$storage = null; - } - - private static function assertParseInitialized() - { - if (self::$applicationId === null) { - throw new \Exception( - 'You must call Parse::initialize() before making any requests.' - ); + + private static function assertParseInitialized() + { + if (self::$applicationId === null) { + throw new \Exception( + 'You must call Parse::initialize() before making any requests.' + ); + } } - } - - /** - * @param $sessionToken - * @param $useMasterKey - * - * @return array - * @ignore - */ - 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; + + /** + * @param $sessionToken + * @param $useMasterKey + * + * @return array + * @ignore + */ + 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'; + } + /** + * 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; } - if ($useMasterKey) { - $headers[] = 'X-Parse-Master-Key: ' . self::$masterKey; - } else { - $headers[] = 'X-Parse-REST-API-Key: ' . self::$restKey; + + /** + * Get a date value in the format stored on Parse. + * + * All the SDKs do some slightly different date handling. + * PHP provides 6 digits for the microseconds (u) so we have to chop 3 off. + * + * @param \DateTime $value DateTime value to format. + * + * @return string + */ + 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; } - if (self::$forceRevocableSession) { - $headers[] = 'X-Parse-Revocable-Session: 1'; + + /** + * Get a date value in the format to use in Local Push Scheduling on Parse. + * + * All the SDKs do some slightly different date handling. + * Format from Parse doc: an ISO 8601 date without a time zone, i.e. 2014-10-16T12:00:00 . + * + * @param \DateTime $value DateTime value to format. + * + * @return string + */ + public static function getLocalPushDateFormat($value) + { + $dateFormatString = 'Y-m-d\TH:i:s'; + $date = date_format($value, $dateFormatString); + return $date; } + /** - * 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/ + * Allows an existing application to start using revocable sessions, without forcing + * all requests for the app to use them. After calling this method, login & signup requests + * will be returned a unique and revocable session token. + * + * @return null */ - $headers[] = 'Expect: '; - return $headers; - } - - /** - * Get a date value in the format stored on Parse. - * - * All the SDKs do some slightly different date handling. - * PHP provides 6 digits for the microseconds (u) so we have to chop 3 off. - * - * @param \DateTime $value DateTime value to format. - * - * @return string - */ - 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; - } - - /** - * Get a date value in the format to use in Local Push Scheduling on Parse. - * - * All the SDKs do some slightly different date handling. - * Format from Parse doc: an ISO 8601 date without a time zone, i.e. 2014-10-16T12:00:00 . - * - * @param \DateTime $value DateTime value to format. - * - * @return string - */ - public static function getLocalPushDateFormat($value) - { - $dateFormatString = 'Y-m-d\TH:i:s'; - $date = date_format($value, $dateFormatString); - return $date; - } - - /** - * Allows an existing application to start using revocable sessions, without forcing - * all requests for the app to use them. After calling this method, login & signup requests - * will be returned a unique and revocable session token. - * - * @return null - */ - public static function enableRevocableSessions() - { - self::$forceRevocableSession = true; - } + public static function enableRevocableSessions() + { + self::$forceRevocableSession = true; + } } diff --git a/src/Parse/ParseCloud.php b/src/Parse/ParseCloud.php index 7891191b..1bed03ce 100644 --- a/src/Parse/ParseCloud.php +++ b/src/Parse/ParseCloud.php @@ -5,35 +5,35 @@ /** * ParseCloud - Facilitates calling Parse Cloud functions * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ class ParseCloud { - /** - * Makes a call to a Cloud function - * - * @param string $name Cloud function name - * @param array $data Parameters to pass - * @param boolean $useMasterKey Whether to use the Master Key - * - * @return mixed - */ - public static function run($name, $data = array(), $useMasterKey = false) - { - $sessionToken = null; - if (ParseUser::getCurrentUser()) { - $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); + /** + * Makes a call to a Cloud function + * + * @param string $name Cloud function name + * @param array $data Parameters to pass + * @param boolean $useMasterKey Whether to use the Master Key + * + * @return mixed + */ + public static function run($name, $data = array(), $useMasterKey = false) + { + $sessionToken = null; + if (ParseUser::getCurrentUser()) { + $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); + } + $response = ParseClient::_request( + 'POST', + '/1/functions/' . $name, + $sessionToken, + json_encode(ParseClient::_encode($data, null, false)), + $useMasterKey + ); + return ParseClient::_decode($response['result']); } - $response = ParseClient::_request( - 'POST', - '/1/functions/' . $name, - $sessionToken, - json_encode(ParseClient::_encode($data, null, false)), - $useMasterKey - ); - return ParseClient::_decode($response['result']); - } -} \ No newline at end of file +} diff --git a/src/Parse/ParseConfig.php b/src/Parse/ParseConfig.php index 674d3461..ce81908d 100644 --- a/src/Parse/ParseConfig.php +++ b/src/Parse/ParseConfig.php @@ -5,37 +5,37 @@ /** * ParseConfig - For accessing Parse Config settings * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ class ParseConfig { - private $currentConfig; + private $currentConfig; - /** - * Creates - */ - public function __construct() { - $result = ParseClient::_request("GET", "/1/config"); - $this->setConfig($result['params']); - } + /** + * Creates + */ + 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]; + public function get($key) { + if (isset($this->currentConfig[$key])) { + return $this->currentConfig[$key]; + } + return null; } - return null; - } - public function escape($key) { - if (isset($this->currentConfig[$key])) { - return htmlentities($this->currentConfig[$key]); + public function escape($key) { + if (isset($this->currentConfig[$key])) { + return htmlentities($this->currentConfig[$key]); + } + return null; } - return null; - } - protected function setConfig($config) { - $this->currentConfig = $config; - } + protected function setConfig($config) { + $this->currentConfig = $config; + } -} \ No newline at end of file +} diff --git a/src/Parse/ParseException.php b/src/Parse/ParseException.php index b10499a6..7b307c13 100644 --- a/src/Parse/ParseException.php +++ b/src/Parse/ParseException.php @@ -5,23 +5,23 @@ /** * ParseException - Wrapper for \Exception class * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ class ParseException extends \Exception { - /** - * Constructs a Parse\Exception - * - * @param string $message Message for the Exception. - * @param int $code Error code. - * @param \Exception $previous Previous Exception. - */ - public function __construct($message, $code = 0, - \Exception $previous = null) - { - parent::__construct($message, $code, $previous); - } + /** + * Constructs a Parse\Exception + * + * @param string $message Message for the Exception. + * @param int $code Error code. + * @param \Exception $previous Previous Exception. + */ + public function __construct($message, $code = 0, + \Exception $previous = null) + { + 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..a75c4f22 100755 --- a/src/Parse/ParseFile.php +++ b/src/Parse/ParseFile.php @@ -5,441 +5,441 @@ /** * ParseFile - Representation of a Parse File object. * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ class ParseFile implements \Parse\Internal\Encodable { - /** - * @var - Filename - */ - private $name; - /** - * @var - URL of File data stored on Parse. - */ - private $url; - /** - * @var - Data - */ - private $data; - /** - * @var - Mime type - */ - private $mimeType; + /** + * @var - Filename + */ + private $name; + /** + * @var - URL of File data stored on Parse. + */ + private $url; + /** + * @var - Data + */ + private $data; + /** + * @var - Mime type + */ + private $mimeType; - /** - * Return the data for the file, downloading it if not already present. - * - * @return mixed - * - * @throws ParseException - */ - public function getData() - { - if ($this->data) { - return $this->data; + /** + * Return the data for the file, downloading it if not already present. + * + * @return mixed + * + * @throws ParseException + */ + public function getData() + { + 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; - } - - /** - * Return the URL for the file, if saved. - * - * @return string|null - */ - public function getURL() - { - return $this->url; - } - - /** - * Return the name for the file - * Upon saving to Parse, the name will change to a unique identifier. - * - * @return string - */ - public function getName() - { - return $this->name; - } - /** - * 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."); + /** + * Return the URL for the file, if saved. + * + * @return string|null + */ + public function getURL() + { + return $this->url; } - $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)); + /** + * Return the name for the file + * Upon saving to Parse, the name will change to a unique identifier. + * + * @return string + */ + public function getName() + { + return $this->name; } - curl_close($rest); - } - /** - * Return the mimeType for the file, if set. - * - * @return string|null - */ - public function getMimeType() - { - return $this->mimeType; - } + /** + * 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."); + } - /** - * Create a Parse File from data - * 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 - * @param string $mimeType Optional, The mime-type to use when saving the file - * - * @return ParseFile - */ - public static function createFromData($contents, $name, $mimeType = null) - { - $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"); - * - * @param string $path Path to local file - * @param string $name Filename to use on Parse, can be used to detect mimeType - * @param string $mimeType Optional, The mime-type to use when saving the file - * - * @return ParseFile - */ - public static function createFromFile($path, $name, $mimeType = null) - { - $contents = file_get_contents($path, "rb"); - return static::createFromData($contents, $name, $mimeType); - } - - /** - * Internal method used when constructing a Parse File from Parse. - * - * @param $name - * @param $url - * - * @return ParseFile - * @ignore - */ - public static function _createFromServer($name, $url) - { - $file = new ParseFile(); - $file->name = $name; - $file->url = $url; - return $file; - } + $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); + } - /** - * Encode to associative array representation. - * - * @return string - * @ignore - */ - public function _encode() - { - return array( - '__type' => 'File', - 'url' => $this->url, - 'name' => $this->name - ); - } + /** + * Return the mimeType for the file, if set. + * + * @return string|null + */ + public function getMimeType() + { + return $this->mimeType; + } - /** - * Uploads the file contents to Parse, if not saved. - * - * @return bool - */ - public function save() - { - if (!$this->url) { - $response = $this->upload(); - $this->url = $response['url']; - $this->name = $response['name']; + /** + * Create a Parse File from data + * 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 + * @param string $mimeType Optional, The mime-type to use when saving the file + * + * @return ParseFile + */ + public static function createFromData($contents, $name, $mimeType = null) + { + $file = new ParseFile(); + $file->name = $name; + $file->mimeType = $mimeType; + $file->data = $contents; + return $file; } - return true; - } - private function upload() - { - $fileParts = explode('.', $this->getName()); - $extension = array_pop($fileParts); - $mimeType = $this->mimeType ?: $this->getMimeTypeForExtension($extension); + /** + * Create a Parse File from the contents of a local file + * i.e. $file = ParseFile::createFromFile("/tmp/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 + * @param string $mimeType Optional, The mime-type to use when saving the file + * + * @return ParseFile + */ + public static function createFromFile($path, $name, $mimeType = null) + { + $contents = file_get_contents($path, "rb"); + return static::createFromData($contents, $name, $mimeType); + } - $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)); + /** + * Internal method used when constructing a Parse File from Parse. + * + * @param $name + * @param $url + * + * @return ParseFile + * @ignore + */ + public static function _createFromServer($name, $url) + { + $file = new ParseFile(); + $file->name = $name; + $file->url = $url; + return $file; } - curl_close($rest); - if (strpos($contentType, 'text/html') !== false) { - throw new ParseException('Bad Request', -1); + + /** + * Encode to associative array representation. + * + * @return string + * @ignore + */ + public function _encode() + { + return array( + '__type' => 'File', + 'url' => $this->url, + 'name' => $this->name + ); } - $decoded = json_decode($response, true); - if (isset($decoded['error'])) { - throw new ParseException($decoded['error'], - isset($decoded['code']) ? $decoded['code'] : 0 - ); + /** + * Uploads the file contents to Parse, if not saved. + * + * @return bool + */ + public function save() + { + if (!$this->url) { + $response = $this->upload(); + $this->url = $response['url']; + $this->name = $response['name']; + } + return true; } - return $decoded; - } + 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); + } + + $decoded = json_decode($response, true); + if (isset($decoded['error'])) { + throw new ParseException($decoded['error'], + isset($decoded['code']) ? $decoded['code'] : 0 + ); + } + 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); + + 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); + return $response; } - $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", - "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", - "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" - ); + 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", + "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", + "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" + ); - if (isset($knownTypes[$extension])) { - return $knownTypes[$extension]; + if (isset($knownTypes[$extension])) { + return $knownTypes[$extension]; + } + return 'unknown/unknown'; } - return 'unknown/unknown'; - } } diff --git a/src/Parse/ParseGeoPoint.php b/src/Parse/ParseGeoPoint.php index 11bef9f8..32b8552b 100755 --- a/src/Parse/ParseGeoPoint.php +++ b/src/Parse/ParseGeoPoint.php @@ -5,97 +5,97 @@ /** * ParseGeoPoint - Representation of a Parse GeoPoint object. * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ class ParseGeoPoint implements \Parse\Internal\Encodable { - /** - * @var - Float value for latitude. - */ - private $latitude; - /** - * @var - Float value for longitude. - */ - private $longitude; + /** + * @var - Float value for latitude. + */ + private $latitude; + /** + * @var - Float value for longitude. + */ + private $longitude; - /** - * Create a Parse GeoPoint object. - * - * @param float $lat Latitude. - * @param float $lon Longitude. - */ - public function __construct($lat, $lon) - { - $this->setLatitude($lat); - $this->setLongitude($lon); - } + /** + * Create a Parse GeoPoint object. + * + * @param float $lat Latitude. + * @param float $lon Longitude. + */ + public function __construct($lat, $lon) + { + $this->setLatitude($lat); + $this->setLongitude($lon); + } - /** - * Returns the Latitude value for this GeoPoint. - * - * @return float - */ - public function getLatitude() - { - return $this->latitude; - } + /** + * Returns the Latitude value for this GeoPoint. + * + * @return float + */ + public function getLatitude() + { + return $this->latitude; + } - /** - * Set the Latitude value for this GeoPoint. - * - * @param $lat - * - * @throws ParseException - */ - public function setLatitude($lat) - { - if ($lat > 90.0 || $lat < -90.0) { - throw new ParseException("Latitude must be within range [-90.0, 90.0]"); + /** + * Set the Latitude value for this GeoPoint. + * + * @param $lat + * + * @throws ParseException + */ + 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; } - $this->latitude = $lat; - } - /** - * Returns the Longitude value for this GeoPoint. - * - * @return float - */ - public function getLongitude() - { - return $this->longitude; - } + /** + * Returns the Longitude value for this GeoPoint. + * + * @return float + */ + public function getLongitude() + { + return $this->longitude; + } - /** - * Set the Longitude value for this GeoPoint. - * - * @param $lon - * - * @throws ParseException - */ - public function setLongitude($lon) - { - if ($lon > 180.0 || $lon < -180.0) { - throw new ParseException( - "Longitude must be within range [-180.0, 180.0]" - ); + /** + * Set the Longitude value for this GeoPoint. + * + * @param $lon + * + * @throws ParseException + */ + public function setLongitude($lon) + { + 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 - * - * @return array - * @ignore - */ - public function _encode() - { - return array( - '__type' => 'GeoPoint', - 'latitude' => $this->latitude, - 'longitude' => $this->longitude - ); - } + /** + * Encode to associative array representation + * + * @return array + * @ignore + */ + public function _encode() + { + return array( + '__type' => 'GeoPoint', + 'latitude' => $this->latitude, + 'longitude' => $this->longitude + ); + } } diff --git a/src/Parse/ParseInstallation.php b/src/Parse/ParseInstallation.php index 10c61cd0..29a20b0d 100644 --- a/src/Parse/ParseInstallation.php +++ b/src/Parse/ParseInstallation.php @@ -7,12 +7,12 @@ /** * ParseInstallation - Representation of an Installation stored on Parse. * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ class ParseInstallation extends ParseObject { - public static $parseClassName = "_Installation"; + public static $parseClassName = "_Installation"; -} \ No newline at end of file +} diff --git a/src/Parse/ParseMemoryStorage.php b/src/Parse/ParseMemoryStorage.php index 57b449fe..f66e16a9 100644 --- a/src/Parse/ParseMemoryStorage.php +++ b/src/Parse/ParseMemoryStorage.php @@ -6,54 +6,54 @@ * ParseMemoryStorage - Uses non-persisted memory for storage. * This is used by default if a PHP Session is not active. * - * @package Parse - * @author Fosco Marotto + * @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]; + /** + * @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]; + } + return null; + } + + public function clear() + { + $this->storage = array(); } - return null; - } - - public function clear() - { - $this->storage = array(); - } - - public function save() - { - // No action required. - return; - } - - public function getKeys() - { - return array_keys($this->storage); - } - - public function getAll() - { - return $this->storage; - } - -} \ No newline at end of file + + public function save() + { + // No action required. + return; + } + + public function getKeys() + { + return array_keys($this->storage); + } + + public function getAll() + { + return $this->storage; + } + +} diff --git a/src/Parse/ParseObject.php b/src/Parse/ParseObject.php index d701eeb9..957bcb66 100755 --- a/src/Parse/ParseObject.php +++ b/src/Parse/ParseObject.php @@ -16,1186 +16,1186 @@ /** * ParseObject - Representation of an object stored on Parse. * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ class ParseObject implements Encodable { - /** - * @var array - Data as it exists on the server. - */ - protected $serverData; - /** - * @var array - Set of unsaved operations. - */ - protected $operationSet; - /** - * @var array - Estimated value of applying operationSet to serverData. - */ - private $estimatedData; - /** - * @var array - Determine if data available for a given key or not. - */ - private $dataAvailability; - /** - * @var - Class Name for data on Parse. - */ - private $className; - /** - * @var string - Unique identifier on Parse. - */ - private $objectId; - /** - * @var \DateTime - Timestamp when object was created. - */ - private $createdAt; - /** - * @var \DateTime - Timestamp when object was last updated. - */ - private $updatedAt; - /** - * @var bool - Whether the object has been fully fetched from Parse. - */ - private $hasBeenFetched; - - /** - * @var array - Holds the registered subclasses and Parse class names. - */ - private static $registeredSubclasses = array(); - - /** - * Create a Parse Object - * - * Creates a pointer object if an objectId is provided, - * otherwise creates a new object. - * - * @param string $className Class Name for data on Parse. - * @param mixed $objectId Object Id for Existing object. - * @param bool $isPointer - * - * @throws Exception - */ - public function __construct($className = null, $objectId = null, - $isPointer = false) - { - 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 ' . - 'create a subclass object.' - ); - } + /** + * @var array - Data as it exists on the server. + */ + protected $serverData; + /** + * @var array - Set of unsaved operations. + */ + protected $operationSet; + /** + * @var array - Estimated value of applying operationSet to serverData. + */ + private $estimatedData; + /** + * @var array - Determine if data available for a given key or not. + */ + private $dataAvailability; + /** + * @var - Class Name for data on Parse. + */ + private $className; + /** + * @var string - Unique identifier on Parse. + */ + private $objectId; + /** + * @var \DateTime - Timestamp when object was created. + */ + private $createdAt; + /** + * @var \DateTime - Timestamp when object was last updated. + */ + private $updatedAt; + /** + * @var bool - Whether the object has been fully fetched from Parse. + */ + private $hasBeenFetched; + + /** + * @var array - Holds the registered subclasses and Parse class names. + */ + private static $registeredSubclasses = array(); + + /** + * Create a Parse Object + * + * Creates a pointer object if an objectId is provided, + * otherwise creates a new object. + * + * @param string $className Class Name for data on Parse. + * @param mixed $objectId Object Id for Existing object. + * @param bool $isPointer + * + * @throws Exception + */ + public function __construct($className = null, $objectId = null, + $isPointer = false) + { + 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 ' . + '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 = array(); + $this->operationSet = array(); + $this->estimatedData = array(); + $this->dataAvailability = array(); + if ($objectId || $isPointer) { + $this->objectId = $objectId; + $this->hasBeenFetched = false; + } else { + $this->hasBeenFetched = true; + } } - } - - /** - * Gets the Subclass className if exists, otherwise false. - */ - private static function getSubclass() - { - return array_search(get_called_class(), self::$registeredSubclasses); - } - - /** - * Setter to catch property calls and protect certain fields. - * - * @param string $key Key to set a value on. - * @param mixed $value Value to assign. - * - * @return null - * @throws Exception - * @ignore - */ - public function __set($key, $value) - { - if ($key != 'objectId' - && $key != 'createdAt' - && $key != 'updatedAt' - && $key != 'className' - ) { - $this->set($key, $value); - } else { - throw new Exception('Protected field could not be set.'); + + /** + * Gets the Subclass className if exists, otherwise false. + */ + private static function getSubclass() + { + return array_search(get_called_class(), self::$registeredSubclasses); } - } - - /** - * Getter to catch direct property calls and pass them to the get function. - * - * @param string $key Key to retrieve from the Object. - * - * @return mixed - * @ignore - */ - public function __get($key) - { - return $this->get($key); - } - - /** - * Get current value for an object property. - * - * @param string $key Key to retrieve from the estimatedData array. - * - * @return mixed - * - * @throws \Exception - */ - public function get($key) - { - if (!$this->_isDataAvailable($key)) { - throw new \Exception( - 'ParseObject has no data for this key. Call fetch() to get the data.'); + + /** + * Setter to catch property calls and protect certain fields. + * + * @param string $key Key to set a value on. + * @param mixed $value Value to assign. + * + * @return null + * @throws Exception + * @ignore + */ + public function __set($key, $value) + { + if ($key != 'objectId' + && $key != 'createdAt' + && $key != 'updatedAt' + && $key != 'className' + ) { + $this->set($key, $value); + } else { + throw new Exception('Protected field could not be set.'); + } } - if (isset($this->estimatedData[$key])) { - return $this->estimatedData[$key]; + + /** + * Getter to catch direct property calls and pass them to the get function. + * + * @param string $key Key to retrieve from the Object. + * + * @return mixed + * @ignore + */ + public function __get($key) + { + return $this->get($key); } - return null; - } - - /** - * Check if the object has a given key - * - * @param string $key Key to check - * - * @return boolean - */ - public function has($key) - { - return isset($this->estimatedData[$key]); - } - - /** - * Check if the a value associated with a key has been - * added/updated/removed and not saved yet. - * - * @param string $key - * @return bool - */ - public function isKeyDirty($key) - { - return isset($this->operationSet[$key]); - } - - /** - * Check if the object or any of its child objects have unsaved operations. - * - * @return bool - */ - public function isDirty() - { - return $this->_isDirty(true); - } - - /** - * Detects if the object (and optionally the child objects) has unsaved - * changes. - * - * @param $considerChildren - * - * @return bool - * @ignore - */ - protected function _isDirty($considerChildren) - { - return - (count($this->operationSet) || $this->objectId === null) || - ($considerChildren && $this->hasDirtyChildren()); - } - - private function hasDirtyChildren() - { - $result = false; - self::traverse(true, $this->estimatedData, function ($object) use (&$result) { - if ($object instanceof ParseObject) { - if ($object->isDirty()) { - $result = true; + + /** + * Get current value for an object property. + * + * @param string $key Key to retrieve from the estimatedData array. + * + * @return mixed + * + * @throws \Exception + */ + public function get($key) + { + if (!$this->_isDataAvailable($key)) { + throw new \Exception( + 'ParseObject has no data for this key. Call fetch() to get the data.'); } - } - }); - return $result; - } - - /** - * Validate and set a value for an object key. - * - * @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 - */ - public function set($key, $value) - { - if (!$key) { - throw new Exception('key may not be null.'); + if (isset($this->estimatedData[$key])) { + return $this->estimatedData[$key]; + } + return null; } - if (is_array($value)) { - throw new Exception( - 'Must use setArray() or setAssociativeArray() for this value.' - ); + + /** + * Check if the object has a given key + * + * @param string $key Key to check + * + * @return boolean + */ + public function has($key) + { + return isset($this->estimatedData[$key]); } - $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 - */ - public function setArray($key, $value) - { - if (!$key) { - throw new Exception('key may not be null.'); + + /** + * Check if the a value associated with a key has been + * added/updated/removed and not saved yet. + * + * @param string $key + * @return bool + */ + public function isKeyDirty($key) + { + return isset($this->operationSet[$key]); } - if (!is_array($value)) { - throw new Exception( - 'Must use set() for non-array values.' - ); + + /** + * Check if the object or any of its child objects have unsaved operations. + * + * @return bool + */ + public function isDirty() + { + return $this->_isDirty(true); } - $this->_performOperation($key, new SetOperation($value)); - } - - /** - * Set an associative 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 - */ - public function setAssociativeArray($key, $value) - { - if (!$key) { - throw new Exception('key may not be null.'); + + /** + * Detects if the object (and optionally the child objects) has unsaved + * changes. + * + * @param $considerChildren + * + * @return bool + * @ignore + */ + protected function _isDirty($considerChildren) + { + return + (count($this->operationSet) || $this->objectId === null) || + ($considerChildren && $this->hasDirtyChildren()); } - if (!is_array($value)) { - throw new Exception( - 'Must use set() for non-array values.' - ); + + private function hasDirtyChildren() + { + $result = false; + self::traverse(true, $this->estimatedData, function ($object) use (&$result) { + if ($object instanceof ParseObject) { + if ($object->isDirty()) { + $result = true; + } + } + }); + return $result; } - $this->_performOperation($key, new SetOperation($value, true)); - } - - /** - * Remove a value from an array for an object key. - * - * @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 - */ - public function remove($key, $value) - { - if (!$key) { - throw new Exception('key may not be null.'); + + /** + * Validate and set a value for an object key. + * + * @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 + */ + public function set($key, $value) + { + 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)); } - if (!is_array($value)) { - $value = [$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 + */ + public function setArray($key, $value) + { + 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 RemoveOperation($value)); - } - - /** - * Revert all unsaved operations. - * - * @return null - */ - public function revert() - { - $this->operationSet = array(); - $this->rebuildEstimatedData(); - } - - /** - * Clear all keys on this object by creating delete operations - * for each key. - * - * @return null - */ - public function clear() - { - foreach ($this->estimatedData as $key => $value) { - $this->delete($key); + + /** + * Set an associative 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 + */ + public function setAssociativeArray($key, $value) + { + 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)); } - } - - /** - * Perform an operation on an object property. - * - * @param string $key Key to perform an operation upon. - * @param FieldOperation $operation Operation to perform. - * - * @return null - * @ignore - */ - public function _performOperation($key, FieldOperation $operation) - { - $oldValue = null; - if (isset($this->estimatedData[$key])) { - $oldValue = $this->estimatedData[$key]; + + /** + * Remove a value from an array for an object key. + * + * @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 + */ + 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)); } - $newValue = $operation->_apply($oldValue, $this, $key); - if ($newValue !== null) { - $this->estimatedData[$key] = $newValue; - } else if (isset($this->estimatedData[$key])) { - unset($this->estimatedData[$key]); + + /** + * Revert all unsaved operations. + * + * @return null + */ + public function revert() + { + $this->operationSet = array(); + $this->rebuildEstimatedData(); } - if (isset($this->operationSet[$key])) { - $oldOperations = $this->operationSet[$key]; - $newOperations = $operation->_mergeWithPrevious($oldOperations); - $this->operationSet[$key] = $newOperations; - } else { - $this->operationSet[$key] = $operation; + /** + * Clear all keys on this object by creating delete operations + * for each key. + * + * @return null + */ + public function clear() + { + foreach ($this->estimatedData as $key => $value) { + $this->delete($key); + } } - $this->dataAvailability[$key] = true; - } - - /** - * Get the Parse Class Name for the object. - * - * @return string - */ - public function getClassName() - { - return $this->className; - } - - /** - * Get the objectId for the object, or null if unsaved. - * - * @return string|null - */ - public function getObjectId() - { - return $this->objectId; - } - - /** - * Get the createdAt for the object, or null if unsaved. - * - * @return \DateTime|null - */ - public function getCreatedAt() - { - return $this->createdAt; - } - - /** - * Returns true if the object has been fetched. - * - * @return bool - */ - public function isDataAvailable() - { - return $this->hasBeenFetched; - } - - private function _isDataAvailable($key) - { - return $this->isDataAvailable() || isset($this->dataAvailability[$key]); - - } - - /** - * Get the updatedAt for the object, or null if unsaved. - * - * @return \DateTime|null - */ - public function getUpdatedAt() - { - return $this->updatedAt; - } - - /** - * Static method which returns a new Parse Object for a given class - * Optionally creates a pointer object if the objectId is provided. - * - * @param string $className Class Name for data on Parse. - * @param string $objectId Unique identifier for existing object. - * @param bool $isPointer If the object is a pointer. - * - * @return Object - */ - public static function create($className, $objectId = null, - $isPointer = false) - { - if (isset(self::$registeredSubclasses[$className])) { - return new self::$registeredSubclasses[$className]( - $className, $objectId, $isPointer - ); - } else { - return new ParseObject($className, $objectId, $isPointer); + + /** + * Perform an operation on an object property. + * + * @param string $key Key to perform an operation upon. + * @param FieldOperation $operation Operation to perform. + * + * @return null + * @ignore + */ + 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]); + } + + 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; } - } - - /** - * Fetch the whole object from the server and update the local object. - * - * @param bool $useMasterKey Whether to use the master key and override ACLs - * - * @return null - */ - public function fetch($useMasterKey = false) - { - $sessionToken = null; - if (ParseUser::getCurrentUser()) { - $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); + + /** + * Get the Parse Class Name for the object. + * + * @return string + */ + public function getClassName() + { + return $this->className; } - $response = ParseClient::_request( - 'GET', - '/1/classes/' . $this->className . '/' . $this->objectId, - $sessionToken, null, $useMasterKey - ); - $this->_mergeAfterFetch($response); - } - - /** - * Merges data received from the server. - * - * @param array $result Data retrieved from the server. - * @param bool $completeData Fetch all data or not. - * - * @return null - * @ignore - */ - public function _mergeAfterFetch($result, $completeData = true) - { - // 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]); - } + + /** + * Get the objectId for the object, or null if unsaved. + * + * @return string|null + */ + public function getObjectId() + { + return $this->objectId; } - $this->serverData = array(); - $this->dataAvailability = array(); - $this->mergeFromServer($result, $completeData); - $this->rebuildEstimatedData(); - } - - /** - * Merges data received from the server with a given selected keys. - * - * @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; + + /** + * Get the createdAt for the object, or null if unsaved. + * + * @return \DateTime|null + */ + public function getCreatedAt() + { + return $this->createdAt; } - } - - /** - * Merges data received from the server. - * - * @param array $data Data retrieved from server. - * @param bool $completeData Fetch all data or not. - * - * @return null - */ - 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); - - 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); - } - } - $this->serverData[$key] = $decodedValue; - $this->dataAvailability[$key] = true; + /** + * Returns true if the object has been fetched. + * + * @return bool + */ + public function isDataAvailable() + { + return $this->hasBeenFetched; } - if (!$this->updatedAt && $this->createdAt) { - $this->updatedAt = $this->createdAt; + + private function _isDataAvailable($key) + { + return $this->isDataAvailable() || isset($this->dataAvailability[$key]); + } - } - - /** - * Handle merging of special fields for the object. - * - * @param array &$data Data received from server. - * - * @return null - */ - public function _mergeMagicFields(&$data) - { - if (isset($data['objectId'])) { - $this->objectId = $data['objectId']; - unset($data['objectId']); + + /** + * Get the updatedAt for the object, or null if unsaved. + * + * @return \DateTime|null + */ + public function getUpdatedAt() + { + return $this->updatedAt; } - if (isset($data['createdAt'])) { - $this->createdAt = new \DateTime($data['createdAt']); - unset($data['createdAt']); + + /** + * Static method which returns a new Parse Object for a given class + * Optionally creates a pointer object if the objectId is provided. + * + * @param string $className Class Name for data on Parse. + * @param string $objectId Unique identifier for existing object. + * @param bool $isPointer If the object is a pointer. + * + * @return Object + */ + public static function create($className, $objectId = null, + $isPointer = false) + { + if (isset(self::$registeredSubclasses[$className])) { + return new self::$registeredSubclasses[$className]( + $className, $objectId, $isPointer + ); + } else { + return new ParseObject($className, $objectId, $isPointer); + } } - if (isset($data['updatedAt'])) { - $this->updatedAt = new \DateTime($data['updatedAt']); - unset($data['updatedAt']); + + /** + * Fetch the whole object from the server and update the local object. + * + * @param bool $useMasterKey Whether to use the master key and override ACLs + * + * @return null + */ + public function fetch($useMasterKey = false) + { + $sessionToken = null; + if (ParseUser::getCurrentUser()) { + $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); + } + $response = ParseClient::_request( + 'GET', + '/1/classes/' . $this->className . '/' . $this->objectId, + $sessionToken, null, $useMasterKey + ); + $this->_mergeAfterFetch($response); } - if (isset($data['ACL'])) { - $acl = ParseACL::_createACLFromJSON($data['ACL']); - $this->serverData['ACL'] = $acl; - unset($data['ACL']); + + /** + * Merges data received from the server. + * + * @param array $result Data retrieved from the server. + * @param bool $completeData Fetch all data or not. + * + * @return null + * @ignore + */ + public function _mergeAfterFetch($result, $completeData = true) + { + // 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]); + } + } + $this->serverData = array(); + $this->dataAvailability = array(); + $this->mergeFromServer($result, $completeData); + $this->rebuildEstimatedData(); } - } - - /** - * Start from serverData and process operations to generate the current - * value set for an object. - * - * @return null - */ - protected function rebuildEstimatedData() - { - $this->estimatedData = array(); - foreach ($this->serverData as $key => $value) { - $this->estimatedData[$key] = $value; + /** + * Merges data received from the server with a given selected keys. + * + * @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->applyOperations($this->operationSet, $this->estimatedData); - } - - /** - * Apply operations to a target object - * - * @param array $operations Operations set to apply. - * @param array &$target Target data to affect. - * - * @return null - */ - 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) - && $newValue !== null && !is_scalar($newValue) - ) { - unset($target[$key]); - unset($this->dataAvailability[$key]); - } else { - $target[$key] = $newValue; - $this->dataAvailability[$key] = true; - } + + /** + * Merges data received from the server. + * + * @param array $data Data retrieved from server. + * @param bool $completeData Fetch all data or not. + * + * @return null + */ + 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); + + 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); + } + } + $this->serverData[$key] = $decodedValue; + $this->dataAvailability[$key] = true; + + } + if (!$this->updatedAt && $this->createdAt) { + $this->updatedAt = $this->createdAt; + } } - } - - /** - * Delete the object from Parse. - * - * @param bool $useMasterKey Whether to use the master key. - * - * @return null - */ - public function destroy($useMasterKey = false) - { - if (!$this->objectId) { - return; + + /** + * Handle merging of special fields for the object. + * + * @param array &$data Data received from server. + * + * @return null + */ + 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']); + } + + } + + /** + * Start from serverData and process operations to generate the current + * value set for an object. + * + * @return null + */ + protected function rebuildEstimatedData() + { + $this->estimatedData = array(); + foreach ($this->serverData as $key => $value) { + $this->estimatedData[$key] = $value; + } + $this->applyOperations($this->operationSet, $this->estimatedData); } - $sessionToken = null; - if (ParseUser::getCurrentUser()) { - $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); + + /** + * Apply operations to a target object + * + * @param array $operations Operations set to apply. + * @param array &$target Target data to affect. + * + * @return null + */ + 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) + && $newValue !== null && !is_scalar($newValue) + ) { + unset($target[$key]); + unset($this->dataAvailability[$key]); + } else { + $target[$key] = $newValue; + $this->dataAvailability[$key] = true; + } + } } - ParseClient::_request( - 'DELETE', '/1/classes/' . $this->className . - '/' . $this->objectId, $sessionToken, null, $useMasterKey - ); - } - - /** - * Delete an array of objects. - * - * @param array $objects Objects to destroy. - * @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); - $currentBatch = []; - $currentcount = 0; + + /** + * Delete the object from Parse. + * + * @param bool $useMasterKey Whether to use the master key. + * + * @return null + */ + public function destroy($useMasterKey = false) + { + if (!$this->objectId) { + return; } - } - if (count($errors)) { - throw new ParseAggregateException( - "Errors during batch destroy.", $errors + $sessionToken = null; + if (ParseUser::getCurrentUser()) { + $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); + } + ParseClient::_request( + 'DELETE', '/1/classes/' . $this->className . + '/' . $this->objectId, $sessionToken, null, $useMasterKey ); - } - } - return null; - } - - private static function destroyBatch(array $objects, $useMasterKey = false) - { - $data = []; - $errors = []; - foreach ($objects as $object) { - $data[] = array( - "method" => "DELETE", - "path" => "/1/classes/" . $object->getClassName() . - "/" . $object->getObjectId() - ); } - $sessionToken = null; - if (ParseUser::getCurrentUser()) { - $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); + + /** + * Delete an array of objects. + * + * @param array $objects Objects to destroy. + * @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); + $currentBatch = []; + $currentcount = 0; + } + } + if (count($errors)) { + throw new ParseAggregateException( + "Errors during batch destroy.", $errors + ); + } + } + return null; } - $result = ParseClient::_request( - "POST", "/1/batch", $sessionToken, - json_encode(array("requests" => $data)), - $useMasterKey - ); - 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( - 'error' => $error, - 'code' => $code + + private static function destroyBatch(array $objects, $useMasterKey = false) + { + $data = []; + $errors = []; + foreach ($objects as $object) { + $data[] = array( + "method" => "DELETE", + "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)), + $useMasterKey ); - } + 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( + 'error' => $error, + 'code' => $code + ); + } + } + return $errors; } - return $errors; - } - - /** - * Increment a numeric key by a certain value. - * - * @param string $key Key for numeric value on object to increment. - * @param int $value Value to increment by. - * - * @return null - */ - public function increment($key, $value = 1) - { - $this->_performOperation($key, new IncrementOperation($value)); - } - - /** - * Add a value to an array property. - * - * @param string $key Key for array value on object to add a value to. - * @param mixed $value Value to add. - * - * @return null - */ - public function add($key, $value) - { - $this->_performOperation($key, new AddOperation($value)); - } - - /** - * Add unique values to an array property. - * - * @param string $key Key for array value on object. - * @param mixed $value Value list to add uniquely. - * - * @return null - */ - public function addUnique($key, $value) - { - $this->_performOperation($key, new AddUniqueOperation($value)); - } - - /** - * Delete a key from an object. - * - * @param string $key Key to remove from object. - * - * @return null - */ - public function delete($key) - { - $this->_performOperation($key, new DeleteOperation()); - } - - /** - * Return a JSON encoded value of the object. - * - * @return string - * @ignore - */ - public function _encode() - { - $out = array(); - if ($this->objectId) { - $out['objectId'] = $this->objectId; + + /** + * Increment a numeric key by a certain value. + * + * @param string $key Key for numeric value on object to increment. + * @param int $value Value to increment by. + * + * @return null + */ + public function increment($key, $value = 1) + { + $this->_performOperation($key, new IncrementOperation($value)); } - if ($this->createdAt) { - $out['createdAt'] = $this->createdAt; + + /** + * Add a value to an array property. + * + * @param string $key Key for array value on object to add a value to. + * @param mixed $value Value to add. + * + * @return null + */ + public function add($key, $value) + { + $this->_performOperation($key, new AddOperation($value)); } - if ($this->updatedAt) { - $out['updatedAt'] = $this->updatedAt; + + /** + * Add unique values to an array property. + * + * @param string $key Key for array value on object. + * @param mixed $value Value list to add uniquely. + * + * @return null + */ + public function addUnique($key, $value) + { + $this->_performOperation($key, new AddUniqueOperation($value)); } - foreach ($this->serverData as $key => $value) { - $out[$key] = $value; + + /** + * Delete a key from an object. + * + * @param string $key Key to remove from object. + * + * @return null + */ + public function delete($key) + { + $this->_performOperation($key, new DeleteOperation()); } - 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(); - } else { - $out[$key][] = $item; - } + + /** + * Return a JSON encoded value of the object. + * + * @return string + * @ignore + */ + public function _encode() + { + $out = array(); + if ($this->objectId) { + $out['objectId'] = $this->objectId; } - } else { - $out[$key] = $value; - } - } - return json_encode($out); - } - - /** - * Returns JSON object of the unsaved operations. - * - * @return array - */ - private function getSaveJSON() - { - return ParseClient::_encode($this->operationSet, true); - } - - /** - * Save Object to Parse - * - * @param bool $useMasterKey Whether to use the Master Key. - * - * @return null - */ - public function save($useMasterKey = false) - { - if (!$this->isDirty()) { - return; + 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(); + } else { + $out[$key][] = $item; + } + } + } else { + $out[$key] = $value; + } + } + return json_encode($out); } - static::deepSave($this, $useMasterKey); - } - - /** - * Save all the objects in the provided array - * - * @param array $list - * @param bool $useMasterKey Whether to use the Master Key. - * - * @return null - */ - public static function saveAll($list, $useMasterKey = false) - { - static::deepSave($list, $useMasterKey); - } - - /** - * Save Object and unsaved children within. - * - * @param $target - * @param bool $useMasterKey Whether to use the Master Key. - * - * @return null - * - * @throws ParseException - */ - 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(); + + /** + * Returns JSON object of the unsaved operations. + * + * @return array + */ + private function getSaveJSON() + { + return ParseClient::_encode($this->operationSet, true); } - foreach ($unsavedFiles as &$file) { - $file->save(); + /** + * Save Object to Parse + * + * @param bool $useMasterKey Whether to use the Master Key. + * + * @return null + */ + public function save($useMasterKey = false) + { + if (!$this->isDirty()) { + return; + } + static::deepSave($this, $useMasterKey); } - $objects = array(); - // Get the set of unique objects among the children. - foreach ($unsavedChildren as &$obj) { - if (!in_array($obj, $objects, true)) { - $objects[] = $obj; - } + /** + * Save all the objects in the provided array + * + * @param array $list + * @param bool $useMasterKey Whether to use the Master Key. + * + * @return null + */ + public static function saveAll($list, $useMasterKey = false) + { + static::deepSave($list, $useMasterKey); } - $remaining = $objects; - while (count($remaining) > 0) { + /** + * Save Object and unsaved children within. + * + * @param $target + * @param bool $useMasterKey Whether to use the Master Key. + * + * @return null + * + * @throws ParseException + */ + 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(); + } - $batch = array(); - $newRemaining = array(); + foreach ($unsavedFiles as &$file) { + $file->save(); + } - foreach ($remaining as $key => &$object) { - if (count($batch) > 40) { - $newRemaining[] = $object; - continue; + $objects = array(); + // Get the set of unique objects among the children. + foreach ($unsavedChildren as &$obj) { + if (!in_array($obj, $objects, true)) { + $objects[] = $obj; + } } - if ($object->canBeSerialized()) { - $batch[] = $object; - } else { - $newRemaining[] = $object; + $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; + } + } + $remaining = $newRemaining; + + 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 + ); + } + + 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 + ); + } else { + $errorCollection[] = array( + 'error' => 'Unknown error in batch save.', + 'code' => -1, + 'object' => $obj + ); + } + } + if (count($errorCollection)) { + throw new ParseAggregateException( + "Errors during batch save.", $errorCollection + ); + } + } } - } - $remaining = $newRemaining; - - 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'; + } + + /** + * Find unsaved children inside an object. + * + * @param ParseObject $object Object to search. + * @param array &$unsavedChildren Array to populate with children. + * @param array &$unsavedFiles Array to populate with files. + */ + private static function findUnsavedChildren($object, + &$unsavedChildren, &$unsavedFiles) + { + 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; + } + } + + }); + } + + /** + * Traverse object to find children. + * + * @param boolean $deep Should this call traverse deeply + * @param ParseObject|array &$object Object to traverse. + * @param callable $mapFunction Function to call for every item. + * @param array $seen Objects already seen. + * + * @return mixed The result of calling mapFunction on the root object. + */ + private static function traverse($deep, &$object, $mapFunction, + $seen = array()) + { + if ($object instanceof ParseObject) { + if (in_array($object, $seen, true)) { + return null; + } + $seen[] = $object; + if ($deep) { + self::traverse( + $deep, $object->estimatedData, $mapFunction, $seen + ); + } + return $mapFunction($object); } - $requests[] = array('method' => $method, - 'path' => $path, - 'body' => $json - ); - } - - 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 - ); - } else { - $errorCollection[] = array( - 'error' => 'Unknown error in batch save.', - 'code' => -1, - 'object' => $obj - ); - } + if ($object instanceof ParseRelation || $object instanceof ParseFile) { + return $mapFunction($object); } - if (count($errorCollection)) { - throw new ParseAggregateException( - "Errors during batch save.", $errorCollection - ); + if (is_array($object)) { + foreach ($object as $key => $value) { + self::traverse($deep, $value, $mapFunction, $seen); + } + return $mapFunction($object); } - } + return $mapFunction($object); } - } - - /** - * Find unsaved children inside an object. - * - * @param ParseObject $object Object to search. - * @param array &$unsavedChildren Array to populate with children. - * @param array &$unsavedFiles Array to populate with files. - */ - private static function findUnsavedChildren($object, - &$unsavedChildren, &$unsavedFiles) - { - 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; - } - } - - }); - } - - /** - * Traverse object to find children. - * - * @param boolean $deep Should this call traverse deeply - * @param ParseObject|array &$object Object to traverse. - * @param callable $mapFunction Function to call for every item. - * @param array $seen Objects already seen. - * - * @return mixed The result of calling mapFunction on the root object. - */ - private static function traverse($deep, &$object, $mapFunction, - $seen = array()) - { - if ($object instanceof ParseObject) { - if (in_array($object, $seen, true)) { - return null; - } - $seen[] = $object; - if ($deep) { - self::traverse( - $deep, $object->estimatedData, $mapFunction, $seen - ); - } - return $mapFunction($object); + + /** + * Determine if the current object can be serialized for saving. + * + * @return bool + */ + private function canBeSerialized() + { + return self::canBeSerializedAsValue($this->estimatedData); } - if ($object instanceof ParseRelation || $object instanceof ParseFile) { - return $mapFunction($object); + + /** + * Checks the given object and any children to see if the whole object + * can be serialized for saving. + * + * @param mixed $object The value to check. + * + * @return bool + */ + private static function canBeSerializedAsValue($object) + { + $result = true; + self::traverse(false, $object, function ($obj) use (&$result) { + // short circuit as soon as possible. + if ($result === false) { + return; + } + // cannot make a pointer to an unsaved object. + if ($obj instanceof ParseObject) { + if (!$obj->getObjectId()) { + $result = false; + return; + } + } + }); + return $result; } - if (is_array($object)) { - foreach ($object as $key => $value) { - self::traverse($deep, $value, $mapFunction, $seen); - } - return $mapFunction($object); + + /** + * Merge server data after a save completes. + * + * @param array $result Data retrieved from server. + * + * @return null + */ + private function mergeAfterSave($result) + { + $this->applyOperations($this->operationSet, $this->serverData); + $this->mergeFromServer($result); + $this->operationSet = array(); + $this->rebuildEstimatedData(); } - return $mapFunction($object); - } - - /** - * Determine if the current object can be serialized for saving. - * - * @return bool - */ - private function canBeSerialized() - { - return self::canBeSerializedAsValue($this->estimatedData); - } - - /** - * Checks the given object and any children to see if the whole object - * can be serialized for saving. - * - * @param mixed $object The value to check. - * - * @return bool - */ - private static function canBeSerializedAsValue($object) - { - $result = true; - self::traverse(false, $object, function ($obj) use (&$result) { - // short circuit as soon as possible. - if ($result === false) { - return; - } - // cannot make a pointer to an unsaved object. - if ($obj instanceof ParseObject) { - if (!$obj->getObjectId()) { - $result = false; - return; + + /** + * 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()); + } } - } - }); - return $result; - } - - /** - * Merge server data after a save completes. - * - * @param array $result Data retrieved from server. - * - * @return null - */ - private function mergeAfterSave($result) - { - $this->applyOperations($this->operationSet, $this->serverData); - $this->mergeFromServer($result); - $this->operationSet = array(); - $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()); - } + return $relation; } - return $relation; - } - - /** - * Gets a Pointer referencing this Object. - * - * @return array - * - * @throws \Exception - * @ignore - */ - public function _toPointer() - { - if (!$this->objectId) { - throw new \Exception("Can't serialize an unsaved Parse.Object"); + + /** + * Gets a Pointer referencing this Object. + * + * @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", + 'className' => $this->className, + 'objectId' => $this->objectId); } - return array( - '__type' => "Pointer", - 'className' => $this->className, - 'objectId' => $this->objectId); - } - - /** - * Set ACL for this object. - * - * @param ParseACL $acl - */ - public function setACL($acl) - { - $this->_performOperation('ACL', new SetOperation($acl)); - } - - /** - * Get ACL assigned to the object. - * - * @return ParseACL - */ - public function getACL() - { - return $this->getACLWithCopy(true); - } - - private function getACLWithCopy($mayCopy) - { - if (!isset($this->estimatedData['ACL'])) { - return null; + + /** + * Set ACL for this object. + * + * @param ParseACL $acl + */ + public function setACL($acl) + { + $this->_performOperation('ACL', new SetOperation($acl)); } - $acl = $this->estimatedData['ACL']; - if ($mayCopy && $acl->_isShared()) { - return clone $acl; + + /** + * Get ACL assigned to the object. + * + * @return ParseACL + */ + public function getACL() + { + return $this->getACLWithCopy(true); } - 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] = - get_called_class(); - } - } else { - throw new \Exception( - "Cannot register a subclass that does not have a parseClassName" - ); + + private function getACLWithCopy($mayCopy) + { + if (!isset($this->estimatedData['ACL'])) { + return null; + } + $acl = $this->estimatedData['ACL']; + if ($mayCopy && $acl->_isShared()) { + return clone $acl; + } + return $acl; } - } - - /** - * Un-register a subclass. - * Cannot be called on the base class ParseObject. - * @ignore - */ - public static function _unregisterSubclass() - { - $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 - */ - public static function query() - { - $subclass = static::getSubclass(); - if ($subclass === false) { - throw new Exception( - 'Cannot create a query for an unregistered subclass.' - ); - } else { - return new ParseQuery($subclass); + + /** + * 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] = + get_called_class(); + } + } 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]); + } + + /** + * Creates a ParseQuery for the subclass of ParseObject. + * Cannot be called on the base class ParseObject. + * + * @return ParseQuery + * + * @throws \Exception + */ + public static function query() + { + $subclass = static::getSubclass(); + if ($subclass === false) { + throw new Exception( + 'Cannot create a query for an unregistered subclass.' + ); + } else { + return new ParseQuery($subclass); + } } - } } diff --git a/src/Parse/ParsePush.php b/src/Parse/ParsePush.php index 59638d1c..a149e25a 100644 --- a/src/Parse/ParsePush.php +++ b/src/Parse/ParsePush.php @@ -5,64 +5,64 @@ /** * ParsePush - Handles sending push notifications with Parse * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ class ParsePush { - /** - * Sends a push notification. - * - * @param array $data The data of the push notification. Valid fields - * are: - * channels - An Array of channels to push to. - * push_time - A Date object for when to send the push. - * expiration_time - A Date object for when to expire - * the push. - * expiration_interval - The seconds from now to expire the push. - * where - A ParseQuery over ParseInstallation that is used to match - * a set of installations to push to. - * data - The data to send as part of the push - * @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']) - && isset($data['expiration_interval'])) { - 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( - 'Where parameter for Parse Push must be of type ParseQuery' + /** + * Sends a push notification. + * + * @param array $data The data of the push notification. Valid fields + * are: + * channels - An Array of channels to push to. + * push_time - A Date object for when to send the push. + * expiration_time - A Date object for when to expire + * the push. + * expiration_interval - The seconds from now to expire the push. + * where - A ParseQuery over ParseInstallation that is used to match + * a set of installations to push to. + * data - The data to send as part of the push + * @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']) + && isset($data['expiration_interval'])) { + 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( + '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 + //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( + $data['expiration_time'], false + )['iso']; + } + return ParseClient::_request( + 'POST', + '/1/push', + null, + json_encode($data), + $useMasterKey ); - } - } - 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( - $data['expiration_time'], false - )['iso']; } - return ParseClient::_request( - 'POST', - '/1/push', - null, - json_encode($data), - $useMasterKey - ); - } -} \ No newline at end of file +} diff --git a/src/Parse/ParseQuery.php b/src/Parse/ParseQuery.php index 2e080685..91c5864d 100755 --- a/src/Parse/ParseQuery.php +++ b/src/Parse/ParseQuery.php @@ -5,772 +5,772 @@ /** * ParseQuery - Handles querying data from Parse * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ class ParseQuery { - /** - * @var - Class Name for data stored on Parse. - */ - private $className; - /** - * @var array - Where constraints. - */ - private $where = array(); - /** - * @var array - Order By keys. - */ - private $orderBy = array(); - /** - * @var array - Include nested objects. - */ - private $includes = array(); - /** - * @var array - Include certain keys only. - */ - private $selectedKeys = array(); - /** - * @var int - Skip from the beginning of the search results. - */ - private $skip = 0; - /** - * @var - Determines if the query is a count query or a results query. - */ - private $count; - /** - * @var int - Limit of results, defaults to 100 when not explicitly set. - */ - private $limit = -1; - - /** - * Create a Parse Query for a given Parse Class. - * - * @param mixed $className Class Name of data on Parse. - */ - public function __construct($className) - { - $this->className = $className; - } - - /** - * 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 - */ - 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; - } - - /** - * Set a constraint for a field matching a given value. - * - * @param string $key Key to set up an equals constraint. - * @param mixed $value Value the key must equal. - * - * @return ParseQuery Returns this query, so you can chain this call. - */ - public function equalTo($key, $value) - { - if ($value === null) { - $this->doesNotExist($key); - } else { - $this->where[$key] = $value; - } - return $this; - } - - /** - * Helper for condition queries. - */ - private function addCondition($key, $condition, $value) - { - if (!isset($this->where[$key])) { - $this->where[$key] = array(); - } - $this->where[$key][$condition] = ParseClient::_encode($value, true); - } - - /** - * Add a constraint to the query that requires a particular key's value to - * be not equal to the provided value. - * - * @param string $key The key to check. - * @param mixed $value The value that must not be equalled. - * - * @return ParseQuery Returns this query, so you can chain this call. - */ - public function notEqualTo($key, $value) - { - $this->addCondition($key, '$ne', $value); - return $this; - } - - /** - * Add a constraint to the query that requires a particular key's value to - * be less than the provided value. - * - * @param string $key The key to check. - * @param mixed $value The value that provides an Upper bound. - * - * @return ParseQuery Returns this query, so you can chain this call. - */ - public function lessThan($key, $value) - { - $this->addCondition($key, '$lt', $value); - return $this; - } - - /** - * Add a constraint to the query that requires a particular key's value to - * be greater than the provided value. - * - * @param string $key The key to check. - * @param mixed $value The value that provides an Lower bound. - * - * @return ParseQuery Returns this query, so you can chain this call. - */ - public function greaterThan($key, $value) - { - $this->addCondition($key, '$gt', $value); - return $this; - } - - /** - * Add a constraint to the query that requires a particular key's value to - * be greater than or equal to the provided value. - * - * @param string $key The key to check. - * @param mixed $value The value that provides an Lower bound. - * - * @return ParseQuery Returns this query, so you can chain this call. - */ - public function greaterThanOrEqualTo($key, $value) - { - $this->addCondition($key, '$gte', $value); - return $this; - } - - /** - * Add a constraint to the query that requires a particular key's value to - * be less than or equal to the provided value. - * - * @param string $key The key to check. - * @param mixed $value The value that provides an Upper bound. - * - * @return ParseQuery Returns this query, so you can chain this call. - */ - public function lessThanOrEqualTo($key, $value) - { - $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"; - } - - /** - * Add a constraint to the query that requires a particular key's value to - * start with the provided value. - * - * @param string $key The key to check. - * @param mixed $value The substring that the value must start with. - * - * @return ParseQuery Returns this query, so you can chain this call. - */ - public function startsWith($key, $value) - { - $this->addCondition($key, '$regex', "^".$this->quote($value)); - return $this; - } - - /** - * Returns an associative array of the query constraints. - * - * @return array - * @ignore - */ - 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; - } - - /** - * Execute a query to get only the first result. - * - * @param bool $useMasterKey If the query should use the master key - * - * @return array - */ - public function first($useMasterKey = false) - { - $this->limit = 1; - $result = $this->find($useMasterKey); - if (count($result)) { - return $result[0]; - } else { - return array(); - } - } - - /** - * 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); - } - - /** - * Execute a count query and return the count. - * - * @param bool $useMasterKey If the query should use the master key - * - * @return int - */ - 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']; - } - - /** - * Execute a find query and return the results. - * - * @param boolean $useMasterKey - * - * @return array - */ - 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; - } - - /** - * Set the skip parameter as a query constraint. - * - * @param int $n Number of objects to skip from start of results. - * - * @return ParseQuery Returns this query, so you can chain this call. - */ - public function skip($n) - { - $this->skip = $n; - return $this; - } - - /** - * Set the limit parameter as a query constraint - * - * @param int $n Number of objects to return from the query. - * - * @return ParseQuery Returns this query, so you can chain this call. - */ - public function limit($n) - { - $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); - } - - /** - * Set the query orderBy to ascending for the given key(s). It can also add - * secondary sort descriptors without overwriting the existing order. - * - * @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 addAscending($key) - { - 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); - } - - /** - * Set the query orderBy to descending for a given key(s). It can also add - * secondary sort descriptors without overwriting the existing order. - * - * @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 addDescending($key) - { - 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; - } - - /** - * Add a proximity based constraint for finding objects with key point - * values near the point given. - * - * @param string $key The key that the ParseGeoPoint is stored in. - * @param ParseGeoPoint $point The reference ParseGeoPoint that is used. - * - * @return ParseQuery Returns this query, so you can chain this call. - */ - public function near($key, $point) - { - $this->addCondition($key, '$nearSphere', $point); - return $this; - } - - /** - * Add a proximity based constraint for finding objects with key point - * values near the point given and within the maximum distance given. - * - * @param string $key The key of the ParseGeoPoint - * @param ParseGeoPoint $point The ParseGeoPoint that is used. - * @param int $maxDistance Maximum distance (in radians) - * - * @return ParseQuery Returns this query, so you can chain this call. - */ - public function withinRadians($key, $point, $maxDistance) - { - $this->near($key, $point); - $this->addCondition($key, '$maxDistance', $maxDistance); - return $this; - } - - /** - * Add a proximity based constraint for finding objects with key point - * values near the point given and within the maximum distance given. - * Radius of earth used is 3958.5 miles. - * - * @param string $key The key of the ParseGeoPoint - * @param ParseGeoPoint $point The ParseGeoPoint that is used. - * @param int $maxDistance Maximum distance (in miles) - * - * @return ParseQuery Returns this query, so you can chain this call. - */ - public function withinMiles($key, $point, $maxDistance) - { - $this->near($key, $point); - $this->addCondition($key, '$maxDistance', $maxDistance / 3958.8); - return $this; - } - - /** - * Add a proximity based constraint for finding objects with key point - * values near the point given and within the maximum distance given. - * Radius of earth used is 6371.0 kilometers. - * - * @param string $key The key of the ParseGeoPoint - * @param ParseGeoPoint $point The ParseGeoPoint that is used. - * @param int $maxDistance Maximum distance (in kilometers) - * - * @return ParseQuery Returns this query, so you can chain this call. - */ - public function withinKilometers($key, $point, $maxDistance) - { - $this->near($key, $point); - $this->addCondition($key, '$maxDistance', $maxDistance / 6371.0); - return $this; - } - - /** - * Add a constraint to the query that requires a particular key's - * coordinates be contained within a given rectangular geographic bounding - * box. - * - * @param string $key The key of the ParseGeoPoint - * @param ParseGeoPoint $southwest The lower-left corner of the box. - * @param ParseGeoPoint $northeast The upper-right corner of the box. - * - * @return ParseQuery Returns this query, so you can chain this call. - */ - public function withinGeoBox($key, $southwest, $northeast) - { - $this->addCondition($key, '$within', - ['$box' => [$southwest, $northeast]]); - return $this; - } - - /** - * Add a constraint to the query that requires a particular key's value to - * be contained in the provided list of values. - * - * @param string $key The key to check. - * @param array $values The values that will match. - * - * @return ParseQuery Returns the query, so you can chain this call. - */ - public function containedIn($key, $values) - { - $this->addCondition($key, '$in', $values); - return $this; - } - - /** - * Iterates over each result of a query, calling a callback for each one. The - * items are processed in an unspecified order. The query may not have any - * sort order, and may not use limit or skip. - * - * @param callable $callback Callback that will be called with each result - * of the query. - * @param boolean $useMasterKey - * @param int $batchSize - * - * @throws \Exception If query has sort, skip, or limit. - */ - public function each($callback, $useMasterKey = false, $batchSize = 100) - { - 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; - } - } - } - - /** - * Add a constraint to the query that requires a particular key's value to - * not be contained in the provided list of values. - * - * @param string $key The key to check. - * @param array $values The values that will not match. - * - * @return ParseQuery Returns the query, so you can chain this call. - */ - public function notContainedIn($key, $values) - { - $this->addCondition($key, '$nin', $values); - return $this; - } - - /** - * Add a constraint that requires that a key's value matches a ParseQuery - * constraint. - * - * @param string $key The key that the contains the object to match - * the query. - * @param ParseQuery $query The query that should match. - * - * @return ParseQuery Returns the query, so you can chain this call. - */ - public function matchesQuery($key, $query) - { - $queryParam = $query->_getOptions(); - $queryParam["className"] = $query->className; - $this->addCondition($key, '$inQuery', $queryParam); - return $this; - } - - /** - * Add a constraint that requires that a key's value not matches a ParseQuery - * constraint. - * - * @param string $key The key that the contains the object not to - * match the query. - * @param ParseQuery $query The query that should not match. - * - * @return ParseQuery Returns the query, so you can chain this call. - */ - public function doesNotMatchQuery($key, $query) - { - $queryParam = $query->_getOptions(); - $queryParam["className"] = $query->className; - $this->addCondition($key, '$notInQuery', $queryParam); - return $this; - } - - /** - * Add a constraint that requires that a key's value matches a value in an - * object returned by the given query. - * - * @param string $key The key that contains teh value that is being - * matched. - * @param string $queryKey The key in objects returned by the query to - * match against. - * @param ParseQuery $query The query to run. - * - * @return ParseQuery Returns the query, so you can chain this call. - */ - public function matchesKeyInQuery($key, $queryKey, $query) - { - $queryParam = $query->_getOptions(); - $queryParam["className"] = $query->className; - $this->addCondition($key, '$select', - ['key' => $queryKey, 'query' => $queryParam]); - return $this; - } - - /** - * Add a constraint that requires that a key's value not match a value in an - * object returned by the given query. - * - * @param string $key The key that contains teh value that is being - * excluded. - * @param string $queryKey The key in objects returned by the query to - * match against. - * @param ParseQuery $query The query to run. - * - * @return ParseQuery Returns the query, so you can chain this call. - */ - public function doesNotMatchKeyInQuery($key, $queryKey, $query) - { - $queryParam = $query->_getOptions(); - $queryParam["className"] = $query->className; - $this->addCondition($key, '$dontSelect', - ['key' => $queryKey, 'query' => $queryParam]); - return $this; - } - - /** - * Constructs a ParseQuery object that is the OR of the passed in queries objects. - * All queries must have same class name. - * - * @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. - */ - 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"); - } - } - $query = new ParseQuery($className); - $query->_or($queryObjects); - return $query; - } - - /** - * Add constraint that at least one of the passed in queries matches. - * - * @param array $queries The list of queries to OR. - * - * @return ParseQuery Returns the query, so you can chain this call. - * @ignore - */ - 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; - } - - /** - * Add a constraint to the query that requires a particular key's value to - * contain each one of the provided list of values. - * - * @param string $key The key to check. This key's value must be an array. - * @param array $values The values that will match. - * - * @return ParseQuery Returns the query, so you can chain this call. - */ - public function containsAll($key, $values) - { - $this->addCondition($key, '$all', $values); - return $this; - } - - /** - * Add a constraint for finding objects that contain the given key. - * - * @param string $key The key that should exist. - * - * @return ParseQuery Returns the query, so you can chain this call. - */ - public function exists($key) - { - $this->addCondition($key, '$exists', true); - return $this; - } - - /** - * Add a constraint for finding objects that not contain the given key. - * - * @param string $key The key that should not exist. - * - * @return ParseQuery Returns the query, so you can chain this call. - */ - public function doesNotExist($key) - { - $this->addCondition($key, '$exists', false); - return $this; - } - - /** - * Restrict the fields of the returned Parse Objects to include only the - * provided keys. If this is called multiple times, then all of the keys - * specified in each of the calls will be included. - * - * @param mixed $key The name(s) of the key(s) to include. It could be - * string, or an Array of string. - * - * @return ParseQuery Returns the query, so you can chain this call. - */ - public function select($key) - { - if (is_array($key)) { - $this->selectedKeys = array_merge($this->selectedKeys, $key); - } else { - $this->selectedKeys[] = $key; - } - return $this; - } - - /** - * Include nested Parse Objects for the provided key. You can use dot - * notation to specify which fields in the included object are also fetch. - * - * @param mixed $key The name(s) of the key(s) to include. It could be - * string, or an Array of string. - * - * @return ParseQuery Returns the query, so you can chain this call. - */ - public function includeKey($key) - { - 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 - * - * @return ParseQuery Returns the query, so you can chain this call. - */ - public function relatedTo($key, $value) - { - $this->addCondition('$relatedTo', $key, $value); - return $this; - } + /** + * @var - Class Name for data stored on Parse. + */ + private $className; + /** + * @var array - Where constraints. + */ + private $where = array(); + /** + * @var array - Order By keys. + */ + private $orderBy = array(); + /** + * @var array - Include nested objects. + */ + private $includes = array(); + /** + * @var array - Include certain keys only. + */ + private $selectedKeys = array(); + /** + * @var int - Skip from the beginning of the search results. + */ + private $skip = 0; + /** + * @var - Determines if the query is a count query or a results query. + */ + private $count; + /** + * @var int - Limit of results, defaults to 100 when not explicitly set. + */ + private $limit = -1; + + /** + * Create a Parse Query for a given Parse Class. + * + * @param mixed $className Class Name of data on Parse. + */ + public function __construct($className) + { + $this->className = $className; + } + + /** + * 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 + */ + 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; + } + + /** + * Set a constraint for a field matching a given value. + * + * @param string $key Key to set up an equals constraint. + * @param mixed $value Value the key must equal. + * + * @return ParseQuery Returns this query, so you can chain this call. + */ + public function equalTo($key, $value) + { + if ($value === null) { + $this->doesNotExist($key); + } else { + $this->where[$key] = $value; + } + return $this; + } + + /** + * Helper for condition queries. + */ + private function addCondition($key, $condition, $value) + { + if (!isset($this->where[$key])) { + $this->where[$key] = array(); + } + $this->where[$key][$condition] = ParseClient::_encode($value, true); + } + + /** + * Add a constraint to the query that requires a particular key's value to + * be not equal to the provided value. + * + * @param string $key The key to check. + * @param mixed $value The value that must not be equalled. + * + * @return ParseQuery Returns this query, so you can chain this call. + */ + public function notEqualTo($key, $value) + { + $this->addCondition($key, '$ne', $value); + return $this; + } + + /** + * Add a constraint to the query that requires a particular key's value to + * be less than the provided value. + * + * @param string $key The key to check. + * @param mixed $value The value that provides an Upper bound. + * + * @return ParseQuery Returns this query, so you can chain this call. + */ + public function lessThan($key, $value) + { + $this->addCondition($key, '$lt', $value); + return $this; + } + + /** + * Add a constraint to the query that requires a particular key's value to + * be greater than the provided value. + * + * @param string $key The key to check. + * @param mixed $value The value that provides an Lower bound. + * + * @return ParseQuery Returns this query, so you can chain this call. + */ + public function greaterThan($key, $value) + { + $this->addCondition($key, '$gt', $value); + return $this; + } + + /** + * Add a constraint to the query that requires a particular key's value to + * be greater than or equal to the provided value. + * + * @param string $key The key to check. + * @param mixed $value The value that provides an Lower bound. + * + * @return ParseQuery Returns this query, so you can chain this call. + */ + public function greaterThanOrEqualTo($key, $value) + { + $this->addCondition($key, '$gte', $value); + return $this; + } + + /** + * Add a constraint to the query that requires a particular key's value to + * be less than or equal to the provided value. + * + * @param string $key The key to check. + * @param mixed $value The value that provides an Upper bound. + * + * @return ParseQuery Returns this query, so you can chain this call. + */ + public function lessThanOrEqualTo($key, $value) + { + $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"; + } + + /** + * Add a constraint to the query that requires a particular key's value to + * start with the provided value. + * + * @param string $key The key to check. + * @param mixed $value The substring that the value must start with. + * + * @return ParseQuery Returns this query, so you can chain this call. + */ + public function startsWith($key, $value) + { + $this->addCondition($key, '$regex', "^".$this->quote($value)); + return $this; + } + + /** + * Returns an associative array of the query constraints. + * + * @return array + * @ignore + */ + 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; + } + + /** + * Execute a query to get only the first result. + * + * @param bool $useMasterKey If the query should use the master key + * + * @return array + */ + public function first($useMasterKey = false) + { + $this->limit = 1; + $result = $this->find($useMasterKey); + if (count($result)) { + return $result[0]; + } else { + return array(); + } + } + + /** + * 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); + } + + /** + * Execute a count query and return the count. + * + * @param bool $useMasterKey If the query should use the master key + * + * @return int + */ + 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']; + } + + /** + * Execute a find query and return the results. + * + * @param boolean $useMasterKey + * + * @return array + */ + 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; + } + + /** + * Set the skip parameter as a query constraint. + * + * @param int $n Number of objects to skip from start of results. + * + * @return ParseQuery Returns this query, so you can chain this call. + */ + public function skip($n) + { + $this->skip = $n; + return $this; + } + + /** + * Set the limit parameter as a query constraint + * + * @param int $n Number of objects to return from the query. + * + * @return ParseQuery Returns this query, so you can chain this call. + */ + public function limit($n) + { + $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); + } + + /** + * Set the query orderBy to ascending for the given key(s). It can also add + * secondary sort descriptors without overwriting the existing order. + * + * @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 addAscending($key) + { + 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); + } + + /** + * Set the query orderBy to descending for a given key(s). It can also add + * secondary sort descriptors without overwriting the existing order. + * + * @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 addDescending($key) + { + 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; + } + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given. + * + * @param string $key The key that the ParseGeoPoint is stored in. + * @param ParseGeoPoint $point The reference ParseGeoPoint that is used. + * + * @return ParseQuery Returns this query, so you can chain this call. + */ + public function near($key, $point) + { + $this->addCondition($key, '$nearSphere', $point); + return $this; + } + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given and within the maximum distance given. + * + * @param string $key The key of the ParseGeoPoint + * @param ParseGeoPoint $point The ParseGeoPoint that is used. + * @param int $maxDistance Maximum distance (in radians) + * + * @return ParseQuery Returns this query, so you can chain this call. + */ + public function withinRadians($key, $point, $maxDistance) + { + $this->near($key, $point); + $this->addCondition($key, '$maxDistance', $maxDistance); + return $this; + } + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given and within the maximum distance given. + * Radius of earth used is 3958.5 miles. + * + * @param string $key The key of the ParseGeoPoint + * @param ParseGeoPoint $point The ParseGeoPoint that is used. + * @param int $maxDistance Maximum distance (in miles) + * + * @return ParseQuery Returns this query, so you can chain this call. + */ + public function withinMiles($key, $point, $maxDistance) + { + $this->near($key, $point); + $this->addCondition($key, '$maxDistance', $maxDistance / 3958.8); + return $this; + } + + /** + * Add a proximity based constraint for finding objects with key point + * values near the point given and within the maximum distance given. + * Radius of earth used is 6371.0 kilometers. + * + * @param string $key The key of the ParseGeoPoint + * @param ParseGeoPoint $point The ParseGeoPoint that is used. + * @param int $maxDistance Maximum distance (in kilometers) + * + * @return ParseQuery Returns this query, so you can chain this call. + */ + public function withinKilometers($key, $point, $maxDistance) + { + $this->near($key, $point); + $this->addCondition($key, '$maxDistance', $maxDistance / 6371.0); + return $this; + } + + /** + * Add a constraint to the query that requires a particular key's + * coordinates be contained within a given rectangular geographic bounding + * box. + * + * @param string $key The key of the ParseGeoPoint + * @param ParseGeoPoint $southwest The lower-left corner of the box. + * @param ParseGeoPoint $northeast The upper-right corner of the box. + * + * @return ParseQuery Returns this query, so you can chain this call. + */ + public function withinGeoBox($key, $southwest, $northeast) + { + $this->addCondition($key, '$within', + ['$box' => [$southwest, $northeast]]); + return $this; + } + + /** + * Add a constraint to the query that requires a particular key's value to + * be contained in the provided list of values. + * + * @param string $key The key to check. + * @param array $values The values that will match. + * + * @return ParseQuery Returns the query, so you can chain this call. + */ + public function containedIn($key, $values) + { + $this->addCondition($key, '$in', $values); + return $this; + } + + /** + * Iterates over each result of a query, calling a callback for each one. The + * items are processed in an unspecified order. The query may not have any + * sort order, and may not use limit or skip. + * + * @param callable $callback Callback that will be called with each result + * of the query. + * @param boolean $useMasterKey + * @param int $batchSize + * + * @throws \Exception If query has sort, skip, or limit. + */ + public function each($callback, $useMasterKey = false, $batchSize = 100) + { + 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; + } + } + } + + /** + * Add a constraint to the query that requires a particular key's value to + * not be contained in the provided list of values. + * + * @param string $key The key to check. + * @param array $values The values that will not match. + * + * @return ParseQuery Returns the query, so you can chain this call. + */ + public function notContainedIn($key, $values) + { + $this->addCondition($key, '$nin', $values); + return $this; + } + + /** + * Add a constraint that requires that a key's value matches a ParseQuery + * constraint. + * + * @param string $key The key that the contains the object to match + * the query. + * @param ParseQuery $query The query that should match. + * + * @return ParseQuery Returns the query, so you can chain this call. + */ + public function matchesQuery($key, $query) + { + $queryParam = $query->_getOptions(); + $queryParam["className"] = $query->className; + $this->addCondition($key, '$inQuery', $queryParam); + return $this; + } + + /** + * Add a constraint that requires that a key's value not matches a ParseQuery + * constraint. + * + * @param string $key The key that the contains the object not to + * match the query. + * @param ParseQuery $query The query that should not match. + * + * @return ParseQuery Returns the query, so you can chain this call. + */ + public function doesNotMatchQuery($key, $query) + { + $queryParam = $query->_getOptions(); + $queryParam["className"] = $query->className; + $this->addCondition($key, '$notInQuery', $queryParam); + return $this; + } + + /** + * Add a constraint that requires that a key's value matches a value in an + * object returned by the given query. + * + * @param string $key The key that contains teh value that is being + * matched. + * @param string $queryKey The key in objects returned by the query to + * match against. + * @param ParseQuery $query The query to run. + * + * @return ParseQuery Returns the query, so you can chain this call. + */ + public function matchesKeyInQuery($key, $queryKey, $query) + { + $queryParam = $query->_getOptions(); + $queryParam["className"] = $query->className; + $this->addCondition($key, '$select', + ['key' => $queryKey, 'query' => $queryParam]); + return $this; + } + + /** + * Add a constraint that requires that a key's value not match a value in an + * object returned by the given query. + * + * @param string $key The key that contains teh value that is being + * excluded. + * @param string $queryKey The key in objects returned by the query to + * match against. + * @param ParseQuery $query The query to run. + * + * @return ParseQuery Returns the query, so you can chain this call. + */ + public function doesNotMatchKeyInQuery($key, $queryKey, $query) + { + $queryParam = $query->_getOptions(); + $queryParam["className"] = $query->className; + $this->addCondition($key, '$dontSelect', + ['key' => $queryKey, 'query' => $queryParam]); + return $this; + } + + /** + * Constructs a ParseQuery object that is the OR of the passed in queries objects. + * All queries must have same class name. + * + * @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. + */ + 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"); + } + } + $query = new ParseQuery($className); + $query->_or($queryObjects); + return $query; + } + + /** + * Add constraint that at least one of the passed in queries matches. + * + * @param array $queries The list of queries to OR. + * + * @return ParseQuery Returns the query, so you can chain this call. + * @ignore + */ + 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; + } + + /** + * Add a constraint to the query that requires a particular key's value to + * contain each one of the provided list of values. + * + * @param string $key The key to check. This key's value must be an array. + * @param array $values The values that will match. + * + * @return ParseQuery Returns the query, so you can chain this call. + */ + public function containsAll($key, $values) + { + $this->addCondition($key, '$all', $values); + return $this; + } + + /** + * Add a constraint for finding objects that contain the given key. + * + * @param string $key The key that should exist. + * + * @return ParseQuery Returns the query, so you can chain this call. + */ + public function exists($key) + { + $this->addCondition($key, '$exists', true); + return $this; + } + + /** + * Add a constraint for finding objects that not contain the given key. + * + * @param string $key The key that should not exist. + * + * @return ParseQuery Returns the query, so you can chain this call. + */ + public function doesNotExist($key) + { + $this->addCondition($key, '$exists', false); + return $this; + } + + /** + * Restrict the fields of the returned Parse Objects to include only the + * provided keys. If this is called multiple times, then all of the keys + * specified in each of the calls will be included. + * + * @param mixed $key The name(s) of the key(s) to include. It could be + * string, or an Array of string. + * + * @return ParseQuery Returns the query, so you can chain this call. + */ + public function select($key) + { + if (is_array($key)) { + $this->selectedKeys = array_merge($this->selectedKeys, $key); + } else { + $this->selectedKeys[] = $key; + } + return $this; + } + + /** + * Include nested Parse Objects for the provided key. You can use dot + * notation to specify which fields in the included object are also fetch. + * + * @param mixed $key The name(s) of the key(s) to include. It could be + * string, or an Array of string. + * + * @return ParseQuery Returns the query, so you can chain this call. + */ + public function includeKey($key) + { + 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 + * + * @return ParseQuery Returns the query, so you can chain this call. + */ + public function relatedTo($key, $value) + { + $this->addCondition('$relatedTo', $key, $value); + return $this; + } } diff --git a/src/Parse/ParseRelation.php b/src/Parse/ParseRelation.php index e3a00210..b3431771 100644 --- a/src/Parse/ParseRelation.php +++ b/src/Parse/ParseRelation.php @@ -7,132 +7,132 @@ * ParseRelation - A class that is used to access all of the children of a many-to-many relationship. Each instance * of ParseRelation is associated with a particular parent object and key. * - * @package Parse - * @author Mohamed Madbouli + * @package Parse + * @author Mohamed Madbouli */ class ParseRelation { - /** - * @var ParseObject - The parent of this relation. - */ - private $parent; - /** - * @var string - The key of the relation in the parent object. - */ - private $key; - /** - * @var string - The className of the target objects. - */ - private $targetClassName; + /** + * @var ParseObject - The parent of this relation. + */ + private $parent; + /** + * @var string - The key of the relation in the parent object. + */ + private $key; + /** + * @var string - The className of the target objects. + */ + private $targetClassName; - /** - * Creates a new Relation for the given parent object, key and class name of target objects. - * - * @param ParseObject $parent The parent of this relation. - * @param string $key The key of the relation in the parent object. - * @param string $targetClassName The className of the target objects. - */ - public function __construct($parent, $key, $targetClassName = null) - { - $this->parent = $parent; - $this->key = $key; - $this->targetClassName = $targetClassName; - } - - /** - * Makes sure that this relation has the right parent and key. - * - * @param $parent - * @param $key - * - * @throws \Exception - */ - private function ensureParentAndKey($parent, $key) - { - if (!$this->parent) { - $this->parent = $parent; - } - if (!$this->key) { - $this->key = $key; + /** + * Creates a new Relation for the given parent object, key and class name of target objects. + * + * @param ParseObject $parent The parent of this relation. + * @param string $key The key of the relation in the parent object. + * @param string $targetClassName The className of the target objects. + */ + public function __construct($parent, $key, $targetClassName = null) + { + $this->parent = $parent; + $this->key = $key; + $this->targetClassName = $targetClassName; } - 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.'); + + /** + * Makes sure that this relation has the right parent and key. + * + * @param $parent + * @param $key + * + * @throws \Exception + */ + 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.'); + } } - } - /** - * Adds a ParseObject or an array of ParseObjects to the relation. - * - * @param mixed $objects The item or items to add. - */ - public function add($objects) - { - if (!is_array($objects)) { - $objects = [$objects]; + /** + * Adds a ParseObject or an array of ParseObjects to the relation. + * + * @param mixed $objects The item or items to add. + */ + 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); } - $operation = new ParseRelationOperation($objects, null); - $this->targetClassName = $operation->_getTargetClass(); - $this->parent->_performOperation($this->key, $operation); - } - /** - * Removes a ParseObject or an array of ParseObjects from this relation. - * - * @param mixed $objects The item or items to remove. - */ - public function remove($objects) - { - if (!is_array($objects)) { - $objects = [$objects]; + /** + * Removes a ParseObject or an array of ParseObjects from this relation. + * + * @param mixed $objects The item or items to remove. + */ + 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); } - $operation = new ParseRelationOperation(null, $objects); - $this->targetClassName = $operation->_getTargetClass(); - $this->parent->_performOperation($this->key, $operation); - } - /** - * Returns the target classname for the relation. - * - * @return string - */ - public function getTargetClass() - { - return $this->targetClassName; - } + /** + * Returns the target classname for the relation. + * + * @return string + */ + public function getTargetClass() + { + return $this->targetClassName; + } - /** - * Set the target classname for the relation. - * - * @param $className - */ - public function setTargetClass($className) - { - $this->targetClassName = $className; - } + /** + * Set the target classname for the relation. + * + * @param $className + */ + public function setTargetClass($className) + { + $this->targetClassName = $className; + } - /** - * Set the parent object for the relation. - * - * @param $parent - */ - public function setParent($parent) { - $this->parent = $parent; - } + /** + * Set the parent object for the relation. + * + * @param $parent + */ + public function setParent($parent) { + $this->parent = $parent; + } - /** - * Gets a query that can be used to query the objects in this relation. - * - * @return ParseQuery That restricts the results to objects in this relations. - */ - public function getQuery() - { - $query = new ParseQuery($this->targetClassName); - $query->relatedTo('object', $this->parent->_toPointer()); - $query->relatedTo('key', $this->key); - return $query; - } + /** + * Gets a query that can be used to query the objects in this relation. + * + * @return ParseQuery That restricts the results to objects in this relations. + */ + public function getQuery() + { + $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..3b6ac04d 100644 --- a/src/Parse/ParseRole.php +++ b/src/Parse/ParseRole.php @@ -7,101 +7,101 @@ /** * ParseRole - Representation of an access Role. * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ class ParseRole extends ParseObject { - public static $parseClassName = "_Role"; + public static $parseClassName = "_Role"; - /** - * Create a ParseRole object with a given name and ACL. - * - * @param string $name - * @param ParseACL $acl - * - * @return ParseRole - */ - public static function createRole($name, ParseACL $acl) - { - $role = ParseObject::create(static::$parseClassName); - $role->setName($name); - $role->setACL($acl); - return $role; - } - - /** - * Returns the role name. - * - * @return string - */ - public function getName() - { - return $this->get("name"); - } - - /** - * Sets the role name. - * - * @param string $name The role name - * - * @return null - */ - public function setName($name) - { - if ($this->getObjectId()) { - throw new ParseException( - "A role's name can only be set before it has been saved." - ); + /** + * Create a ParseRole object with a given name and ACL. + * + * @param string $name + * @param ParseACL $acl + * + * @return ParseRole + */ + public static function createRole($name, ParseACL $acl) + { + $role = ParseObject::create(static::$parseClassName); + $role->setName($name); + $role->setACL($acl); + return $role; } - if (!is_string($name)) { - throw new ParseException( - "A role's name must be a string." - ); + + /** + * Returns the role name. + * + * @return string + */ + public function getName() + { + return $this->get("name"); } - return $this->set("name", $name); - } - /** - * Gets the ParseRelation for the ParseUsers which are direct children of - * this role. These users are granted any privileges that this role - * has been granted. - * - * @return ParseRelation - */ - public function getUsers() - { - return $this->getRelation("users"); - } + /** + * Sets the role name. + * + * @param string $name The role name + * + * @return null + */ + public function setName($name) + { + 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( + "A role's name must be a string." + ); + } + return $this->set("name", $name); + } - /** - * Gets the ParseRelation for the ParseRoles which are direct children of - * this role. These roles' users are granted any privileges that this role - * has been granted. - * - * @return ParseRelation - */ - public function getRoles() - { - return $this->getRelation("roles"); - } + /** + * Gets the ParseRelation for the ParseUsers which are direct children of + * this role. These users are granted any privileges that this role + * has been granted. + * + * @return ParseRelation + */ + public function getUsers() + { + return $this->getRelation("users"); + } - public function save($useMasterKey = false) - { - if (!$this->getACL()) { - throw new ParseException( - "Roles must have an ACL." - ); + /** + * Gets the ParseRelation for the ParseRoles which are direct children of + * this role. These roles' users are granted any privileges that this role + * has been granted. + * + * @return ParseRelation + */ + public function getRoles() + { + return $this->getRelation("roles"); } - if (!$this->getName() || !is_string($this->getName())) { - throw new ParseException( - "Roles must have a name." - ); + + 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( + "Roles must have a name." + ); + } + return parent::save($useMasterKey); } - return parent::save($useMasterKey); - } -} \ No newline at end of file +} diff --git a/src/Parse/ParseSession.php b/src/Parse/ParseSession.php index 2c93f8c2..4e586a8a 100644 --- a/src/Parse/ParseSession.php +++ b/src/Parse/ParseSession.php @@ -8,83 +8,83 @@ /** * ParseSession - Representation of an expiring user session. * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ class ParseSession extends ParseObject { - public static $parseClassName = "_Session"; + public static $parseClassName = "_Session"; - private $_sessionToken = null; + private $_sessionToken = null; - /** - * Returns the session token string. - * - * @return string - */ - public function getSessionToken() - { - return $this->_sessionToken; - } + /** + * Returns the session token string. + * + * @return string + */ + public function getSessionToken() + { + return $this->_sessionToken; + } - /** - * Retrieves the Session object for the currently logged in user. - * - * @param boolean $useMasterKey If the Master Key should be used to override security. - * - * @return ParseSession - */ - 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; - } + /** + * Retrieves the Session object for the currently logged in user. + * + * @param boolean $useMasterKey If the Master Key should be used to override security. + * + * @return ParseSession + */ + 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; + } - /** - * Determines whether the current session token is revocable. - * This method is useful for migrating an existing app to use - * revocable sessions. - * - * @return boolean - */ - public static function isCurrentSessionRevocable() - { - $user = ParseUser::getCurrentUser(); - if ($user) { - return self::_isRevocable($user->getSessionToken()); + /** + * Determines whether the current session token is revocable. + * This method is useful for migrating an existing app to use + * revocable sessions. + * + * @return boolean + */ + public static function isCurrentSessionRevocable() + { + $user = ParseUser::getCurrentUser(); + if ($user) { + return self::_isRevocable($user->getSessionToken()); + } } - } - /** - * Determines whether a session token is revocable. - * - * @param string $token The session token to check - * - * @return boolean - */ - public static function _isRevocable($token) - { - return strpos($token, "r:") === 0; - } + /** + * Determines whether a session token is revocable. + * + * @param string $token The session token to check + * + * @return boolean + */ + public static function _isRevocable($token) + { + return strpos($token, "r:") === 0; + } - /** - * After a save, perform Session object specific logic. - * - * @return null - */ - private function handleSaveResult() - { - if (isset($this->serverData['sessionToken'])) { - $this->_sessionToken = $this->serverData['sessionToken']; - unset($this->serverData['sessionToken']); + /** + * After a save, perform Session object specific logic. + * + * @return null + */ + private function handleSaveResult() + { + if (isset($this->serverData['sessionToken'])) { + $this->_sessionToken = $this->serverData['sessionToken']; + unset($this->serverData['sessionToken']); + } + $this->rebuildEstimatedData(); } - $this->rebuildEstimatedData(); - } -} \ No newline at end of file +} diff --git a/src/Parse/ParseSessionStorage.php b/src/Parse/ParseSessionStorage.php index 2d38ee11..9c95fa35 100644 --- a/src/Parse/ParseSessionStorage.php +++ b/src/Parse/ParseSessionStorage.php @@ -5,66 +5,66 @@ /** * ParseSessionStorage - Uses PHP session support for persistent storage. * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ class ParseSessionStorage implements ParseStorageInterface { - /** - * @var string Parse will store its values in a specific key. - */ - private $storageKey = 'parseData'; + /** + * @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( - 'PHP session_start() must be called first.' - ); + 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] = array(); + } } - 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 null; } - return null; - } - public function clear() - { - $_SESSION[$this->storageKey] = array(); - } + public function clear() + { + $_SESSION[$this->storageKey] = array(); + } - public function save() - { - // No action required. PHP handles persistence for $_SESSION. - return; - } + public function save() + { + // No action required. PHP handles persistence for $_SESSION. + return; + } - public function getKeys() - { - return array_keys($_SESSION[$this->storageKey]); - } + public function getKeys() + { + return array_keys($_SESSION[$this->storageKey]); + } - public function getAll() - { - return $_SESSION[$this->storageKey]; - } + public function getAll() + { + return $_SESSION[$this->storageKey]; + } -} \ No newline at end of file +} diff --git a/src/Parse/ParseStorageInterface.php b/src/Parse/ParseStorageInterface.php index c3700048..8b33b869 100644 --- a/src/Parse/ParseStorageInterface.php +++ b/src/Parse/ParseStorageInterface.php @@ -5,68 +5,68 @@ /** * ParseStorageInterface - Specifies an interface for implementing persistence. * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ interface ParseStorageInterface { - /** - * Sets a key-value pair in storage. - * - * @param string $key The key to set - * @param mixed $value The value to set - * - * @return null - */ - public function set($key, $value); + /** + * Sets a key-value pair in storage. + * + * @param string $key The key to set + * @param mixed $value The value to set + * + * @return null + */ + public function set($key, $value); - /** - * Remove a key from storage. - * - * @param string $key The key to remove. - * - * @return null - */ - public function remove($key); + /** + * Remove a key from storage. + * + * @param string $key The key to remove. + * + * @return null + */ + public function remove($key); - /** - * Gets the value for a key from storage. - * - * @param string $key The key to get the value for - * - * @return mixed - */ - public function get($key); + /** + * Gets the value for a key from storage. + * + * @param string $key The key to get the value for + * + * @return mixed + */ + public function get($key); - /** - * Clear all the values in storage. - * - * @return null - */ - public function clear(); + /** + * Clear all the values in storage. + * + * @return null + */ + public function clear(); - /** - * Save the data, if necessary. This would be a no-op when using the - * $_SESSION implementation, but could be used for saving to file or - * database as an action instead of on every set. - * - * @return null - */ - public function save(); + /** + * Save the data, if necessary. This would be a no-op when using the + * $_SESSION implementation, but could be used for saving to file or + * database as an action instead of on every set. + * + * @return null + */ + public function save(); - /** - * Get all keys in storage. - * - * @return array - */ - public function getKeys(); + /** + * Get all keys in storage. + * + * @return array + */ + public function getKeys(); - /** - * Get all key-value pairs from storage. - * - * @return array - */ - public function getAll(); + /** + * Get all key-value pairs from storage. + * + * @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..94a7cdd2 100644 --- a/src/Parse/ParseUser.php +++ b/src/Parse/ParseUser.php @@ -5,312 +5,312 @@ /** * ParseUser - Representation of a user object stored on Parse. * - * @package Parse - * @author Fosco Marotto + * @package Parse + * @author Fosco Marotto */ class ParseUser extends ParseObject { - public static $parseClassName = "_User"; + public static $parseClassName = "_User"; - /** - * @var ParseUser The currently logged-in user. - */ - private static $currentUser = null; + /** + * @var ParseUser The currently logged-in user. + */ + private static $currentUser = null; - /** - * @var string The sessionToken for an authenticated user. - */ - protected $_sessionToken = null; + /** + * @var string The sessionToken for an authenticated user. + */ + protected $_sessionToken = null; - /** - * Returns the username. - * - * @return string|null - */ - public function getUsername() - { - return $this->get("username"); - } - - /** - * Sets the username for the ParseUser. - * - * @param string $username The username - * - * @return null - */ - public function setUsername($username) - { - return $this->set("username", $username); - } - - /** - * Sets the password for the ParseUser. - * - * @param string $password The password - * - * @return null - */ - public function setPassword($password) - { - return $this->set("password", $password); - } - - /** - * Returns the email address, if set, for the ParseUser. - * - * @return string|null - */ - public function getEmail() - { - return $this->get("email"); - } - - /** - * Sets the email address for the ParseUser. - * - * @param string $email The email address - * - * @return null - */ - public function setEmail($email) - { - return $this->set("email", $email); - } - - /** - * Checks whether this user has been authenticated. - * - * @return boolean - */ - public function isAuthenticated() - { - 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(); - */ - 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( - "Cannot sign up user with an empty password." - ); + /** + * Returns the username. + * + * @return string|null + */ + public function getUsername() + { + return $this->get("username"); } - if ($this->getObjectId()) { - throw new ParseException( - "Cannot sign up an already existing user." - ); + + /** + * Sets the username for the ParseUser. + * + * @param string $username The username + * + * @return null + */ + public function setUsername($username) + { + return $this->set("username", $username); } - parent::save(); - $this->handleSaveResult(true); - } - /** - * Logs in a and returns a valid ParseUser, or throws if invalid. - * - * @param string $username - * @param string $password - * - * @return ParseUser - * - * @throws ParseException - */ - public static function logIn($username, $password) - { - if (!$username) { - throw new ParseException("Cannot log in user with an empty name"); + /** + * Sets the password for the ParseUser. + * + * @param string $password The password + * + * @return null + */ + public function setPassword($password) + { + return $this->set("password", $password); } - if (!$password) { - throw new ParseException( - "Cannot log in user with an empty password." - ); + + /** + * Returns the email address, if set, for the ParseUser. + * + * @return string|null + */ + public function getEmail() + { + return $this->get("email"); } - $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; - } - /** - * Logs in a user with a session token. Calls the /users/me route and if - * valid, creates and returns the current user. - * - * @param string $sessionToken - * - * @return ParseUser - */ - 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; - } + /** + * Sets the email address for the ParseUser. + * + * @param string $email The email address + * + * @return null + */ + public function setEmail($email) + { + return $this->set("email", $email); + } - /** - * 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 - * - * @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. - } - static::$currentUser = null; + /** + * Checks whether this user has been authenticated. + * + * @return boolean + */ + public function isAuthenticated() + { + return $this->_sessionToken !== null; } - ParseClient::getStorage()->remove('user'); - } - /** - * After a save, perform User object specific logic. - * - * @param boolean $makeCurrent Whether to set the current user. - * - * @return null - */ - private function handleSaveResult($makeCurrent = false) - { - if (isset($this->serverData['password'])) { - unset($this->serverData['password']); + /** + * 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(); + */ + 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( + "Cannot sign up user with an empty password." + ); + } + if ($this->getObjectId()) { + throw new ParseException( + "Cannot sign up an already existing user." + ); + } + parent::save(); + $this->handleSaveResult(true); } - if (isset($this->serverData['sessionToken'])) { - $this->_sessionToken = $this->serverData['sessionToken']; - unset($this->serverData['sessionToken']); + + /** + * Logs in a and returns a valid ParseUser, or throws if invalid. + * + * @param string $username + * @param string $password + * + * @return ParseUser + * + * @throws ParseException + */ + public static function logIn($username, $password) + { + 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; } - if ($makeCurrent) { - static::$currentUser = $this; - static::saveCurrentUser(); + + /** + * Logs in a user with a session token. Calls the /users/me route and if + * valid, creates and returns the current user. + * + * @param string $sessionToken + * + * @return ParseUser + */ + 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; } - $this->rebuildEstimatedData(); - } - /** - * Retrieves the currently logged in ParseUser with a valid session, - * either from memory or the storage provider, if necessary. - * - * @return ParseUser|null - */ - public static function getCurrentUser() - { - if (static::$currentUser instanceof ParseUser) { - return static::$currentUser; + /** + * 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 + * + * @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. + } + static::$currentUser = null; + } + ParseClient::getStorage()->remove('user'); } - $storage = ParseClient::getStorage(); - $userData = $storage->get("user"); - if ($userData instanceof ParseUser) { - static::$currentUser = $userData; - return $userData; + + /** + * After a save, perform User object specific logic. + * + * @param boolean $makeCurrent Whether to set the current user. + * + * @return null + */ + 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($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 = array(); - static::$currentUser = $user; - return $user; + + /** + * Retrieves the currently logged in ParseUser with a valid session, + * either from memory or the storage provider, if necessary. + * + * @return ParseUser|null + */ + 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); + } + $user->_opSetQueue = array(); + static::$currentUser = $user; + return $user; + } + return null; } - return null; - } - /** - * Persists the current user to the storage provider. - * - * @return null - */ - protected static function saveCurrentUser() - { - $storage = ParseClient::getStorage(); - $storage->set('user', ParseUser::getCurrentUser()); - } + /** + * Persists the current user to the storage provider. + * + * @return null + */ + protected static function saveCurrentUser() + { + $storage = ParseClient::getStorage(); + $storage->set('user', ParseUser::getCurrentUser()); + } - /** - * Returns the session token, if available - * - * @return string|null - */ - public function getSessionToken() - { - return $this->_sessionToken; - } + /** + * Returns the session token, if available + * + * @return string|null + */ + public function getSessionToken() + { + return $this->_sessionToken; + } - /** - * Returns true if this user is the current user. - * - * @return boolean - */ - public function isCurrent() - { - if (ParseUser::getCurrentUser() && $this->getObjectId()) { - if ($this->getObjectId() == ParseUser::getCurrentUser()->getObjectId()) { - return true; - } + /** + * Returns true if this user is the current user. + * + * @return boolean + */ + public function isCurrent() + { + 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 - */ - public function save($useMasterKey = false) - { - if ($this->getObjectId()) { - parent::save($useMasterKey); - } else { - throw new ParseException( - "You must call signUp to create a new User." - ); + /** + * Save the current user object, unless it is not signed up. + * + * @return null + * + * @throws ParseException + */ + public function save($useMasterKey = false) + { + if ($this->getObjectId()) { + parent::save($useMasterKey); + } else { + throw new ParseException( + "You must call signUp to create a new User." + ); + } } - } - /** - * Requests a password reset email to be sent to the specified email - * address associated with the user account. This email allows the user - * to securely reset their password on the Parse site. - * - * @param string $email - * - * @return null - */ - public static function requestPasswordReset($email) - { - $json = json_encode(array('email' => $email)); - ParseClient::_request('POST', '/1/requestPasswordReset', null, $json); - } + /** + * Requests a password reset email to be sent to the specified email + * address associated with the user account. This email allows the user + * to securely reset their password on the Parse site. + * + * @param string $email + * + * @return null + */ + public static function requestPasswordReset($email) + { + $json = json_encode(array('email' => $email)); + ParseClient::_request('POST', '/1/requestPasswordReset', null, $json); + } - /** - * @ignore - */ - public static function _clearCurrentUserVariable() - { - static::$currentUser = null; - } + /** + * @ignore + */ + public static function _clearCurrentUserVariable() + { + static::$currentUser = null; + } -} \ No newline at end of file +} diff --git a/tests/IncrementTest.php b/tests/IncrementTest.php index 5f5650db..ecacd32b 100644 --- a/tests/IncrementTest.php +++ b/tests/IncrementTest.php @@ -9,227 +9,227 @@ class IncrementTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - 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( - $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, - '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, - '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', - "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, ' . - 'expected number, but got string' - ); - $objAgain->save(); - } -} \ No newline at end of file + public static function setUpBeforeClass() + { + 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( + $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, + '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, + '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', + "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, ' . + 'expected number, but got string' + ); + $objAgain->save(); + } +} diff --git a/tests/ParseACLTest.php b/tests/ParseACLTest.php index 683e77f3..a79601a6 100644 --- a/tests/ParseACLTest.php +++ b/tests/ParseACLTest.php @@ -8,384 +8,384 @@ class ParseACLTest extends \PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } - - public function setUp() - { - ParseTestHelper::clearClass("_User"); - ParseTestHelper::clearClass("Object"); - } - - public function tearDown() - { - ParseTestHelper::tearDown(); - } - - 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) { + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); } - $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 setUp() + { + ParseTestHelper::clearClass("_User"); + ParseTestHelper::clearClass("Object"); } - try { - $object->destroy(); - $this->fail('delete should fail with object not found'); - } catch (\Parse\ParseException $e) { + public function tearDown() + { + ParseTestHelper::tearDown(); } - 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 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(); - 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 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 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) { + } } - $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 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(); } - try { - $object->destroy(); - $this->fail('delete should fail with object not found'); - } 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(); - 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 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())); + } - $user = new ParseUser(); - try { - $acl->setReadAccess($user, true); - $this->fail('Exception should have thrown'); - } catch (Exception $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 { - $acl->getReadAccess($user); - $this->fail('Exception should have thrown'); - } catch (Exception $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) { + } + } - try { - $acl->setWriteAccess($user, true); - $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()); } - 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..f174ea75 100644 --- a/tests/ParseAnalyticsTest.php +++ b/tests/ParseAnalyticsTest.php @@ -7,73 +7,73 @@ class ParseAnalyticsTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } - public function tearDown() - { - ParseTestHelper::tearDown(); - } + public function tearDown() + { + ParseTestHelper::tearDown(); + } - public function assertAnalyticsValidation($event, $params, $expectedJSON) - { - // We'll test that the event encodes properly, and that the analytics call - // doesn't throw an exception. - $json = ParseAnalytics::_toSaveJSON($params ?: array()); - $this->assertEquals($expectedJSON, $json); - ParseAnalytics::track($event, $params ?: array()); - } + public function assertAnalyticsValidation($event, $params, $expectedJSON) + { + // We'll test that the event encodes properly, and that the analytics call + // doesn't throw an exception. + $json = ParseAnalytics::_toSaveJSON($params ?: array()); + $this->assertEquals($expectedJSON, $json); + ParseAnalytics::track($event, $params ?: array()); + } - 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( - 'Exception', 'A name for the custom event must be provided.' - ); - ParseAnalytics::track(''); - } + public function testFailsOnEventName1() + { + $this->setExpectedException( + 'Exception', 'A name for the custom event must be provided.' + ); + ParseAnalytics::track(''); + } - public function testFailsOnEventName2() - { - $this->setExpectedException( - 'Exception', 'A name for the custom event must be provided.' - ); - ParseAnalytics::track(' '); - } + public function testFailsOnEventName2() + { + $this->setExpectedException( + 'Exception', 'A name for the custom event must be provided.' + ); + ParseAnalytics::track(' '); + } - public function testFailsOnEventName3() - { - $this->setExpectedException( - 'Exception', 'A name for the custom event must be provided.' - ); - ParseAnalytics::track(" \n"); - } + public function testFailsOnEventName3() + { + $this->setExpectedException( + 'Exception', 'A name for the custom event must be provided.' + ); + ParseAnalytics::track(" \n"); + } - public function testTrackEventDimensions() - { - $expected = '{"dimensions":{"foo":"bar","bar":"baz"}}'; - $params = array( - 'foo' => 'bar', - 'bar' => 'baz' - ); - $this->assertAnalyticsValidation('testDimensions', $params, $expected); + 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( - 'foo' => 'bar', - 'bar' => 'baz', - 'someDate' => $date - ); - $this->assertAnalyticsValidation('testDate', $params, $expected); - } + $date = date(DATE_RFC3339); + $expected = '{"dimensions":{"foo":"bar","bar":"baz","someDate":"' . + $date . '"}}'; + $params = array( + 'foo' => 'bar', + 'bar' => 'baz', + 'someDate' => $date + ); + $this->assertAnalyticsValidation('testDate', $params, $expected); + } -} \ No newline at end of file +} diff --git a/tests/ParseBytesTest.php b/tests/ParseBytesTest.php index 00975754..08d410bc 100644 --- a/tests/ParseBytesTest.php +++ b/tests/ParseBytesTest.php @@ -8,44 +8,44 @@ class ParseBytesTest extends \PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } - - 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")); - } - -} \ No newline at end of file + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } + + 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..a48bf0a3 100644 --- a/tests/ParseCloudTest.php +++ b/tests/ParseCloudTest.php @@ -9,33 +9,33 @@ class ParseCloudTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } - - public function testFunctionsWithObjectParamsFails() - { - $obj = ParseObject::create('SomeClass'); - $obj->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); - } - -} \ No newline at end of file + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } + + public function testFunctionsWithObjectParamsFails() + { + $obj = ParseObject::create('SomeClass'); + $obj->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); + } + +} diff --git a/tests/ParseConfigTest.php b/tests/ParseConfigTest.php index b48066c2..47c2cb4c 100644 --- a/tests/ParseConfigTest.php +++ b/tests/ParseConfigTest.php @@ -5,19 +5,19 @@ require_once 'ParseTestHelper.php'; class ParseConfigMock extends ParseConfig { - public function __construct() { - $this->setConfig(["foo" => "bar", "some" => 1]); - } + 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")); - } + public function testGetConfig() + { + $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..ff10207d 100644 --- a/tests/ParseFileTest.php +++ b/tests/ParseFileTest.php @@ -8,135 +8,135 @@ class ParseFileTest extends \PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } - - 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( - strpos( - $file3->getData(), 'i am looking for myself' - ) !== false - ); - } - - 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( - 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 static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } + + 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( + strpos( + $file3->getData(), 'i am looking for myself' + ) !== false + ); + } + + 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( + 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(); + } } diff --git a/tests/ParseGeoBoxTest.php b/tests/ParseGeoBoxTest.php index cc79d1e9..8d8e6788 100644 --- a/tests/ParseGeoBoxTest.php +++ b/tests/ParseGeoBoxTest.php @@ -11,146 +11,146 @@ class ParseGeoBoxTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } - - public function setUp() - { - ParseTestHelper::clearClass("TestObject"); - } - - public function tearDown() - { - ParseTestHelper::tearDown(); - } - - 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'); - - $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); - - // 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')); - - // 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) { + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); } - $northwestOfSF = new ParseGeoPoint(37.822802, -122.526398); - $southeastOfSF = new ParseGeoPoint(37.708813, -122.373962); + public function setUp() + { + ParseTestHelper::clearClass("TestObject"); + } - // 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) { + public function tearDown() + { + ParseTestHelper::tearDown(); } - // 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) { + 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'); + + $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); + + // 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')); + + // 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) { + } + + $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) { + } + + // 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) { + } } - } - - 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'); - - $center->set('location', $centerPoint); - $center->save(); - - $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) { + + public function testGeoBoxTooLarge() + { + $centerPoint = new ParseGeoPoint(0, 0); + $center = ParseObject::create('TestObject'); + + $center->set('location', $centerPoint); + $center->save(); + + $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) { + } } - } } diff --git a/tests/ParseGeoPointTest.php b/tests/ParseGeoPointTest.php index e68f488b..578b8294 100644 --- a/tests/ParseGeoPointTest.php +++ b/tests/ParseGeoPointTest.php @@ -10,198 +10,198 @@ class ParseGeoPointTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } - - public function setUp() - { - ParseTestHelper::clearClass("TestObject"); - } - - public function tearDown() - { - ParseTestHelper::tearDown(); - } - - public function testGeoPointBase() - { - $point = new ParseGeoPoint(44.0, -11.0); - $obj = ParseObject::create('TestObject'); - $obj->set('location', $point); - - $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)); - - // Round trip encoding - $actualPoint = $results[0]->get('location'); - $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(); + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); } - $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 setUp() + { + ParseTestHelper::clearClass("TestObject"); } - // 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)); - - // all - $query = new ParseQuery('TestObject'); - $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)); - - // 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')); - - // 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')); - - } - - 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(); - - // [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(); - - // [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(); - - // test point SFO - $point = new ParseGeoPoint(37.6189722, -122.3748889); - - // Kilometers - // baseline all - $query = new ParseQuery('PlaceObject'); - $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)); - - // drop hawaii - $query = new ParseQuery('PlaceObject'); - $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')); - - // drop SF - $query = new ParseQuery('PlaceObject'); - $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)); - - // drop hawaii - $query = new ParseQuery('PlaceObject'); - $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')); - - // drop SF - $query = new ParseQuery('PlaceObject'); - $query->withinMiles('location', $point, 10.0); - $results = $query->find(); - $this->assertEquals(0, count($results)); - } + public function tearDown() + { + ParseTestHelper::tearDown(); + } + + public function testGeoPointBase() + { + $point = new ParseGeoPoint(44.0, -11.0); + $obj = ParseObject::create('TestObject'); + $obj->set('location', $point); + + $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)); + + // Round trip encoding + $actualPoint = $results[0]->get('location'); + $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'); + $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)); + + // all + $query = new ParseQuery('TestObject'); + $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)); + + // 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')); + + // 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')); + + } + + 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(); + + // [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(); + + // [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(); + + // test point SFO + $point = new ParseGeoPoint(37.6189722, -122.3748889); + + // Kilometers + // baseline all + $query = new ParseQuery('PlaceObject'); + $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)); + + // drop hawaii + $query = new ParseQuery('PlaceObject'); + $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')); + + // drop SF + $query = new ParseQuery('PlaceObject'); + $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)); + + // drop hawaii + $query = new ParseQuery('PlaceObject'); + $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')); + + // drop SF + $query = new ParseQuery('PlaceObject'); + $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..2583ebd6 100644 --- a/tests/ParseMemoryStorageTest.php +++ b/tests/ParseMemoryStorageTest.php @@ -10,62 +10,62 @@ class ParseMemoryStorageTest extends PHPUnit_Framework_TestCase { - /** - * @var ParseMemoryStorage - */ - private static $parseStorage; + /** + * @var ParseMemoryStorage + */ + private static $parseStorage; - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - self::$parseStorage = ParseClient::getStorage(); - } + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + self::$parseStorage = ParseClient::getStorage(); + } - public function tearDown() - { - ParseTestHelper::tearDown(); - self::$parseStorage->clear(); - } + public function tearDown() + { + ParseTestHelper::tearDown(); + self::$parseStorage->clear(); + } - public function testIsUsingDefaultStorage() - { - $this->assertTrue( - self::$parseStorage instanceof Parse\ParseMemoryStorage - ); - } + 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 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 testRemove() + { + self::$parseStorage->set('foo', 'bar'); + self::$parseStorage->remove('foo'); + $this->assertNull(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 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)); - } + 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)); + } -} \ No newline at end of file +} diff --git a/tests/ParseObjectTest.php b/tests/ParseObjectTest.php index 2262d5a0..999ed27f 100644 --- a/tests/ParseObjectTest.php +++ b/tests/ParseObjectTest.php @@ -10,920 +10,920 @@ class ParseObjectTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } - - public function tearDown() - { - ParseTestHelper::tearDown(); - } - - 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', - '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 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, - 'Returned object was not a ParseObject'); - $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 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 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 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 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 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 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 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(); - // 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); - } - - 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( - $endTime->getTimestamp() - $obj->getCreatedAt()->getTimestamp() - ); - $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 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 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')); - } - - 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 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')); - } - - 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 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')); - } - - 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 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')); - } - - 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 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 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 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 testNewKeyIsDirtyAfterSave() - { - $obj = ParseObject::create("TestObject"); - $obj->save(); - $obj->set('content', 'x'); - $obj->fetch(); - $this->assertTrue($obj->isKeyDirty('content')); - } - - public function testAddWithAnObject() - { - $parent = ParseObject::create("Person"); - $child = ParseObject::create("Person"); - $child->save(); - $parent->add("children", array($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 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 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 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')), - '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()); - - $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()); - - $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->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()); - - $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()); - - $obj->save(); - $this->assertFalse($child->isDirty()); - $this->assertFalse($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()); - - // check simultaneous save - $obj->save(); - $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 testEmptyObjectsAndArrays() - { - $obj = ParseObject::create('TestObject'); - $obj->setArray('arr', array()); - $obj->setAssociativeArray('obj', array()); - $saveOpArray = new SetOperation(array()); - $saveOpAssoc = new SetOperation(array(), true); - $this->assertTrue( - is_array($saveOpArray->_encode()), "Value should be array." - ); - $this->assertTrue( - is_object($saveOpAssoc->_encode()), "Value should be object." - ); - $obj->save(); - $obj->setAssociativeArray('obj', array( - '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()); - } - - 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 static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } + + public function tearDown() + { + ParseTestHelper::tearDown(); + } + + 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', + '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 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, + 'Returned object was not a ParseObject'); + $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 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 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 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 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 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 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 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(); + // 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); + } + + 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( + $endTime->getTimestamp() - $obj->getCreatedAt()->getTimestamp() + ); + $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 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 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')); + } + + 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 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')); + } + + 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 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')); + } + + 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 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')); + } + + 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 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 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 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 testNewKeyIsDirtyAfterSave() + { + $obj = ParseObject::create("TestObject"); + $obj->save(); + $obj->set('content', 'x'); + $obj->fetch(); + $this->assertTrue($obj->isKeyDirty('content')); + } + + public function testAddWithAnObject() + { + $parent = ParseObject::create("Person"); + $child = ParseObject::create("Person"); + $child->save(); + $parent->add("children", array($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 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 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 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')), + '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()); + + $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()); + + $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->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()); + + $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()); + + $obj->save(); + $this->assertFalse($child->isDirty()); + $this->assertFalse($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()); + + // check simultaneous save + $obj->save(); + $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 testEmptyObjectsAndArrays() + { + $obj = ParseObject::create('TestObject'); + $obj->setArray('arr', array()); + $obj->setAssociativeArray('obj', array()); + $saveOpArray = new SetOperation(array()); + $saveOpAssoc = new SetOperation(array(), true); + $this->assertTrue( + is_array($saveOpArray->_encode()), "Value should be array." + ); + $this->assertTrue( + is_object($saveOpAssoc->_encode()), "Value should be object." + ); + $obj->save(); + $obj->setAssociativeArray('obj', array( + '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()); + } + + 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..7520980c 100644 --- a/tests/ParsePushTest.php +++ b/tests/ParsePushTest.php @@ -9,41 +9,41 @@ class ParsePushTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } - - public function tearDown() - { - ParseTestHelper::tearDown(); - } - - public function testBasicPush() - { - ParsePush::send(array( - 'channels' => array(''), - 'data' => array('alert' => 'sample message') - )); - } - - 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(), - 'expiration_time' => new DateTime(), - 'channels' => array() - )); - } -} \ No newline at end of file + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } + + public function tearDown() + { + ParseTestHelper::tearDown(); + } + + public function testBasicPush() + { + ParsePush::send(array( + 'channels' => array(''), + 'data' => array('alert' => 'sample message') + )); + } + + 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(), + 'expiration_time' => new DateTime(), + 'channels' => array() + )); + } +} diff --git a/tests/ParseQueryTest.php b/tests/ParseQueryTest.php index 71a23e73..dd38be83 100644 --- a/tests/ParseQueryTest.php +++ b/tests/ParseQueryTest.php @@ -11,1510 +11,1510 @@ class ParseQueryTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } - - public function setUp() - { - ParseTestHelper::clearClass("TestObject"); - } - - public function tearDown() - { - ParseTestHelper::tearDown(); - } - - /** - * This function used as a helper function in test functions to save objects. - * - * @param int $numberOfObjects Number of objects you want to save. - * @param callable $callback Function which takes int as a parameter. - * and should return ParseObject. - */ - public function saveObjects($numberOfObjects, $callback) - { - $allObjects = array(); - for ($i = 0; $i < $numberOfObjects; $i++) { - $allObjects[] = $callback($i); - } - ParseObject::saveAll($allObjects); - } - - public function provideTestObjects($numberOfObjects) - { - $this->saveObjects($numberOfObjects, function ($i) { - $obj = ParseObject::create('TestObject'); - $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), - 'Did not find object.'); - $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), - '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 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, - 'LessThan function did not return correct number of objects.'); - $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, - 'LessThanOrEqualTo function did not return correct number of objects.'); - $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, - 'StartsWith function did not return correct number of objects.'); - $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, - '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, - '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, - 'StartsWith function did not return correct number of objects.'); - $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, - 'StartsWith function did not return correct number of objects.'); - $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, - '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, - 'StartsWith function did not return correct number of objects.'); - $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, - 'StartsWith function did not return correct number of objects.'); - $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, - '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, - 'GreaterThan function did not return correct number of objects.'); - $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, - 'GreaterThanOrEqualTo function did not return correct number of objects.'); - $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), - '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), - 'LessThanGreaterThan did not return correct number of objects.'); - $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) { - $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), - 'Did not find object.'); - $this->assertEquals(4, $results[0]->get("number"), - 'Did not return the correct object.'); - } - - 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), - '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 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"), - '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 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"), - '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 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) { - $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"), - 'Did not return the correct object.'); - } - - public function testNotEqualToObject() - { - ParseTestHelper::clearClass("Container"); - ParseTestHelper::clearClass("Item"); - $items = array(); - $this->saveObjects(2, function ($i) use (&$items) { - $items[] = ParseObject::create("Item"); - return $items[$i]; - }); - $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), - 'Did not return the correct object.'); - } - - 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), - 'Did not return the correct object.'); - $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) { - return ParseObject::create("TestObject"); - }); - $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, - 'Did not return correct number of objects.'); - $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) { - $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, - '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 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), - 'Did not return correct number of objects.'); - 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) { - $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), - 'Did not return correct number of objects.'); - 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) { - $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), - 'Did not return correct number of objects.'); - 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), - 'Did not return the correct object.'); - foreach ($results as $parentObj) { - $this->assertLessThanOrEqual(15, $parentObj->get("x"), - 'Did not return the correct object.'); - $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); - - $personHomeTown = ["Djibouti", "Ouagadougou", "Detroit"]; - $personName = ["Bob", "Tom", "Billy"]; - $numberOfPersonObjects = count($personHomeTown); - - $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) { - $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); - - $query = new ParseQuery("Person"); - $query->matchesKeyInQuery("hometown", "location", $subQuery); - $results = $query->find(); - - $this->assertEquals(1, count($results), - 'Did not return correct number of objects.'); - $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); - - $query = new ParseQuery("Person"); - $query->doesNotmatchKeyInQuery("hometown", "location", $subQuery); - $results = $query->find(); - - $this->assertEquals(1, count($results), - 'Did not return correct number of objects.'); - $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, - 'Did not return correct number of objects.'); - 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) { - $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), - 'Did not return correct number of objects.'); - } - - 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); - - $values = array(); - $query->each(function ($obj) use (&$values) { - $values[] = $obj->get("x"); - }, 10); - - $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], - 'Did not return the correct object.'); - } - } - - 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) { - }); - } - - 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) { - }); - } - - 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) { - }); - } - - 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), - 'Did not return correct number of objects.'); - } - - public function testContainsAllDateArrayQueries() - { - ParseTestHelper::clearClass("DateSet"); - $dates1 = array( - 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-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-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), - 'Did not return correct number of objects.'); - } - - public function testContainsAllObjectArrayQueries() - { - ParseTestHelper::clearClass("MessageSet"); - $messageList = array(); - $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]) - ); - $messageSet2->save(); - - $query = new ParseQuery("MessageSet"); - $query->containsAll("messages", array($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) { - $message = ParseObject::create("TestObject"); - if ($i > 0) { - $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), - 'Did not return correct number of objects.'); - } - - 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), - 'Did not return correct number of objects.'); - } - - 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), - 'Did not return correct number of objects.'); - } - - public function testObjectIdContainedInQueries() - { - ParseTestHelper::clearClass("BoxedNumber"); - $objects = array(); - $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(), - $objects[3]->getObjectId(), - $objects[0]->getObjectId(), - "NONSENSE"] - ); - $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"), - 'Did not return the correct object.'); - $this->assertEquals(2, $results[1]->get("number"), - 'Did not return the correct object.'); - $this->assertEquals(3, $results[2]->get("number"), - 'Did not return the correct object.'); - } - - public function testStartsWith() - { - $someAscii = "\\E' !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTU" . - "VWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'"; - $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]); - return $obj; - }); - $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 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'), - 'Did not return the correct object.'); - $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), - 'Did not return correct number of objects.'); - 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'), - '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), - 'Did not return correct number of objects.'); - 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'), - '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 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'), - '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), - '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'), - 'Did not return the correct object.'); - } - } - - public function testOrderByUpdatedAtAsc() - { - $numbers = [3, 1, 2]; - $objects = array(); - $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), - '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'), - 'Did not return the correct object.'); - } - } - - public function testOrderByUpdatedAtDesc() - { - $numbers = [3, 1, 2]; - $objects = array(); - $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), - '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'), - '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'), - 'Did not return the correct object.'); - $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'), - 'Did not return the correct object.'); - $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'), - 'Did not return the correct object.'); - $this->assertEquals(1, $result->get('bar'), - 'Did not return the correct object.'); - - } - - public function testExists() - { - $this->saveObjects(9, function ($i) { - $obj = ParseObject::create("TestObject"); - if ($i & 1) { - $obj->set('y', $i); - } else { - $obj->set('x', $i); - } - return $obj; - }); - $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) { - $obj = ParseObject::create("TestObject"); - if ($i & 1) { - $obj->set('y', $i); - } else { - $obj->set('x', $i); - } - return $obj; - }); - $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) { - $obj = ParseObject::create("TestObject"); - if ($i & 1) { - $obj->set('y', $i); - } else { - $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), - 'Did not return correct number of objects.'); - } - - public function testDoesNotExistRelation() - { - ParseTestHelper::clearClass("Item"); - $this->saveObjects(9, function ($i) { - $obj = ParseObject::create("TestObject"); - if ($i & 1) { - $obj->set('y', $i); - } else { - $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), - '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 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'), - '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'), - 'Object should be fetched.'); - $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) { - $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), - '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'), - '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), - '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), - '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), - '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) { - $parent = ParseObject::create('Parent'); - $parent->set('num', $i); - if ($i & 1) { + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } + + public function setUp() + { + ParseTestHelper::clearClass("TestObject"); + } + + public function tearDown() + { + ParseTestHelper::tearDown(); + } + + /** + * This function used as a helper function in test functions to save objects. + * + * @param int $numberOfObjects Number of objects you want to save. + * @param callable $callback Function which takes int as a parameter. + * and should return ParseObject. + */ + public function saveObjects($numberOfObjects, $callback) + { + $allObjects = array(); + for ($i = 0; $i < $numberOfObjects; $i++) { + $allObjects[] = $callback($i); + } + ParseObject::saveAll($allObjects); + } + + public function provideTestObjects($numberOfObjects) + { + $this->saveObjects($numberOfObjects, function ($i) { + $obj = ParseObject::create('TestObject'); + $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), + 'Did not find object.'); + $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), + '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 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, + 'LessThan function did not return correct number of objects.'); + $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, + 'LessThanOrEqualTo function did not return correct number of objects.'); + $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, + 'StartsWith function did not return correct number of objects.'); + $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, + '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, + '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, + 'StartsWith function did not return correct number of objects.'); + $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, + 'StartsWith function did not return correct number of objects.'); + $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, + '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, + 'StartsWith function did not return correct number of objects.'); + $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, + 'StartsWith function did not return correct number of objects.'); + $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, + '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, + 'GreaterThan function did not return correct number of objects.'); + $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, + 'GreaterThanOrEqualTo function did not return correct number of objects.'); + $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), + '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), + 'LessThanGreaterThan did not return correct number of objects.'); + $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) { + $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), + 'Did not find object.'); + $this->assertEquals(4, $results[0]->get("number"), + 'Did not return the correct object.'); + } + + 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), + '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 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"), + '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 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"), + '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 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) { + $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"), + 'Did not return the correct object.'); + } + + public function testNotEqualToObject() + { + ParseTestHelper::clearClass("Container"); + ParseTestHelper::clearClass("Item"); + $items = array(); + $this->saveObjects(2, function ($i) use (&$items) { + $items[] = ParseObject::create("Item"); + return $items[$i]; + }); + $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), + 'Did not return the correct object.'); + } + + 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), + 'Did not return the correct object.'); + $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) { + return ParseObject::create("TestObject"); + }); + $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, + 'Did not return correct number of objects.'); + $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) { + $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, + '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 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), + 'Did not return correct number of objects.'); + 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) { + $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), + 'Did not return correct number of objects.'); + 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) { + $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), + 'Did not return correct number of objects.'); + 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), + 'Did not return the correct object.'); + foreach ($results as $parentObj) { + $this->assertLessThanOrEqual(15, $parentObj->get("x"), + 'Did not return the correct object.'); + $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); + + $personHomeTown = ["Djibouti", "Ouagadougou", "Detroit"]; + $personName = ["Bob", "Tom", "Billy"]; + $numberOfPersonObjects = count($personHomeTown); + + $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) { + $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); + + $query = new ParseQuery("Person"); + $query->matchesKeyInQuery("hometown", "location", $subQuery); + $results = $query->find(); + + $this->assertEquals(1, count($results), + 'Did not return correct number of objects.'); + $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); + + $query = new ParseQuery("Person"); + $query->doesNotmatchKeyInQuery("hometown", "location", $subQuery); + $results = $query->find(); + + $this->assertEquals(1, count($results), + 'Did not return correct number of objects.'); + $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, + 'Did not return correct number of objects.'); + 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) { + $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), + 'Did not return correct number of objects.'); + } + + 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); + + $values = array(); + $query->each(function ($obj) use (&$values) { + $values[] = $obj->get("x"); + }, 10); + + $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], + 'Did not return the correct object.'); + } + } + + 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) { + }); + } + + 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) { + }); + } + + 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) { + }); + } + + 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), + 'Did not return correct number of objects.'); + } + + public function testContainsAllDateArrayQueries() + { + ParseTestHelper::clearClass("DateSet"); + $dates1 = array( + 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-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-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), + 'Did not return correct number of objects.'); + } + + public function testContainsAllObjectArrayQueries() + { + ParseTestHelper::clearClass("MessageSet"); + $messageList = array(); + $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]) + ); + $messageSet2->save(); + + $query = new ParseQuery("MessageSet"); + $query->containsAll("messages", array($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) { + $message = ParseObject::create("TestObject"); + if ($i > 0) { + $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), + 'Did not return correct number of objects.'); + } + + 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), + 'Did not return correct number of objects.'); + } + + 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), + 'Did not return correct number of objects.'); + } + + public function testObjectIdContainedInQueries() + { + ParseTestHelper::clearClass("BoxedNumber"); + $objects = array(); + $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(), + $objects[3]->getObjectId(), + $objects[0]->getObjectId(), + "NONSENSE"] + ); + $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"), + 'Did not return the correct object.'); + $this->assertEquals(2, $results[1]->get("number"), + 'Did not return the correct object.'); + $this->assertEquals(3, $results[2]->get("number"), + 'Did not return the correct object.'); + } + + public function testStartsWith() + { + $someAscii = "\\E' !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTU" . + "VWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'"; + $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]); + return $obj; + }); + $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 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'), + 'Did not return the correct object.'); + $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), + 'Did not return correct number of objects.'); + 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'), + '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), + 'Did not return correct number of objects.'); + 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'), + '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 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'), + '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), + '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'), + 'Did not return the correct object.'); + } + } + + public function testOrderByUpdatedAtAsc() + { + $numbers = [3, 1, 2]; + $objects = array(); + $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), + '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'), + 'Did not return the correct object.'); + } + } + + public function testOrderByUpdatedAtDesc() + { + $numbers = [3, 1, 2]; + $objects = array(); + $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), + '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'), + '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'), + 'Did not return the correct object.'); + $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'), + 'Did not return the correct object.'); + $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'), + 'Did not return the correct object.'); + $this->assertEquals(1, $result->get('bar'), + 'Did not return the correct object.'); + + } + + public function testExists() + { + $this->saveObjects(9, function ($i) { + $obj = ParseObject::create("TestObject"); + if ($i & 1) { + $obj->set('y', $i); + } else { + $obj->set('x', $i); + } + return $obj; + }); + $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) { + $obj = ParseObject::create("TestObject"); + if ($i & 1) { + $obj->set('y', $i); + } else { + $obj->set('x', $i); + } + return $obj; + }); + $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) { + $obj = ParseObject::create("TestObject"); + if ($i & 1) { + $obj->set('y', $i); + } else { + $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), + 'Did not return correct number of objects.'); + } + + public function testDoesNotExistRelation() + { + ParseTestHelper::clearClass("Item"); + $this->saveObjects(9, function ($i) { + $obj = ParseObject::create("TestObject"); + if ($i & 1) { + $obj->set('y', $i); + } else { + $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), + '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); - } - return $parent; - }); - - $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'), - 'Object should be fetched'); - } 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'), - 'Object should be fetched'); - $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) { - $items[] = ParseObject::create("Item"); - $items[$i]->set('x', $i); - return $items[$i]; - }); - $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), - 'Did not return the correct object.'); - } - - 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), - 'Did not return correct number of objects.'); - } - - public function provideTimeTestObjects() - { - ParseTestHelper::clearClass("TimeObject"); - $items = array(); - $this->saveObjects(3, function ($i) use (&$items) { - $timeObject = ParseObject::create('TimeObject'); - $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), - 'Did not return correct number of objects.'); - $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), - '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 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 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); - } + $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'), + 'Object should be fetched.'); + $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'), + 'Object should be fetched.'); + $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) { + $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), + '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'), + '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), + '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), + '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), + '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) { + $parent = ParseObject::create('Parent'); + $parent->set('num', $i); + if ($i & 1) { + $parent->set('child', $child); + } + return $parent; + }); + + $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'), + 'Object should be fetched'); + } 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'), + 'Object should be fetched'); + $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) { + $items[] = ParseObject::create("Item"); + $items[$i]->set('x', $i); + return $items[$i]; + }); + $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), + 'Did not return the correct object.'); + } + + 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), + 'Did not return correct number of objects.'); + } + + public function provideTimeTestObjects() + { + ParseTestHelper::clearClass("TimeObject"); + $items = array(); + $this->saveObjects(3, function ($i) use (&$items) { + $timeObject = ParseObject::create('TimeObject'); + $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), + 'Did not return correct number of objects.'); + $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), + '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 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 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..2e93c0cc 100644 --- a/tests/ParseRelationTest.php +++ b/tests/ParseRelationTest.php @@ -5,131 +5,131 @@ require_once 'ParseTestHelper.php'; class ParseRelationTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } - - public function tearDown() - { - ParseTestHelper::tearDown(); - } - - /** - * This function used as a helper function in test functions to save objects. - * - * @param int $numberOfObjects Number of objects you want to save. - * @param callable $callback Function which takes int as a parameter. - * and should return ParseObject. - */ - public function saveObjects($numberOfObjects, $callback) - { - $allObjects = array(); - for ($i = 0; $i < $numberOfObjects; $i++) { - $allObjects[] = $callback($i); + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } + + public function tearDown() + { + ParseTestHelper::tearDown(); + } + + /** + * This function used as a helper function in test functions to save objects. + * + * @param int $numberOfObjects Number of objects you want to save. + * @param callable $callback Function which takes int as a parameter. + * and should return ParseObject. + */ + public function saveObjects($numberOfObjects, $callback) + { + $allObjects = array(); + for ($i = 0; $i < $numberOfObjects; $i++) { + $allObjects[] = $callback($i); + } + ParseObject::saveAll($allObjects); + } + + public function testParseRelations() + { + $children = array(); + $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([ + $children[5], + $children[6], + $children[7], + $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()); + + } + + public function testQueriesOnRelationFields() + { + $children = array(); + $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([ + $children[0], + $children[1], + $children[2] + ]); + $parent->save(); + $parent2 = ParseObject::create('ParentObject'); + $parent2->set('x', 3); + $relation2 = $parent2->getRelation('children'); + $relation2->add([ + $children[4], + $children[5], + $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()); + } - ParseObject::saveAll($allObjects); - } - - public function testParseRelations() - { - $children = array(); - $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([ - $children[5], - $children[6], - $children[7], - $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()); - - } - - public function testQueriesOnRelationFields() - { - $children = array(); - $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([ - $children[0], - $children[1], - $children[2] - ]); - $parent->save(); - $parent2 = ParseObject::create('ParentObject'); - $parent2->set('x', 3); - $relation2 = $parent2->getRelation('children'); - $relation2->add([ - $children[4], - $children[5], - $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()); - - } } diff --git a/tests/ParseRoleTest.php b/tests/ParseRoleTest.php index 26326343..7decdcb2 100644 --- a/tests/ParseRoleTest.php +++ b/tests/ParseRoleTest.php @@ -10,208 +10,208 @@ class ParseRoleTest extends \PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } - - public function setUp() - { - ParseTestHelper::clearClass("_User"); - ParseTestHelper::clearClass("_Role"); - ParseTestHelper::clearClass("Things"); - } - - public function tearDown() - { - ParseTestHelper::tearDown(); - } - - public function testCreateRole() - { - $role = ParseRole::createRole("Admin", $this->aclPublic()); - $role->save(); - $this->assertNotNull($role->getObjectId(), "Role should have objectId."); - } - - public function testRoleWithoutACLFails() - { - $role = new ParseRole(); - $role->setName("Admin"); - $this->setExpectedException('Parse\ParseException', 'ACL'); - $role->save(); - } - - 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 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 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 testRoleNameUnique() - { - $role = ParseRole::createRole("Admin", $this->aclPublic()); - $role->save(); - $role2 = ParseRole::createRole("Admin", $this->aclPublic()); - $this->setExpectedException('Parse\ParseException', 'duplicate'); - $role2->save(); - } - - 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 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 - */ - - public function aclPrivateTo($someone) - { - $acl = new ParseACL(); - $acl->setReadAccess($someone, true); - $acl->setWriteAccess($someone, true); - return $acl; - } - - public function aclPublic() - { - $acl = new ParseACL(); - $acl->setPublicReadAccess(true); - $acl->setPublicWriteAccess(true); - return $acl; - } - - public function createUser($username) - { - $user = new ParseUser(); - $user->setUsername($username); - $user->setPassword($username); - return $user; - } - - 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(); - - $eden['apple'] = ParseObject::create("Things"); - $eden['apple']->set("name", "apple"); - $eden['apple']->set("ACL", $this->aclPrivateTo($eden['humans'])); - - $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; - - } + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } + + public function setUp() + { + ParseTestHelper::clearClass("_User"); + ParseTestHelper::clearClass("_Role"); + ParseTestHelper::clearClass("Things"); + } + + public function tearDown() + { + ParseTestHelper::tearDown(); + } + + public function testCreateRole() + { + $role = ParseRole::createRole("Admin", $this->aclPublic()); + $role->save(); + $this->assertNotNull($role->getObjectId(), "Role should have objectId."); + } + + public function testRoleWithoutACLFails() + { + $role = new ParseRole(); + $role->setName("Admin"); + $this->setExpectedException('Parse\ParseException', 'ACL'); + $role->save(); + } + + 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 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 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 testRoleNameUnique() + { + $role = ParseRole::createRole("Admin", $this->aclPublic()); + $role->save(); + $role2 = ParseRole::createRole("Admin", $this->aclPublic()); + $this->setExpectedException('Parse\ParseException', 'duplicate'); + $role2->save(); + } + + 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 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 + */ + + public function aclPrivateTo($someone) + { + $acl = new ParseACL(); + $acl->setReadAccess($someone, true); + $acl->setWriteAccess($someone, true); + return $acl; + } + + public function aclPublic() + { + $acl = new ParseACL(); + $acl->setPublicReadAccess(true); + $acl->setPublicWriteAccess(true); + return $acl; + } + + public function createUser($username) + { + $user = new ParseUser(); + $user->setUsername($username); + $user->setPassword($username); + return $user; + } + + 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(); + + $eden['apple'] = ParseObject::create("Things"); + $eden['apple']->set("name", "apple"); + $eden['apple']->set("ACL", $this->aclPrivateTo($eden['humans'])); + + $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..91d9535e 100644 --- a/tests/ParseSessionStorageTest.php +++ b/tests/ParseSessionStorageTest.php @@ -10,67 +10,67 @@ class ParseSessionStorageTest extends PHPUnit_Framework_TestCase { - /** - * @var ParseSessionStorage - */ - private static $parseStorage; + /** + * @var ParseSessionStorage + */ + private static $parseStorage; - public static function setUpBeforeClass() - { - ParseClient::_unsetStorage(); - session_start(); - ParseTestHelper::setUp(); - self::$parseStorage = ParseClient::getStorage(); - } + public static function setUpBeforeClass() + { + ParseClient::_unsetStorage(); + session_start(); + ParseTestHelper::setUp(); + self::$parseStorage = ParseClient::getStorage(); + } - public function tearDown() - { - ParseTestHelper::tearDown(); - self::$parseStorage->clear(); - } + public function tearDown() + { + ParseTestHelper::tearDown(); + self::$parseStorage->clear(); + } - public static function tearDownAfterClass() - { - session_destroy(); - } + public static function tearDownAfterClass() + { + session_destroy(); + } - public function testIsUsingParseSession() - { - $this->assertTrue(self::$parseStorage instanceof Parse\ParseSessionStorage); - } + public function testIsUsingParseSession() + { + $this->assertTrue(self::$parseStorage instanceof Parse\ParseSessionStorage); + } - public function testSetAndGet() - { - self::$parseStorage->set('foo', 'bar'); - $this->assertEquals('bar', self::$parseStorage->get('foo')); - } + 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 testRemove() + { + self::$parseStorage->set('foo', 'bar'); + self::$parseStorage->remove('foo'); + $this->assertNull(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 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)); - } + 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..04dfb3ac 100644 --- a/tests/ParseSessionTest.php +++ b/tests/ParseSessionTest.php @@ -11,51 +11,51 @@ class ParseSessionTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - ParseTestHelper::clearClass(ParseUser::$parseClassName); - ParseTestHelper::clearClass(ParseSession::$parseClassName); - } - - 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); - } - -} \ No newline at end of file + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + ParseTestHelper::clearClass(ParseUser::$parseClassName); + ParseTestHelper::clearClass(ParseSession::$parseClassName); + } + + 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..5adf8df5 100644 --- a/tests/ParseSubclassTest.php +++ b/tests/ParseSubclassTest.php @@ -10,28 +10,28 @@ class ParseSubclassTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } - - 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')); - } - -} \ No newline at end of file + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } + + 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..554bb8da 100644 --- a/tests/ParseTestHelper.php +++ b/tests/ParseTestHelper.php @@ -7,29 +7,29 @@ class ParseTestHelper { - public static function setUp() - { - ini_set('error_reporting', E_ALL); - ini_set('display_errors', 1); - date_default_timezone_set('UTC'); - ParseClient::initialize( - 'app-id-here', - 'rest-api-key-here', - 'master-key-here' - ); - } + public static function setUp() + { + ini_set('error_reporting', E_ALL); + ini_set('display_errors', 1); + date_default_timezone_set('UTC'); + ParseClient::initialize( + 'app-id-here', + 'rest-api-key-here', + 'master-key-here' + ); + } - public static function tearDown() - { + public static function tearDown() + { - } + } - public static function clearClass($class) - { - $query = new ParseQuery($class); - $query->each(function(ParseObject $obj) { - $obj->destroy(true); - }, true); - } + 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..d7340ca2 100644 --- a/tests/ParseUserTest.php +++ b/tests/ParseUserTest.php @@ -10,421 +10,421 @@ class ParseUserTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - ParseTestHelper::clearClass(ParseUser::$parseClassName); - } - - public function tearDown() - { - ParseTestHelper::tearDown(); - ParseUser::logOut(); - ParseTestHelper::clearClass(ParseUser::$parseClassName); - } - - public static function tearDownAfterClass() - { - ParseUser::_unregisterSubclass(); - } - - 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 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 testBecome() - { - $user = new ParseUser(); - $user->setUsername("asdf"); - $user->setPassword("zxcv"); - $user->signUp(); - $this->assertEquals(ParseUser::getCurrentUser(), $user); - - $sessionToken = $user->getSessionToken(); - - $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'); - } - - 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(); - - $this->assertEquals(ParseUser::getCurrentUser(), $otherUser); - - $this->setExpectedException( - 'Parse\ParseException', 'UserCannotBeAlteredWithoutSession' - ); - $user->setUsername('changed'); - $user->save(); - } - - 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(); - - $this->assertEquals(ParseUser::getCurrentUser(), $otherUser); - - $this->setExpectedException( - 'Parse\ParseException', 'UserCannotBeAlteredWithoutSession' - ); - $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( - 'Parse\ParseAggregateException', 'Errors during batch save.' - ); - ParseObject::saveAll(array($item1, $item2, $user)); - } - - 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()); - - $currentAgain = ParseUser::getCurrentUser(); - $this->assertEquals($current, $currentAgain); - - 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 testPasswordReset() - { - $user = new ParseUser(); - $user->setUsername('asdf'); - $user->setPassword('zxcv'); - $user->set('email', 'asdf@example.com'); - $user->signUp(); - - ParseUser::requestPasswordReset('asdf@example.com'); - } - - public function testPasswordResetFails() - { - $this->setExpectedException( - 'Parse\ParseException', 'no user found with email' - ); - 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 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 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; + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + ParseTestHelper::clearClass(ParseUser::$parseClassName); } - $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; + + public function tearDown() + { + ParseTestHelper::tearDown(); + ParseUser::logOut(); + ParseTestHelper::clearClass(ParseUser::$parseClassName); + } + + public static function tearDownAfterClass() + { + ParseUser::_unregisterSubclass(); + } + + 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 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 testBecome() + { + $user = new ParseUser(); + $user->setUsername("asdf"); + $user->setPassword("zxcv"); + $user->signUp(); + $this->assertEquals(ParseUser::getCurrentUser(), $user); + + $sessionToken = $user->getSessionToken(); + + $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'); + } + + 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(); + + $this->assertEquals(ParseUser::getCurrentUser(), $otherUser); + + $this->setExpectedException( + 'Parse\ParseException', 'UserCannotBeAlteredWithoutSession' + ); + $user->setUsername('changed'); + $user->save(); + } + + 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(); + + $this->assertEquals(ParseUser::getCurrentUser(), $otherUser); + + $this->setExpectedException( + 'Parse\ParseException', 'UserCannotBeAlteredWithoutSession' + ); + $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( + 'Parse\ParseAggregateException', 'Errors during batch save.' + ); + ParseObject::saveAll(array($item1, $item2, $user)); + } + + 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()); + + $currentAgain = ParseUser::getCurrentUser(); + $this->assertEquals($current, $currentAgain); + + 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 testPasswordReset() + { + $user = new ParseUser(); + $user->setUsername('asdf'); + $user->setPassword('zxcv'); + $user->set('email', 'asdf@example.com'); + $user->signUp(); + + ParseUser::requestPasswordReset('asdf@example.com'); + } + + public function testPasswordResetFails() + { + $this->setExpectedException( + 'Parse\ParseException', 'no user found with email' + ); + 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 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 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; + } + + $inList = array($userList[0], $userList[3], $userList[3]); + $query = new ParseQuery("TestObject"); + $query->containedIn('from', $inList); + $results = $query->find(); + + $this->assertEquals(3, count($results)); + } + + public function testSavingUserThrows() + { + $user = new ParseUser(); + $user->setUsername('asdf'); + $user->setPassword('zxcv'); + $this->setExpectedException('Parse\ParseException', 'You must call signUp'); + $user->save(); + } + + 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 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 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 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 testUserWithMissingUsername() + { + $user = new ParseUser(); + $user->setPassword('test'); + $this->setExpectedException('Parse\ParseException', 'empty name'); + $user->signUp(); + } + + 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')); } - $inList = array($userList[0], $userList[3], $userList[3]); - $query = new ParseQuery("TestObject"); - $query->containedIn('from', $inList); - $results = $query->find(); - - $this->assertEquals(3, count($results)); - } - - public function testSavingUserThrows() - { - $user = new ParseUser(); - $user->setUsername('asdf'); - $user->setPassword('zxcv'); - $this->setExpectedException('Parse\ParseException', 'You must call signUp'); - $user->save(); - } - - 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 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 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 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 testUserWithMissingUsername() - { - $user = new ParseUser(); - $user->setPassword('test'); - $this->setExpectedException('Parse\ParseException', 'empty name'); - $user->signUp(); - } - - 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')); - } - -} \ No newline at end of file +} diff --git a/tests/bootstrap.php b/tests/bootstrap.php index b2634320..182cd572 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -1,5 +1,6 @@ \ No newline at end of file diff --git a/tests/cloudcode/cloud/main.js b/tests/cloudcode/cloud/main.js index d0cddd46..67dc5370 100644 --- a/tests/cloudcode/cloud/main.js +++ b/tests/cloudcode/cloud/main.js @@ -1,43 +1,43 @@ Parse.Cloud.define("bar", function(request, response) { - if (request.params.key2 === "value1") { - response.success('Foo'); - } else { - response.error("bad stuff happened"); - } + if (request.params.key2 === "value1") { + response.success('Foo'); + } else { + response.error("bad stuff happened"); + } }); Parse.Cloud.define("foo", function(request, response) { - var key1 = request.params.key1; - var key2 = request.params.key2; - if (key1 === "value1" && key2 - && key2.length === 3 && key2[0] === 1 - && key2[1] === 2 && key2[2] === 3) { - result = { - object: { - __type: 'Object', - className: 'Foo', - objectId: '1', - x: 2, - relation: { - __type: 'Object', - className: 'Bar', - objectId: '2', - x: 3 - } - }, - array:[ - { - __type: 'Object', - className: 'Bar', - objectId: '10', - x: 2 - } - ] - }; - response.success(result); - } else if (key1 === "value1") { - response.success({a: 2}); - } else { - response.error('invalid!'); - } + var key1 = request.params.key1; + var key2 = request.params.key2; + if (key1 === "value1" && key2 + && key2.length === 3 && key2[0] === 1 + && key2[1] === 2 && key2[2] === 3) { + result = { + object: { + __type: 'Object', + className: 'Foo', + objectId: '1', + x: 2, + relation: { + __type: 'Object', + className: 'Bar', + objectId: '2', + x: 3 + } + }, + array:[ + { + __type: 'Object', + className: 'Bar', + objectId: '10', + x: 2 + } + ] + }; + response.success(result); + } else if (key1 === "value1") { + response.success({a: 2}); + } else { + response.error('invalid!'); + } }); 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 + From 87e9d1cb6003781e52202a6b250e4fc4756a6fbb Mon Sep 17 00:00:00 2001 From: Graham Campbell Date: Tue, 31 Mar 2015 23:37:36 +0100 Subject: [PATCH 4/4] Applied StyleCI fixes --- autoload.php | 15 +- src/Parse/Internal/AddOperation.php | 27 +- src/Parse/Internal/AddUniqueOperation.php | 24 +- src/Parse/Internal/DeleteOperation.php | 13 +- src/Parse/Internal/Encodable.php | 3 - src/Parse/Internal/FieldOperation.php | 9 +- src/Parse/Internal/IncrementOperation.php | 18 +- src/Parse/Internal/ParseRelationOperation.php | 89 ++-- src/Parse/Internal/RemoveOperation.php | 26 +- src/Parse/Internal/SetOperation.php | 15 +- src/Parse/ParseACL.php | 109 ++--- src/Parse/ParseAggregateException.php | 13 +- src/Parse/ParseAnalytics.php | 23 +- src/Parse/ParseBytes.php | 15 +- src/Parse/ParseClient.php | 82 ++-- src/Parse/ParseCloud.php | 16 +- src/Parse/ParseConfig.php | 28 +- src/Parse/ParseException.php | 11 +- src/Parse/ParseFile.php | 420 +++++++++--------- src/Parse/ParseGeoPoint.php | 14 +- src/Parse/ParseInstallation.php | 5 - src/Parse/ParseMemoryStorage.php | 10 +- src/Parse/ParseObject.php | 287 ++++++------ src/Parse/ParsePush.php | 27 +- src/Parse/ParseQuery.php | 218 +++++---- src/Parse/ParseRelation.php | 17 +- src/Parse/ParseRole.php | 12 +- src/Parse/ParseSession.php | 8 +- src/Parse/ParseSessionStorage.php | 10 +- src/Parse/ParseStorageInterface.php | 7 +- src/Parse/ParseUser.php | 31 +- tests/IncrementTest.php | 5 +- tests/ParseACLTest.php | 17 +- tests/ParseAnalyticsTest.php | 26 +- tests/ParseBytesTest.php | 7 +- tests/ParseCloudTest.php | 12 +- tests/ParseConfigTest.php | 8 +- tests/ParseFileTest.php | 5 +- tests/ParseGeoBoxTest.php | 17 +- tests/ParseGeoPointTest.php | 5 +- tests/ParseMemoryStorageTest.php | 4 - tests/ParseObjectTest.php | 37 +- tests/ParsePushTest.php | 30 +- tests/ParseQueryTest.php | 111 +++-- tests/ParseRelationTest.php | 28 +- tests/ParseRoleTest.php | 27 +- tests/ParseSessionStorageTest.php | 4 - tests/ParseSessionTest.php | 6 +- tests/ParseSubclassTest.php | 4 - tests/ParseTestHelper.php | 7 +- tests/ParseUserTest.php | 15 +- tests/bootstrap.php | 2 +- 52 files changed, 1006 insertions(+), 973 deletions(-) diff --git a/autoload.php b/autoload.php index 190bd15a..85a84430 100755 --- a/autoload.php +++ b/autoload.php @@ -15,31 +15,30 @@ * https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader-examples.md */ -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 ) { + $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'; // if the file exists, require it - if ( file_exists( $file ) ) { + if (file_exists($file)) { require $file; } }); diff --git a/src/Parse/Internal/AddOperation.php b/src/Parse/Internal/AddOperation.php index 96c565f5..219f3832 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. */ @@ -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,8 +58,9 @@ public function _encode() * * @param FieldOperation $previous Previous operation. * - * @return FieldOperation Merged operation. * @throws ParseException + * + * @return FieldOperation Merged operation. */ public function _mergeWithPrevious($previous) { @@ -73,14 +72,16 @@ public function _mergeWithPrevious($previous) } if ($previous instanceof SetOperation) { $oldList = $previous->getValue(); + return new SetOperation( - array_merge((array)$oldList, (array)$this->objects) + array_merge((array) $oldList, (array) $this->objects) ); } if ($previous instanceof AddOperation) { $oldList = $previous->getValue(); + return new SetOperation( - array_merge((array)$oldList, (array)$this->objects) + array_merge((array) $oldList, (array) $this->objects) ); } throw new ParseException( @@ -91,9 +92,9 @@ public function _mergeWithPrevious($previous) /** * Applies current operation, returns resulting value. * - * @param mixed $oldValue Value prior to this operation. - * @param mixed $obj Value being applied. - * @param string $key Key this operation affects. + * @param mixed $oldValue Value prior to this operation. + * @param mixed $obj Value being applied. + * @param string $key Key this operation affects. * * @return array */ @@ -102,7 +103,7 @@ public function _apply($oldValue, $obj, $key) if (!$oldValue) { return $this->objects; } - return array_merge((array)$oldValue, (array)$this->objects); - } + return array_merge((array) $oldValue, (array) $this->objects); + } } diff --git a/src/Parse/Internal/AddUniqueOperation.php b/src/Parse/Internal/AddUniqueOperation.php index 66f68f85..76733391 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. */ @@ -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,8 +58,9 @@ public function _encode() * * @param FieldOperation $previous Previous Operation. * - * @return FieldOperation Merged Operation. * @throws ParseException + * + * @return FieldOperation Merged Operation. */ public function _mergeWithPrevious($previous) { @@ -74,11 +73,13 @@ public function _mergeWithPrevious($previous) 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( @@ -89,9 +90,9 @@ public function _mergeWithPrevious($previous) /** * Apply the current operation and return the result. * - * @param mixed $oldValue Value prior to this operation. - * @param array $obj Value being applied. - * @param string $key Key this operation affects. + * @param mixed $oldValue Value prior to this operation. + * @param array $obj Value being applied. + * @param string $key Key this operation affects. * * @return array */ @@ -101,14 +102,14 @@ public function _apply($oldValue, $obj, $key) return $this->objects; } if (!is_array($oldValue)) { - $oldValue = (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)) { + } elseif (is_object($object)) { if (!in_array($object, $oldValue, true)) { $oldValue[] = $object; } @@ -118,6 +119,7 @@ public function _apply($oldValue, $obj, $key) } } } + return $oldValue; } @@ -130,7 +132,7 @@ private function isParseObjectInArray($parseObject, $oldValue) } } } + return false; } - } diff --git a/src/Parse/Internal/DeleteOperation.php b/src/Parse/Internal/DeleteOperation.php index 7aaee5f0..a703c80e 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,21 +16,21 @@ class DeleteOperation implements FieldOperation */ public function _encode() { - return array('__op' => 'Delete'); + return ['__op' => 'Delete']; } /** * Applies the current operation and returns the result. * - * @param mixed $oldValue Value prior to this operation. - * @param mixed $object Unused for this operation type. - * @param string $key Key to remove from the target object. + * @param mixed $oldValue Value prior to this operation. + * @param mixed $object Unused for this operation type. + * @param string $key Key to remove from the target object. * * @return null */ public function _apply($oldValue, $object, $key) { - return null; + return; } /** @@ -46,5 +44,4 @@ public function _mergeWithPrevious($previous) { return $this; } - } diff --git a/src/Parse/Internal/Encodable.php b/src/Parse/Internal/Encodable.php index 0a6aa6a9..a965c966 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(); - } diff --git a/src/Parse/Internal/FieldOperation.php b/src/Parse/Internal/FieldOperation.php index 13bf1112..01535072 100755 --- a/src/Parse/Internal/FieldOperation.php +++ b/src/Parse/Internal/FieldOperation.php @@ -5,18 +5,16 @@ /** * 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. * - * @param mixed $oldValue Value prior to this operation. - * @param mixed $object Value for this operation. - * @param string $key Key to perform this operation on. + * @param mixed $oldValue Value prior to this operation. + * @param mixed $object Value for this operation. + * @param string $key Key to perform this operation on. * * @return mixed Result of the operation. */ @@ -31,5 +29,4 @@ public function _apply($oldValue, $object, $key); * @return FieldOperation Merged operation result. */ public function _mergeWithPrevious($previous); - } diff --git a/src/Parse/Internal/IncrementOperation.php b/src/Parse/Internal/IncrementOperation.php index 41818049..73726c2a 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. */ @@ -45,24 +43,26 @@ public function getValue() */ public function _encode() { - return array('__op' => 'Increment', 'amount' => $this->value); + return ['__op' => 'Increment', 'amount' => $this->value]; } /** * Apply the current operation and return the result. * - * @param mixed $oldValue Value prior to this operation. - * @param mixed $object Value for this operation. - * @param string $key Key to set Value on. + * @param mixed $oldValue Value prior to this operation. + * @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; } @@ -72,8 +72,9 @@ public function _apply($oldValue, $object, $key) * * @param FieldOperation $previous Previous Operation. * - * @return FieldOperation * @throws ParseException + * + * @return FieldOperation */ public function _mergeWithPrevious($previous) { @@ -95,5 +96,4 @@ public function _mergeWithPrevious($previous) 'Operation is invalid after previous operation.' ); } - } diff --git a/src/Parse/Internal/ParseRelationOperation.php b/src/Parse/Internal/ParseRelationOperation.php index 6a1c80e8..a3e18a0b 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,22 +20,22 @@ 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->relationsToAdd['null'] = []; + $this->relationsToRemove['null'] = []; + if ($objectsToAdd !== null) { $this->checkAndAssignClassName($objectsToAdd); $this->addObjects($objectsToAdd, $this->relationsToAdd); } - if ( $objectsToRemove !== null) { + if ($objectsToRemove !== null) { $this->checkAndAssignClassName($objectsToRemove); $this->addObjects($objectsToRemove, $this->relationsToRemove); } @@ -69,7 +68,7 @@ private function checkAndAssignClassName($objects) * Adds an object or array of objects to the array, replacing any * existing instance of the same object. * - * @param array $objects Array of ParseObjects to add. + * @param array $objects Array of ParseObjects to add. * @param array $container Array to contain new ParseObjects. */ private function addObjects($objects, &$container) @@ -89,7 +88,7 @@ private function addObjects($objects, &$container) /** * Removes an object (and any duplicate instances of that object) from the array. * - * @param array $objects Array of ParseObjects to remove. + * @param array $objects Array of ParseObjects to remove. * @param array $container Array to remove from it ParseObjects. */ private function removeObjects($objects, &$container) @@ -97,7 +96,7 @@ private function removeObjects($objects, &$container) if (!is_array($objects)) { $objects = [$objects]; } - $nullObjects = array(); + $nullObjects = []; foreach ($objects as $object) { if ($object->getObjectId() == null) { $nullObjects[] = $object; @@ -110,29 +109,29 @@ private function removeObjects($objects, &$container) } } - /** * Applies the current operation and returns the result. * - * @param mixed $oldValue Value prior to this operation. - * @param mixed $object Value for this operation. - * @param string $key Key to perform this operation on. - * - * @return mixed Result of the operation. + * @param mixed $oldValue Value prior to this operation. + * @param mixed $object Value for this operation. + * @param string $key Key to perform this operation on. * * @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) { + } 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."); @@ -145,9 +144,9 @@ 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) { @@ -159,8 +158,8 @@ public function _mergeWithPrevious($previous) && $previous->targetClassName != $this->targetClassName ) { throw new \Exception('Related object object must be of class ' - . $this->targetClassName . ', but ' . $previous->targetClassName - . ' was passed in.'); + .$this->targetClassName.', but '.$previous->targetClassName + .' was passed in.'); } $newRelationToAdd = self::convertToOneDimensionalArray( $this->relationsToAdd); @@ -191,38 +190,39 @@ public function _mergeWithPrevious($previous) /** * Returns an associative array encoding of the current operation. * - * @return mixed - * * @throws \Exception + * + * @return mixed */ public function _encode() { - $addRelation = array(); - $removeRelation = array(); + $addRelation = []; + $removeRelation = []; if (!empty($this->relationsToAdd)) { - $addRelation = array( - '__op' => 'AddRelation', + $addRelation = [ + '__op' => 'AddRelation', 'objects' => ParseClient::_encode( self::convertToOneDimensionalArray($this->relationsToAdd), true - ) - ); + ), + ]; } if (!empty($this->relationsToRemove)) { - $removeRelation = array( - '__op' => 'RemoveRelation', + $removeRelation = [ + '__op' => 'RemoveRelation', 'objects' => ParseClient::_encode( self::convertToOneDimensionalArray($this->relationsToRemove), true - ) - ); + ), + ]; } if (!empty($addRelation) && !empty($removeRelation)) { - return array( + return [ '__op' => 'Batch', - 'ops' => [$addRelation, $removeRelation] - ); + 'ops' => [$addRelation, $removeRelation], + ]; } + return empty($addRelation) ? $removeRelation : $addRelation; } @@ -267,7 +267,7 @@ public static function removeElementsFromArray($elements, &$array) */ public static function convertToOneDimensionalArray($array) { - $newArray = array(); + $newArray = []; if (is_array($array)) { foreach ($array as $value) { $newArray = array_merge($newArray, self::convertToOneDimensionalArray($value)); @@ -275,6 +275,7 @@ public static function convertToOneDimensionalArray($array) } else { $newArray[] = $array; } + return $newArray; } } diff --git a/src/Parse/Internal/RemoveOperation.php b/src/Parse/Internal/RemoveOperation.php index 16cbac6b..f38afab9 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. */ @@ -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,8 +60,9 @@ public function _encode() * * @param FieldOperation $previous Previous operation. * - * @return FieldOperation Merged operation. * @throws ParseException + * + * @return FieldOperation Merged operation. */ public function _mergeWithPrevious($previous) { @@ -80,8 +79,9 @@ public function _mergeWithPrevious($previous) } if ($previous instanceof RemoveOperation) { $oldList = $previous->getValue(); + return new RemoveOperation( - array_merge((array)$oldList, (array)$this->objects) + array_merge((array) $oldList, (array) $this->objects) ); } throw new ParseException( @@ -92,18 +92,18 @@ public function _mergeWithPrevious($previous) /** * Applies current operation, returns resulting value. * - * @param mixed $oldValue Value prior to this operation. - * @param mixed $obj Value being applied. - * @param string $key Key this operation affects. + * @param mixed $oldValue Value prior to this operation. + * @param mixed $obj Value being applied. + * @param string $key Key this operation affects. * * @return array */ public function _apply($oldValue, $obj, $key) { if (empty($oldValue)) { - return array(); + return []; } - $newValue = array(); + $newValue = []; foreach ($oldValue as $oldObject) { foreach ($this->objects as $newObject) { if ($oldObject instanceof ParseObject) { @@ -121,7 +121,7 @@ public function _apply($oldValue, $obj, $key) } } } + return $newValue; } - } diff --git a/src/Parse/Internal/SetOperation.php b/src/Parse/Internal/SetOperation.php index 0f31fc55..1c6c7243 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. */ @@ -26,8 +24,8 @@ class SetOperation implements FieldOperation /** * Create a SetOperation with a value. * - * @param mixed $value Value to set for this operation. - * @param bool $isAssociativeArray If the value should be forced as object. + * @param mixed $value Value to set for this operation. + * @param bool $isAssociativeArray If the value should be forced as object. */ public function __construct($value, $isAssociativeArray = false) { @@ -57,17 +55,19 @@ public function _encode() foreach ($this->value as $key => $value) { $object->$key = ParseClient::_encode($value, true); } + return ParseClient::_encode($object, true); } + return ParseClient::_encode($this->value, true); } /** * Apply the current operation and return the result. * - * @param mixed $oldValue Value prior to this operation. - * @param mixed $object Value for this operation. - * @param string $key Key to set this value on. + * @param mixed $oldValue Value prior to this operation. + * @param mixed $object Value for this operation. + * @param string $key Key to set this value on. * * @return mixed */ @@ -88,5 +88,4 @@ public function _mergeWithPrevious($previous) { return $this; } - } diff --git a/src/Parse/ParseACL.php b/src/Parse/ParseACL.php index 7f849c90..dfe933b4 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 - */ @@ -58,6 +57,7 @@ public static function createACLWithUser($user) $acl = new ParseACL(); $acl->setUserReadAccess($user, true); $acl->setUserWriteAccess($user, true); + return $acl; } @@ -66,8 +66,9 @@ public static function createACLWithUser($user) * * @param array $data represents permissions. * - * @return ParseACL * @throws \Exception + * + * @return ParseACL * @ignore */ public static function _createACLFromJSON($data) @@ -89,6 +90,7 @@ public static function _createACLFromJSON($data) $acl->setAccess($accessType, $id, $value); } } + return $acl; } @@ -104,7 +106,7 @@ public function _isShared() } /** - * Set shared for ParseACL + * Set shared for ParseACL. * * @param bool $shared * @ignore @@ -122,6 +124,7 @@ public function _encode() if (empty($this->permissionsById)) { return new \stdClass(); } + return $this->permissionsById; } @@ -130,8 +133,8 @@ public function _encode() * the user has permission for accessing or not. * * @param string $accessType Access name. - * @param string $userId User id. - * @param bool $allowed If user allowed to access or not. + * @param string $userId User id. + * @param bool $allowed If user allowed to access or not. * * @throws ParseException */ @@ -141,7 +144,7 @@ private function setAccess($accessType, $userId, $allowed) $userId = $userId->getObjectId(); } if ($userId instanceof ParseRole) { - $userId = "role:" . $userId->getName(); + $userId = "role:".$userId->getName(); } if (!is_string($userId)) { throw new ParseException( @@ -152,7 +155,7 @@ private function setAccess($accessType, $userId, $allowed) if (!$allowed) { return; } - $this->permissionsById[$userId] = array(); + $this->permissionsById[$userId] = []; } if ($allowed) { $this->permissionsById[$userId][$accessType] = true; @@ -168,7 +171,7 @@ private function setAccess($accessType, $userId, $allowed) * Get if the given userId has a permission for the given access type or not. * * @param string $accessType Access name. - * @param string $userId User id. + * @param string $userId User id. * * @return bool */ @@ -180,14 +183,15 @@ private function getAccess($accessType, $userId) if (!isset($this->permissionsById[$userId][$accessType])) { return false; } + return $this->permissionsById[$userId][$accessType]; } /** * Set whether the given user id is allowed to read this object. * - * @param string $userId User id. - * @param bool $allowed If user allowed to read or not. + * @param string $userId User id. + * @param bool $allowed If user allowed to read or not. * * @throws \Exception */ @@ -207,23 +211,24 @@ 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); } /** * Set whether the given user id is allowed to write this object. * - * @param string $userId User id. - * @param bool $allowed If user allowed to write or not. + * @param string $userId User id. + * @param bool $allowed If user allowed to write or not. * * @throws \Exception */ @@ -243,19 +248,19 @@ 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); } - /** * Set whether the public is allowed to read this object. * @@ -300,7 +305,7 @@ public function getPublicWriteAccess() * Set whether the given user is allowed to read this object. * * @param ParseUser $user - * @param bool $allowed + * @param bool $allowed * * @throws \Exception */ @@ -320,15 +325,16 @@ 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()); } @@ -336,7 +342,7 @@ public function getUserReadAccess($user) * Set whether the given user is allowed to write this object. * * @param ParseUser $user - * @param bool $allowed + * @param bool $allowed * * @throws \Exception */ @@ -356,15 +362,16 @@ 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()); } @@ -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. + * @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); } /** @@ -414,11 +420,11 @@ public function getRoleWriteAccessWithName($roleName) * are allowed to write this object. * * @param string $roleName The name of the role. - * @param bool $allowed Whether the given role can write this object. + * @param bool $allowed Whether the given role can write this object. */ public function setRoleWriteAccessWithName($roleName, $allowed) { - $this->setWriteAccess('role:' . $roleName, $allowed); + $this->setWriteAccess('role:'.$roleName, $allowed); } /** @@ -449,6 +455,7 @@ private static function validateRoleState($role) public function getRoleReadAccess($role) { $this->validateRoleState($role); + return $this->getRoleReadAccessWithName($role->getName()); } @@ -457,8 +464,8 @@ public function getRoleReadAccess($role) * object. The role must already be saved on the server and its data must * have been fetched in order to use this method. * - * @param ParseRole $role The role to assign access. - * @param bool $allowed Whether the given role can read this object. + * @param ParseRole $role The role to assign access. + * @param bool $allowed Whether the given role can read this object. */ public function setRoleReadAccess($role, $allowed) { @@ -479,6 +486,7 @@ public function setRoleReadAccess($role, $allowed) public function getRoleWriteAccess($role) { $this->validateRoleState($role); + return $this->getRoleWriteAccessWithName($role->getName()); } @@ -487,8 +495,8 @@ public function getRoleWriteAccess($role) * object. The role must already be saved on the server and its data must * have been fetched in order to use this method. * - * @param ParseRole $role The role to assign access. - * @param bool $allowed Whether the given role can read this object. + * @param ParseRole $role The role to assign access. + * @param bool $allowed Whether the given role can read this object. */ public function setRoleWriteAccess($role, $allowed) { @@ -500,18 +508,18 @@ public function setRoleWriteAccess($role, $allowed) * Sets a default ACL that will be applied to all ParseObjects when they * are created. * - * @param ParseACL $acl The ACL to use as a template for all ParseObjects - * created after setDefaultACL has been called. This - * value will be copied and used as a template for the - * creation of new ACLs, so changes to the instance - * after setDefaultACL() has been called will not be - * reflected in new ParseObjects. - * @param bool $withAccessForCurrentUser If true, the ParseACL that is applied to - * newly-created ParseObjects will provide read - * and write access to the ParseUser#getCurrentUser() - * at the time of creation. If false, the provided - * ACL will be used without modification. If acl is - * null, this value is ignored. + * @param ParseACL $acl The ACL to use as a template for all ParseObjects + * created after setDefaultACL has been called. This + * value will be copied and used as a template for the + * creation of new ACLs, so changes to the instance + * after setDefaultACL() has been called will not be + * reflected in new ParseObjects. + * @param bool $withAccessForCurrentUser If true, the ParseACL that is applied to + * newly-created ParseObjects will provide read + * and write access to the ParseUser#getCurrentUser() + * at the time of creation. If false, the provided + * ACL will be used without modification. If acl is + * null, this value is ignored. */ public static function setDefaultACL($acl, $withAccessForCurrentUser) { @@ -546,9 +554,10 @@ public static function _getDefaultACL() self::$defaultACLWithCurrentUser->setUserWriteAccess(ParseUser::getCurrentUser(), true); self::$lastCurrentUser = clone ParseUser::getCurrentUser(); } + return self::$defaultACLWithCurrentUser; } + return self::$defaultACL; } - } diff --git a/src/Parse/ParseAggregateException.php b/src/Parse/ParseAggregateException.php index 6e3f3303..24b0748b 100644 --- a/src/Parse/ParseAggregateException.php +++ b/src/Parse/ParseAggregateException.php @@ -3,24 +3,22 @@ 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 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; @@ -35,5 +33,4 @@ public function getErrors() { return $this->errors; } - } diff --git a/src/Parse/ParseAnalytics.php b/src/Parse/ParseAnalytics.php index de936d7d..f6a8bff0 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 @@ -35,13 +33,14 @@ class ParseAnalytics * * There is a default limit of 4 dimensions per event tracked. * - * @param string $name The name of the custom event - * @param array $dimensions The dictionary of segment information + * @param string $name The name of the custom event + * @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) { @@ -52,9 +51,10 @@ public static function track($name, $dimensions = array()) throw new Exception('Dimensions expected string keys and values.'); } } + return ParseClient::_request( 'POST', - '/1/events/' . $name, + '/1/events/'.$name, null, static::_toSaveJSON($dimensions) ); @@ -66,11 +66,10 @@ public static function track($name, $dimensions = array()) public static function _toSaveJSON($data) { return json_encode( - array( - 'dimensions' => $data - ), + [ + 'dimensions' => $data, + ], JSON_FORCE_OBJECT ); } - } diff --git a/src/Parse/ParseBytes.php b/src/Parse/ParseBytes.php index 2463a80b..4799fbd6 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 */ @@ -27,11 +25,12 @@ public static function createFromByteArray(array $byteArray) { $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 * @@ -41,6 +40,7 @@ public static function createFromBase64Data($base64Data) { $bytes = new ParseBytes(); $bytes->setBase64Data($base64Data); + return $bytes; } @@ -56,7 +56,7 @@ private function setByteArray(array $byteArray) } /** - * Encode to associative array representation + * Encode to associative array representation. * * @return array * @ignore @@ -67,9 +67,10 @@ public function _encode() foreach ($this->byteArray as $byte) { $data .= chr($byte); } - return array( + + return [ '__type' => 'Bytes', - 'base64' => base64_encode($data) - ); + 'base64' => base64_encode($data), + ]; } } diff --git a/src/Parse/ParseClient.php b/src/Parse/ParseClient.php index 5d692f8f..716bd2fd 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'; @@ -58,10 +58,10 @@ final class ParseClient /** * Parse\Client::initialize, must be called before using Parse features. * - * @param string $app_id Parse Application ID - * @param string $rest_key Parse REST API Key - * @param string $master_key Parse Master Key - * @param boolean $enableCurlExceptions Enable or disable Parse curl exceptions + * @param string $app_id Parse Application ID + * @param string $rest_key Parse REST API Key + * @param string $master_key Parse Master Key + * @param boolean $enableCurlExceptions Enable or disable Parse curl exceptions * * @return null */ @@ -87,20 +87,21 @@ public static function initialize($app_id, $rest_key, $master_key, $enableCurlEx /** * ParseClient::_encode, internal method for encoding object values. * - * @param mixed $value Value to encode - * @param bool $allowParseObjects Allow nested objects + * @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) - ); + return [ + '__type' => 'Date', 'iso' => self::getProperDateFormat($value), + ]; } if ($value instanceof \stdClass) { @@ -111,6 +112,7 @@ public static function _encode($value, $allowParseObjects) if (!$allowParseObjects) { throw new \Exception('ParseObjects not allowed here.'); } + return $value->_toPointer(); } @@ -125,6 +127,7 @@ public static function _encode($value, $allowParseObjects) if (!is_scalar($value) && $value !== null) { throw new \Exception('Invalid type encountered.'); } + return $value; } @@ -141,14 +144,14 @@ public static function _decode($data) // 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; + $tmp = (array) $data; if (!empty($tmp)) { return self::_decode(get_object_vars($data)); } } if (!$data && !is_array($data)) { - return null; + return; } if (is_array($data)) { @@ -177,6 +180,7 @@ public static function _decode($data) if ($typeString === 'Object') { $output = ParseObject::create($data['className']); $output->_mergeAfterFetch($data); + return $output; } @@ -184,12 +188,12 @@ public static function _decode($data) return $data; } - $newDict = array(); + $newDict = []; foreach ($data as $key => $value) { $newDict[$key] = static::_decode($value); } - return $newDict; + return $newDict; } return $data; @@ -198,32 +202,34 @@ public static function _decode($data) /** * ParseClient::_encodeArray, internal method for encoding arrays. * - * @param array $value Array to encode. - * @param bool $allowParseObjects Allow nested objects. + * @param array $value Array to encode. + * @param bool $allowParseObjects Allow nested objects. * * @return array Encoded results. * @ignore */ public static function _encodeArray($value, $allowParseObjects) { - $output = array(); + $output = []; foreach ($value as $key => $item) { $output[$key] = self::_encode($item, $allowParseObjects); } + return $output; } /** * Parse\Client::_request, internal method for communicating with Parse. * - * @param string $method HTTP Method for this request. - * @param string $relativeUrl REST API Path. - * @param null $sessionToken Session Token. - * @param null $data Data to provide with the request. - * @param bool $useMasterKey Whether to use the Master Key. + * @param string $method HTTP Method for this request. + * @param string $relativeUrl REST API Path. + * @param null $sessionToken Session Token. + * @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, @@ -235,9 +241,9 @@ public static function _request($method, $relativeUrl, $sessionToken = null, self::assertParseInitialized(); $headers = self::_getRequestHeaders($sessionToken, $useMasterKey); - $url = self::HOST_NAME . $relativeUrl; + $url = self::HOST_NAME.$relativeUrl; if ($method === 'GET' && !empty($data)) { - $url .= '?' . http_build_query($data); + $url .= '?'.http_build_query($data); } $rest = curl_init(); curl_setopt($rest, CURLOPT_URL, $url); @@ -277,8 +283,8 @@ public static function _request($method, $relativeUrl, $sessionToken = null, isset($decoded['code']) ? $decoded['code'] : 0 ); } - return $decoded; + return $decoded; } /** @@ -337,25 +343,26 @@ 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); + $headers = ['X-Parse-Application-Id: '.self::$applicationId, + 'X-Parse-Client-Version: '.self::VERSION_STRING, ]; if ($sessionToken) { - $headers[] = 'X-Parse-Session-Token: ' . $sessionToken; + $headers[] = 'X-Parse-Session-Token: '.$sessionToken; } if ($useMasterKey) { - $headers[] = 'X-Parse-Master-Key: ' . self::$masterKey; + $headers[] = 'X-Parse-Master-Key: '.self::$masterKey; } else { - $headers[] = 'X-Parse-REST-API-Key: ' . self::$restKey; + $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; } @@ -373,7 +380,8 @@ public static function getProperDateFormat($value) { $dateFormatString = 'Y-m-d\TH:i:s.u'; $date = date_format($value, $dateFormatString); - $date = substr($date, 0, -3) . 'Z'; + $date = substr($date, 0, -3).'Z'; + return $date; } @@ -391,6 +399,7 @@ public static function getLocalPushDateFormat($value) { $dateFormatString = 'Y-m-d\TH:i:s'; $date = date_format($value, $dateFormatString); + return $date; } @@ -405,5 +414,4 @@ public static function enableRevocableSessions() { self::$forceRevocableSession = true; } - } diff --git a/src/Parse/ParseCloud.php b/src/Parse/ParseCloud.php index 1bed03ce..b0db92ba 100644 --- a/src/Parse/ParseCloud.php +++ b/src/Parse/ParseCloud.php @@ -3,24 +3,22 @@ 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 + * @param string $name Cloud function name + * @param array $data Parameters to pass * @param boolean $useMasterKey Whether to use the Master Key * * @return mixed */ - public static function run($name, $data = array(), $useMasterKey = false) + public static function run($name, $data = [], $useMasterKey = false) { $sessionToken = null; if (ParseUser::getCurrentUser()) { @@ -28,12 +26,12 @@ public static function run($name, $data = array(), $useMasterKey = false) } $response = ParseClient::_request( 'POST', - '/1/functions/' . $name, + '/1/functions/'.$name, $sessionToken, json_encode(ParseClient::_encode($data, null, false)), $useMasterKey ); + return ParseClient::_decode($response['result']); } - } diff --git a/src/Parse/ParseConfig.php b/src/Parse/ParseConfig.php index ce81908d..43858032 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() { + public function __construct() + { $result = ParseClient::_request("GET", "/1/config"); $this->setConfig($result['params']); } - public function get($key) { + public function get($key) + { if (isset($this->currentConfig[$key])) { return $this->currentConfig[$key]; } - return null; + + return; } - public function escape($key) { + public function escape($key) + { if (isset($this->currentConfig[$key])) { return htmlentities($this->currentConfig[$key]); } - return null; + + return; } - protected function setConfig($config) { + protected function setConfig($config) + { $this->currentConfig = $config; } - } diff --git a/src/Parse/ParseException.php b/src/Parse/ParseException.php index 7b307c13..b4e7a9a3 100644 --- a/src/Parse/ParseException.php +++ b/src/Parse/ParseException.php @@ -3,19 +3,17 @@ 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. + * @param string $message Message for the Exception. + * @param int $code Error code. * @param \Exception $previous Previous Exception. */ public function __construct($message, $code = 0, @@ -23,5 +21,4 @@ public function __construct($message, $code = 0, { parent::__construct($message, $code, $previous); } - } diff --git a/src/Parse/ParseFile.php b/src/Parse/ParseFile.php index a75c4f22..62485275 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,9 +29,9 @@ 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() { @@ -44,6 +42,7 @@ public function getData() throw new ParseException("Cannot retrieve data for unsaved ParseFile."); } $this->data = $this->download(); + return $this->data; } @@ -69,7 +68,7 @@ public function getName() } /** - * Send a REST request to delete the ParseFile + * Send a REST request to delete the ParseFile. * * @throws ParseException */ @@ -80,7 +79,7 @@ public function delete() } $headers = ParseClient::_getRequestHeaders(null, true); - $url = ParseClient::HOST_NAME . '/1/files/' . $this->getName(); + $url = ParseClient::HOST_NAME.'/1/files/'.$this->getName(); $rest = curl_init(); curl_setopt($rest, CURLOPT_URL, $url); curl_setopt($rest, CURLOPT_CUSTOMREQUEST, "DELETE"); @@ -106,10 +105,10 @@ public function getMimeType() /** * 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 + * @param mixed $contents The file contents + * @param string $name The file name on Parse, can be used to detect mimeType * @param string $mimeType Optional, The mime-type to use when saving the file * * @return ParseFile @@ -120,16 +119,17 @@ public static function createFromData($contents, $name, $mimeType = null) $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 + * @param string $path Path to local file + * @param string $name Filename to use on Parse, can be used to detect mimeType * @param string $mimeType Optional, The mime-type to use when saving the file * * @return ParseFile @@ -137,6 +137,7 @@ 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); } @@ -154,6 +155,7 @@ public static function _createFromServer($name, $url) $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, + ]; } /** @@ -184,6 +186,7 @@ public function save() $this->url = $response['url']; $this->name = $response['name']; } + return true; } @@ -194,12 +197,12 @@ private function upload() $mimeType = $this->mimeType ?: $this->getMimeTypeForExtension($extension); $headers = ParseClient::_getRequestHeaders(null, false); - $url = ParseClient::HOST_NAME . '/1/files/' . $this->getName(); + $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; + $headers[] = 'Content-Type: '.$mimeType; curl_setopt($rest, CURLOPT_POST, 1); curl_setopt($rest, CURLOPT_POSTFIELDS, $this->getData()); curl_setopt($rest, CURLOPT_HTTPHEADER, $headers); @@ -219,8 +222,8 @@ private function upload() isset($decoded['code']) ? $decoded['code'] : 0 ); } - return $decoded; + return $decoded; } private function download() @@ -240,206 +243,207 @@ private function download() $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", + $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'; } - } diff --git a/src/Parse/ParseGeoPoint.php b/src/Parse/ParseGeoPoint.php index 32b8552b..25941000 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. */ @@ -85,17 +83,17 @@ public function setLongitude($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 29a20b0d..70793c44 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"; - } diff --git a/src/Parse/ParseMemoryStorage.php b/src/Parse/ParseMemoryStorage.php index f66e16a9..fb0881c3 100644 --- a/src/Parse/ParseMemoryStorage.php +++ b/src/Parse/ParseMemoryStorage.php @@ -6,16 +6,14 @@ * 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(); + private $storage = []; public function set($key, $value) { @@ -32,12 +30,13 @@ public function get($key) if (isset($this->storage[$key])) { return $this->storage[$key]; } - return null; + + return; } public function clear() { - $this->storage = array(); + $this->storage = []; } public function save() @@ -55,5 +54,4 @@ public function getAll() { return $this->storage; } - } diff --git a/src/Parse/ParseObject.php b/src/Parse/ParseObject.php index 957bcb66..3d4e7fdd 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,17 +59,17 @@ 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. * * @param string $className Class Name for data on Parse. - * @param mixed $objectId Object Id for Existing object. - * @param bool $isPointer + * @param mixed $objectId Object Id for Existing object. + * @param bool $isPointer * * @throws Exception */ @@ -81,7 +78,7 @@ public function __construct($className = null, $objectId = null, { if (empty(self::$registeredSubclasses)) { throw new Exception( - 'You must initialize the ParseClient using ParseClient::initialize ' . + 'You must initialize the ParseClient using ParseClient::initialize '. 'and your Parse API keys before you can begin working with Objects.' ); } @@ -92,17 +89,17 @@ public function __construct($className = null, $objectId = null, } 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 ' . + '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(); + $this->serverData = []; + $this->operationSet = []; + $this->estimatedData = []; + $this->dataAvailability = []; if ($objectId || $isPointer) { $this->objectId = $objectId; $this->hasBeenFetched = false; @@ -122,11 +119,12 @@ private static function getSubclass() /** * Setter to catch property calls and protect certain fields. * - * @param string $key Key to set a value on. - * @param mixed $value Value to assign. + * @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) @@ -160,9 +158,9 @@ public function __get($key) * * @param string $key Key to retrieve from the estimatedData array. * - * @return mixed - * * @throws \Exception + * + * @return mixed */ public function get($key) { @@ -173,11 +171,12 @@ public function get($key) if (isset($this->estimatedData[$key])) { return $this->estimatedData[$key]; } - return null; + + return; } /** - * Check if the object has a given key + * Check if the object has a given key. * * @param string $key Key to check * @@ -193,6 +192,7 @@ public function has($key) * added/updated/removed and not saved yet. * * @param string $key + * * @return bool */ public function isKeyDirty($key) @@ -236,17 +236,19 @@ private function hasDirtyChildren() } } }); + return $result; } /** * Validate and set a value for an object key. * - * @param string $key Key to set a value for on the object. - * @param mixed $value Value to set on the key. + * @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) { @@ -264,11 +266,12 @@ public function set($key, $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. + * @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) { @@ -286,11 +289,12 @@ public function setArray($key, $value) /** * Set an associative 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. + * @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) { @@ -308,11 +312,12 @@ public function setAssociativeArray($key, $value) /** * Remove a value from an array for an object key. * - * @param string $key Key to remove the value from on the object. - * @param mixed $value Value to remove from the array. + * @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) { @@ -332,7 +337,7 @@ public function remove($key, $value) */ public function revert() { - $this->operationSet = array(); + $this->operationSet = []; $this->rebuildEstimatedData(); } @@ -352,7 +357,7 @@ public function clear() /** * Perform an operation on an object property. * - * @param string $key Key to perform an operation upon. + * @param string $key Key to perform an operation upon. * @param FieldOperation $operation Operation to perform. * * @return null @@ -367,7 +372,7 @@ public function _performOperation($key, FieldOperation $operation) $newValue = $operation->_apply($oldValue, $this, $key); if ($newValue !== null) { $this->estimatedData[$key] = $newValue; - } else if (isset($this->estimatedData[$key])) { + } elseif (isset($this->estimatedData[$key])) { unset($this->estimatedData[$key]); } @@ -424,7 +429,6 @@ public function isDataAvailable() private function _isDataAvailable($key) { return $this->isDataAvailable() || isset($this->dataAvailability[$key]); - } /** @@ -442,8 +446,8 @@ public function getUpdatedAt() * Optionally creates a pointer object if the objectId is provided. * * @param string $className Class Name for data on Parse. - * @param string $objectId Unique identifier for existing object. - * @param bool $isPointer If the object is a pointer. + * @param string $objectId Unique identifier for existing object. + * @param bool $isPointer If the object is a pointer. * * @return Object */ @@ -474,7 +478,7 @@ public function fetch($useMasterKey = false) } $response = ParseClient::_request( 'GET', - '/1/classes/' . $this->className . '/' . $this->objectId, + '/1/classes/'.$this->className.'/'.$this->objectId, $sessionToken, null, $useMasterKey ); $this->_mergeAfterFetch($response); @@ -483,8 +487,8 @@ public function fetch($useMasterKey = false) /** * Merges data received from the server. * - * @param array $result Data retrieved from the server. - * @param bool $completeData Fetch all data or not. + * @param array $result Data retrieved from the server. + * @param bool $completeData Fetch all data or not. * * @return null * @ignore @@ -498,8 +502,8 @@ public function _mergeAfterFetch($result, $completeData = true) unset($this->operationSet[$key]); } } - $this->serverData = array(); - $this->dataAvailability = array(); + $this->serverData = []; + $this->dataAvailability = []; $this->mergeFromServer($result, $completeData); $this->rebuildEstimatedData(); } @@ -507,9 +511,10 @@ public function _mergeAfterFetch($result, $completeData = true) /** * Merges data received from the server with a given selected keys. * - * @param array $result Data retrieved from the server. - * @param array $selectedKeys Keys to be fetched. Null or empty means all - * data will be fetched. + * @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 */ @@ -524,8 +529,8 @@ public function _mergeAfterFetchWithSelectedKeys($result, $selectedKeys) /** * Merges data received from the server. * - * @param array $data Data retrieved from server. - * @param bool $completeData Fetch all data or not. + * @param array $data Data retrieved from server. + * @param bool $completeData Fetch all data or not. * * @return null */ @@ -553,7 +558,6 @@ private function mergeFromServer($data, $completeData = true) } $this->serverData[$key] = $decodedValue; $this->dataAvailability[$key] = true; - } if (!$this->updatedAt && $this->createdAt) { $this->updatedAt = $this->createdAt; @@ -586,7 +590,6 @@ public function _mergeMagicFields(&$data) $this->serverData['ACL'] = $acl; unset($data['ACL']); } - } /** @@ -597,7 +600,7 @@ public function _mergeMagicFields(&$data) */ protected function rebuildEstimatedData() { - $this->estimatedData = array(); + $this->estimatedData = []; foreach ($this->serverData as $key => $value) { $this->estimatedData[$key] = $value; } @@ -605,10 +608,10 @@ protected function rebuildEstimatedData() } /** - * 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. + * @param array &$target Target data to affect. * * @return null */ @@ -646,18 +649,19 @@ public function destroy($useMasterKey = false) $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); } ParseClient::_request( - 'DELETE', '/1/classes/' . $this->className . - '/' . $this->objectId, $sessionToken, null, $useMasterKey + 'DELETE', '/1/classes/'.$this->className. + '/'.$this->objectId, $sessionToken, null, $useMasterKey ); } /** * Delete an array of objects. * - * @param array $objects Objects to destroy. + * @param array $objects Objects to destroy. * @param boolean $useMasterKey Whether to use the master key or not. * * @throws ParseAggregateException + * * @return null */ public static function destroyAll(array $objects, $useMasterKey = false) @@ -685,7 +689,8 @@ public static function destroyAll(array $objects, $useMasterKey = false) ); } } - return null; + + return; } private static function destroyBatch(array $objects, $useMasterKey = false) @@ -693,11 +698,11 @@ private static function destroyBatch(array $objects, $useMasterKey = false) $data = []; $errors = []; foreach ($objects as $object) { - $data[] = array( + $data[] = [ "method" => "DELETE", - "path" => "/1/classes/" . $object->getClassName() . - "/" . $object->getObjectId() - ); + "path" => "/1/classes/".$object->getClassName(). + "/".$object->getObjectId(), + ]; } $sessionToken = null; if (ParseUser::getCurrentUser()) { @@ -705,7 +710,7 @@ private static function destroyBatch(array $objects, $useMasterKey = false) } $result = ParseClient::_request( "POST", "/1/batch", $sessionToken, - json_encode(array("requests" => $data)), + json_encode(["requests" => $data]), $useMasterKey ); foreach ($objects as $key => $object) { @@ -713,20 +718,21 @@ private static function destroyBatch(array $objects, $useMasterKey = false) $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; } /** * Increment a numeric key by a certain value. * - * @param string $key Key for numeric value on object to increment. - * @param int $value Value to increment by. + * @param string $key Key for numeric value on object to increment. + * @param int $value Value to increment by. * * @return null */ @@ -738,8 +744,8 @@ public function increment($key, $value = 1) /** * Add a value to an array property. * - * @param string $key Key for array value on object to add a value to. - * @param mixed $value Value to add. + * @param string $key Key for array value on object to add a value to. + * @param mixed $value Value to add. * * @return null */ @@ -751,8 +757,8 @@ public function add($key, $value) /** * Add unique values to an array property. * - * @param string $key Key for array value on object. - * @param mixed $value Value list to add uniquely. + * @param string $key Key for array value on object. + * @param mixed $value Value list to add uniquely. * * @return null */ @@ -781,7 +787,7 @@ public function delete($key) */ public function _encode() { - $out = array(); + $out = []; if ($this->objectId) { $out['objectId'] = $this->objectId; } @@ -797,8 +803,8 @@ public function _encode() 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(); + } elseif (is_array($value)) { + $out[$key] = []; foreach ($value as $item) { if (is_object($item) && $item instanceof \Parse\Internal\Encodable) { $out[$key][] = $item->_encode(); @@ -810,6 +816,7 @@ public function _encode() $out[$key] = $value; } } + return json_encode($out); } @@ -824,9 +831,9 @@ private function getSaveJSON() } /** - * Save Object to Parse + * Save Object to Parse. * - * @param bool $useMasterKey Whether to use the Master Key. + * @param bool $useMasterKey Whether to use the Master Key. * * @return null */ @@ -839,10 +846,10 @@ public function save($useMasterKey = false) } /** - * 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. + * @param bool $useMasterKey Whether to use the Master Key. * * @return null */ @@ -855,16 +862,16 @@ public static function saveAll($list, $useMasterKey = false) * Save Object and unsaved children within. * * @param $target - * @param bool $useMasterKey Whether to use the Master Key. - * - * @return null + * @param bool $useMasterKey Whether to use the Master Key. * * @throws ParseException + * + * @return null */ private static function deepSave($target, $useMasterKey = false) { - $unsavedChildren = array(); - $unsavedFiles = array(); + $unsavedChildren = []; + $unsavedFiles = []; static::findUnsavedChildren($target, $unsavedChildren, $unsavedFiles); $sessionToken = null; if (ParseUser::getCurrentUser()) { @@ -875,7 +882,7 @@ private static function deepSave($target, $useMasterKey = false) $file->save(); } - $objects = array(); + $objects = []; // Get the set of unique objects among the children. foreach ($unsavedChildren as &$obj) { if (!in_array($obj, $objects, true)) { @@ -885,9 +892,8 @@ private static function deepSave($target, $useMasterKey = false) $remaining = $objects; while (count($remaining) > 0) { - - $batch = array(); - $newRemaining = array(); + $batch = []; + $newRemaining = []; foreach ($remaining as $key => &$object) { if (count($batch) > 40) { @@ -906,19 +912,19 @@ private static function deepSave($target, $useMasterKey = false) throw new Exception("Tried to save a batch with a cycle."); } - $requests = array(); + $requests = []; foreach ($batch as $obj) { $json = $obj->getSaveJSON(); $method = 'POST'; - $path = '/1/classes/' . $obj->getClassName(); + $path = '/1/classes/'.$obj->getClassName(); if ($obj->getObjectId()) { - $path .= '/' . $obj->getObjectId(); + $path .= '/'.$obj->getObjectId(); $method = 'PUT'; } - $requests[] = array('method' => $method, - 'path' => $path, - 'body' => $json - ); + $requests[] = ['method' => $method, + 'path' => $path, + 'body' => $json, + ]; } if (count($requests) === 1) { @@ -928,29 +934,29 @@ private static function deepSave($target, $useMasterKey = false) $batch[0]->mergeAfterSave($result); } else { $result = ParseClient::_request('POST', '/1/batch', $sessionToken, - json_encode(array("requests" => $requests)), $useMasterKey); + json_encode(["requests" => $requests]), $useMasterKey); - $errorCollection = array(); + $errorCollection = []; foreach ($batch as $key => &$obj) { if (isset($result[$key]['success'])) { $obj->mergeAfterSave($result[$key]['success']); - } else if (isset($result[$key]['error'])) { + } elseif (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 - ); + $errorCollection[] = [ + 'error' => $error, + 'code' => $code, + 'object' => $obj, + ]; } else { - $errorCollection[] = array( - 'error' => 'Unknown error in batch save.', - 'code' => -1, - 'object' => $obj - ); + $errorCollection[] = [ + 'error' => 'Unknown error in batch save.', + 'code' => -1, + 'object' => $obj, + ]; } } if (count($errorCollection)) { @@ -965,9 +971,9 @@ private static function deepSave($target, $useMasterKey = false) /** * Find unsaved children inside an object. * - * @param ParseObject $object Object to search. - * @param array &$unsavedChildren Array to populate with children. - * @param array &$unsavedFiles Array to populate with files. + * @param ParseObject $object Object to search. + * @param array &$unsavedChildren Array to populate with children. + * @param array &$unsavedFiles Array to populate with files. */ private static function findUnsavedChildren($object, &$unsavedChildren, &$unsavedFiles) @@ -980,7 +986,7 @@ private static function findUnsavedChildren($object, if ($obj->_isDirty(false)) { $unsavedChildren[] = $obj; } - } else if ($obj instanceof ParseFile) { + } elseif ($obj instanceof ParseFile) { if (!$obj->getURL()) { $unsavedFiles[] = $obj; } @@ -992,19 +998,19 @@ private static function findUnsavedChildren($object, /** * Traverse object to find children. * - * @param boolean $deep Should this call traverse deeply - * @param ParseObject|array &$object Object to traverse. - * @param callable $mapFunction Function to call for every item. - * @param array $seen Objects already seen. + * @param boolean $deep Should this call traverse deeply + * @param ParseObject|array &$object Object to traverse. + * @param callable $mapFunction Function to call for every item. + * @param array $seen Objects already seen. * * @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; + return; } $seen[] = $object; if ($deep) { @@ -1012,6 +1018,7 @@ private static function traverse($deep, &$object, $mapFunction, $deep, $object->estimatedData, $mapFunction, $seen ); } + return $mapFunction($object); } if ($object instanceof ParseRelation || $object instanceof ParseFile) { @@ -1021,8 +1028,10 @@ private static function traverse($deep, &$object, $mapFunction, foreach ($object as $key => $value) { self::traverse($deep, $value, $mapFunction, $seen); } + return $mapFunction($object); } + return $mapFunction($object); } @@ -1056,17 +1065,19 @@ private static function canBeSerializedAsValue($object) if ($obj instanceof ParseObject) { if (!$obj->getObjectId()) { $result = false; + return; } } }); + return $result; } /** * Merge server data after a save completes. * - * @param array $result Data retrieved from server. + * @param array $result Data retrieved from server. * * @return null */ @@ -1074,7 +1085,7 @@ private function mergeAfterSave($result) { $this->applyOperations($this->operationSet, $this->serverData); $this->mergeFromServer($result); - $this->operationSet = array(); + $this->operationSet = []; $this->rebuildEstimatedData(); } @@ -1082,8 +1093,9 @@ private function mergeAfterSave($result) * 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. + * exists for the key or can be created for this key. */ public function getRelation($key) { @@ -1094,15 +1106,17 @@ public function getRelation($key) $relation->setTargetClass($object->getTargetClass()); } } + return $relation; } /** * Gets a Pointer referencing this Object. * + * @throws \Exception + * * @return array * - * @throws \Exception * @ignore */ public function _toPointer() @@ -1110,10 +1124,11 @@ public function _toPointer() if (!$this->objectId) { throw new \Exception("Can't serialize an unsaved Parse.Object"); } - return array( - '__type' => "Pointer", + + return [ + '__type' => "Pointer", 'className' => $this->className, - 'objectId' => $this->objectId); + 'objectId' => $this->objectId, ]; } /** @@ -1139,18 +1154,20 @@ public function getACL() private function getACLWithCopy($mayCopy) { if (!isset($this->estimatedData['ACL'])) { - return null; + return; } $acl = $this->estimatedData['ACL']; if ($mayCopy && $acl->_isShared()) { return clone $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() @@ -1170,6 +1187,7 @@ public static function registerSubclass() /** * Un-register a subclass. * Cannot be called on the base class ParseObject. + * * @ignore */ public static function _unregisterSubclass() @@ -1182,9 +1200,9 @@ public static function _unregisterSubclass() * 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() { @@ -1197,5 +1215,4 @@ public static function query() return new ParseQuery($subclass); } } - } diff --git a/src/Parse/ParsePush.php b/src/Parse/ParsePush.php index a149e25a..fd039ef2 100644 --- a/src/Parse/ParsePush.php +++ b/src/Parse/ParsePush.php @@ -3,30 +3,29 @@ 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. * - * @param array $data The data of the push notification. Valid fields - * are: - * channels - An Array of channels to push to. - * push_time - A Date object for when to send the push. - * expiration_time - A Date object for when to expire - * the push. - * expiration_interval - The seconds from now to expire the push. - * where - A ParseQuery over ParseInstallation that is used to match - * a set of installations to push to. - * data - The data to send as part of the push + * @param array $data The data of the push notification. Valid fields + * are: + * channels - An Array of channels to push to. + * push_time - A Date object for when to send the push. + * expiration_time - A Date object for when to expire + * the push. + * expiration_interval - The seconds from now to expire the push. + * where - A ParseQuery over ParseInstallation that is used to match + * a set of installations to push to. + * data - The data to send as part of the push * @param boolean $useMasterKey Whether to use the Master Key for the request * * @throws \Exception, ParseException + * * @return mixed */ public static function send($data, $useMasterKey = false) @@ -56,6 +55,7 @@ public static function send($data, $useMasterKey = false) $data['expiration_time'], false )['iso']; } + return ParseClient::_request( 'POST', '/1/push', @@ -64,5 +64,4 @@ public static function send($data, $useMasterKey = false) $useMasterKey ); } - } diff --git a/src/Parse/ParseQuery.php b/src/Parse/ParseQuery.php index 91c5864d..7ee96b2e 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. */ @@ -55,14 +53,14 @@ public function __construct($className) } /** - * 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 + * Execute a query to retrieve a specific object. * - * @return array + * @param string $objectId Unique object id to retrieve. + * @param bool $useMasterKey If the query should use the master key * * @throws ParseException + * + * @return array */ public function get($objectId, $useMasterKey = false) { @@ -71,14 +69,15 @@ public function get($objectId, $useMasterKey = false) if (empty($result)) { throw new ParseException("Object not found.", 101); } + return $result; } /** * Set a constraint for a field matching a given value. * - * @param string $key Key to set up an equals constraint. - * @param mixed $value Value the key must equal. + * @param string $key Key to set up an equals constraint. + * @param mixed $value Value the key must equal. * * @return ParseQuery Returns this query, so you can chain this call. */ @@ -89,6 +88,7 @@ public function equalTo($key, $value) } else { $this->where[$key] = $value; } + return $this; } @@ -98,7 +98,7 @@ public function equalTo($key, $value) private function addCondition($key, $condition, $value) { if (!isset($this->where[$key])) { - $this->where[$key] = array(); + $this->where[$key] = []; } $this->where[$key][$condition] = ParseClient::_encode($value, true); } @@ -107,14 +107,15 @@ private function addCondition($key, $condition, $value) * Add a constraint to the query that requires a particular key's value to * be not equal to the provided value. * - * @param string $key The key to check. - * @param mixed $value The value that must not be equalled. + * @param string $key The key to check. + * @param mixed $value The value that must not be equalled. * * @return ParseQuery Returns this query, so you can chain this call. */ public function notEqualTo($key, $value) { $this->addCondition($key, '$ne', $value); + return $this; } @@ -122,14 +123,15 @@ public function notEqualTo($key, $value) * Add a constraint to the query that requires a particular key's value to * be less than the provided value. * - * @param string $key The key to check. - * @param mixed $value The value that provides an Upper bound. + * @param string $key The key to check. + * @param mixed $value The value that provides an Upper bound. * * @return ParseQuery Returns this query, so you can chain this call. */ public function lessThan($key, $value) { $this->addCondition($key, '$lt', $value); + return $this; } @@ -137,14 +139,15 @@ public function lessThan($key, $value) * Add a constraint to the query that requires a particular key's value to * be greater than the provided value. * - * @param string $key The key to check. - * @param mixed $value The value that provides an Lower bound. + * @param string $key The key to check. + * @param mixed $value The value that provides an Lower bound. * * @return ParseQuery Returns this query, so you can chain this call. */ public function greaterThan($key, $value) { $this->addCondition($key, '$gt', $value); + return $this; } @@ -152,14 +155,15 @@ public function greaterThan($key, $value) * Add a constraint to the query that requires a particular key's value to * be greater than or equal to the provided value. * - * @param string $key The key to check. - * @param mixed $value The value that provides an Lower bound. + * @param string $key The key to check. + * @param mixed $value The value that provides an Lower bound. * * @return ParseQuery Returns this query, so you can chain this call. */ public function greaterThanOrEqualTo($key, $value) { $this->addCondition($key, '$gte', $value); + return $this; } @@ -167,38 +171,41 @@ public function greaterThanOrEqualTo($key, $value) * Add a constraint to the query that requires a particular key's value to * be less than or equal to the provided value. * - * @param string $key The key to check. - * @param mixed $value The value that provides an Upper bound. + * @param string $key The key to check. + * @param mixed $value The value that provides an Upper bound. * * @return ParseQuery Returns this query, so you can chain this call. */ public function lessThanOrEqualTo($key, $value) { $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"; } /** * Add a constraint to the query that requires a particular key's value to * start with the provided value. * - * @param string $key The key to check. - * @param mixed $value The substring that the value must start with. + * @param string $key The key to check. + * @param mixed $value The substring that the value must start with. * * @return ParseQuery Returns this query, so you can chain this call. */ public function startsWith($key, $value) { $this->addCondition($key, '$regex', "^".$this->quote($value)); + return $this; } @@ -210,15 +217,15 @@ public function startsWith($key, $value) */ public function _getOptions() { - $opts = array(); + $opts = []; if (!empty($this->where)) { $opts['where'] = $this->where; } if (count($this->includes)) { - $opts['include'] = join(',', $this->includes); + $opts['include'] = implode(',', $this->includes); } if (count($this->selectedKeys)) { - $opts['keys'] = join(',', $this->selectedKeys); + $opts['keys'] = implode(',', $this->selectedKeys); } if ($this->limit >= 0) { $opts['limit'] = $this->limit; @@ -227,11 +234,12 @@ public function _getOptions() $opts['skip'] = $this->skip; } if ($this->orderBy) { - $opts['order'] = join(',', $this->orderBy); + $opts['order'] = implode(',', $this->orderBy); } if ($this->count) { $opts['count'] = $this->count; } + return $opts; } @@ -249,12 +257,13 @@ public function first($useMasterKey = false) if (count($result)) { return $result[0]; } else { - return array(); + return []; } } /** * Build query string from query constraints. + * * @param array $queryOptions Associative array of the query constraints. * * @return string Query string. @@ -265,6 +274,7 @@ private function buildQueryString($queryOptions) $queryOptions["where"] = ParseClient::_encode($queryOptions["where"], true); $queryOptions["where"] = json_encode($queryOptions["where"]); } + return http_build_query($queryOptions); } @@ -281,8 +291,9 @@ public function count($useMasterKey = false) $this->count = 1; $queryString = $this->buildQueryString($this->_getOptions()); $result = ParseClient::_request('GET', - '/1/classes/' . $this->className . - '?' . $queryString, null, null, $useMasterKey); + '/1/classes/'.$this->className. + '?'.$queryString, null, null, $useMasterKey); + return $result['count']; } @@ -301,14 +312,15 @@ public function find($useMasterKey = false) } $queryString = $this->buildQueryString($this->_getOptions()); $result = ParseClient::_request('GET', - '/1/classes/' . $this->className . - '?' . $queryString, $sessionToken, null, $useMasterKey); - $output = array(); + '/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; } @@ -322,11 +334,12 @@ public function find($useMasterKey = false) public function skip($n) { $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. * @@ -335,19 +348,22 @@ public function skip($n) public function limit($n) { $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(); + $this->orderBy = []; + return $this->addAscending($key); } @@ -366,19 +382,22 @@ public function addAscending($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(); + $this->orderBy = []; + return $this->addDescending($key); } @@ -394,12 +413,13 @@ public function addDescending($key) { if (is_array($key)) { $key = array_map(function ($element) { - return '-' . $element; + return '-'.$element; }, $key); $this->orderBy = array_merge($this->orderBy, $key); } else { - $this->orderBy[] = "-" . $key; + $this->orderBy[] = "-".$key; } + return $this; } @@ -407,7 +427,7 @@ public function addDescending($key) * Add a proximity based constraint for finding objects with key point * values near the point given. * - * @param string $key The key that the ParseGeoPoint is stored in. + * @param string $key The key that the ParseGeoPoint is stored in. * @param ParseGeoPoint $point The reference ParseGeoPoint that is used. * * @return ParseQuery Returns this query, so you can chain this call. @@ -415,6 +435,7 @@ public function addDescending($key) public function near($key, $point) { $this->addCondition($key, '$nearSphere', $point); + return $this; } @@ -422,9 +443,9 @@ public function near($key, $point) * Add a proximity based constraint for finding objects with key point * values near the point given and within the maximum distance given. * - * @param string $key The key of the ParseGeoPoint - * @param ParseGeoPoint $point The ParseGeoPoint that is used. - * @param int $maxDistance Maximum distance (in radians) + * @param string $key The key of the ParseGeoPoint + * @param ParseGeoPoint $point The ParseGeoPoint that is used. + * @param int $maxDistance Maximum distance (in radians) * * @return ParseQuery Returns this query, so you can chain this call. */ @@ -432,6 +453,7 @@ public function withinRadians($key, $point, $maxDistance) { $this->near($key, $point); $this->addCondition($key, '$maxDistance', $maxDistance); + return $this; } @@ -440,9 +462,9 @@ public function withinRadians($key, $point, $maxDistance) * values near the point given and within the maximum distance given. * Radius of earth used is 3958.5 miles. * - * @param string $key The key of the ParseGeoPoint - * @param ParseGeoPoint $point The ParseGeoPoint that is used. - * @param int $maxDistance Maximum distance (in miles) + * @param string $key The key of the ParseGeoPoint + * @param ParseGeoPoint $point The ParseGeoPoint that is used. + * @param int $maxDistance Maximum distance (in miles) * * @return ParseQuery Returns this query, so you can chain this call. */ @@ -450,6 +472,7 @@ public function withinMiles($key, $point, $maxDistance) { $this->near($key, $point); $this->addCondition($key, '$maxDistance', $maxDistance / 3958.8); + return $this; } @@ -458,9 +481,9 @@ public function withinMiles($key, $point, $maxDistance) * values near the point given and within the maximum distance given. * Radius of earth used is 6371.0 kilometers. * - * @param string $key The key of the ParseGeoPoint - * @param ParseGeoPoint $point The ParseGeoPoint that is used. - * @param int $maxDistance Maximum distance (in kilometers) + * @param string $key The key of the ParseGeoPoint + * @param ParseGeoPoint $point The ParseGeoPoint that is used. + * @param int $maxDistance Maximum distance (in kilometers) * * @return ParseQuery Returns this query, so you can chain this call. */ @@ -468,6 +491,7 @@ public function withinKilometers($key, $point, $maxDistance) { $this->near($key, $point); $this->addCondition($key, '$maxDistance', $maxDistance / 6371.0); + return $this; } @@ -476,7 +500,7 @@ public function withinKilometers($key, $point, $maxDistance) * coordinates be contained within a given rectangular geographic bounding * box. * - * @param string $key The key of the ParseGeoPoint + * @param string $key The key of the ParseGeoPoint * @param ParseGeoPoint $southwest The lower-left corner of the box. * @param ParseGeoPoint $northeast The upper-right corner of the box. * @@ -486,6 +510,7 @@ public function withinGeoBox($key, $southwest, $northeast) { $this->addCondition($key, '$within', ['$box' => [$southwest, $northeast]]); + return $this; } @@ -493,14 +518,15 @@ public function withinGeoBox($key, $southwest, $northeast) * Add a constraint to the query that requires a particular key's value to * be contained in the provided list of values. * - * @param string $key The key to check. - * @param array $values The values that will match. + * @param string $key The key to check. + * @param array $values The values that will match. * * @return ParseQuery Returns the query, so you can chain this call. */ public function containedIn($key, $values) { $this->addCondition($key, '$in', $values); + return $this; } @@ -509,10 +535,10 @@ public function containedIn($key, $values) * items are processed in an unspecified order. The query may not have any * sort order, and may not use limit or skip. * - * @param callable $callback Callback that will be called with each result - * of the query. - * @param boolean $useMasterKey - * @param int $batchSize + * @param callable $callback Callback that will be called with each result + * of the query. + * @param boolean $useMasterKey + * @param int $batchSize * * @throws \Exception If query has sort, skip, or limit. */ @@ -547,14 +573,15 @@ public function each($callback, $useMasterKey = false, $batchSize = 100) * Add a constraint to the query that requires a particular key's value to * not be contained in the provided list of values. * - * @param string $key The key to check. - * @param array $values The values that will not match. + * @param string $key The key to check. + * @param array $values The values that will not match. * * @return ParseQuery Returns the query, so you can chain this call. */ public function notContainedIn($key, $values) { $this->addCondition($key, '$nin', $values); + return $this; } @@ -562,8 +589,8 @@ public function notContainedIn($key, $values) * Add a constraint that requires that a key's value matches a ParseQuery * constraint. * - * @param string $key The key that the contains the object to match - * the query. + * @param string $key The key that the contains the object to match + * the query. * @param ParseQuery $query The query that should match. * * @return ParseQuery Returns the query, so you can chain this call. @@ -573,6 +600,7 @@ public function matchesQuery($key, $query) $queryParam = $query->_getOptions(); $queryParam["className"] = $query->className; $this->addCondition($key, '$inQuery', $queryParam); + return $this; } @@ -580,8 +608,8 @@ public function matchesQuery($key, $query) * Add a constraint that requires that a key's value not matches a ParseQuery * constraint. * - * @param string $key The key that the contains the object not to - * match the query. + * @param string $key The key that the contains the object not to + * match the query. * @param ParseQuery $query The query that should not match. * * @return ParseQuery Returns the query, so you can chain this call. @@ -591,6 +619,7 @@ public function doesNotMatchQuery($key, $query) $queryParam = $query->_getOptions(); $queryParam["className"] = $query->className; $this->addCondition($key, '$notInQuery', $queryParam); + return $this; } @@ -598,11 +627,11 @@ public function doesNotMatchQuery($key, $query) * Add a constraint that requires that a key's value matches a value in an * object returned by the given query. * - * @param string $key The key that contains teh value that is being - * matched. - * @param string $queryKey The key in objects returned by the query to - * match against. - * @param ParseQuery $query The query to run. + * @param string $key The key that contains teh value that is being + * matched. + * @param string $queryKey The key in objects returned by the query to + * match against. + * @param ParseQuery $query The query to run. * * @return ParseQuery Returns the query, so you can chain this call. */ @@ -612,6 +641,7 @@ public function matchesKeyInQuery($key, $queryKey, $query) $queryParam["className"] = $query->className; $this->addCondition($key, '$select', ['key' => $queryKey, 'query' => $queryParam]); + return $this; } @@ -619,11 +649,11 @@ public function matchesKeyInQuery($key, $queryKey, $query) * Add a constraint that requires that a key's value not match a value in an * object returned by the given query. * - * @param string $key The key that contains teh value that is being - * excluded. - * @param string $queryKey The key in objects returned by the query to - * match against. - * @param ParseQuery $query The query to run. + * @param string $key The key that contains teh value that is being + * excluded. + * @param string $queryKey The key in objects returned by the query to + * match against. + * @param ParseQuery $query The query to run. * * @return ParseQuery Returns the query, so you can chain this call. */ @@ -633,6 +663,7 @@ public function doesNotMatchKeyInQuery($key, $queryKey, $query) $queryParam["className"] = $query->className; $this->addCondition($key, '$dontSelect', ['key' => $queryKey, 'query' => $queryParam]); + return $this; } @@ -642,9 +673,9 @@ 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) { @@ -660,6 +691,7 @@ public static function orQueries($queryObjects) } $query = new ParseQuery($className); $query->_or($queryObjects); + return $query; } @@ -673,11 +705,12 @@ public static function orQueries($queryObjects) */ private function _or($queries) { - $this->where['$or'] = array(); + $this->where['$or'] = []; $length = count($queries); for ($i = 0; $i < $length; $i++) { $this->where['$or'][] = $queries[$i]->where; } + return $this; } @@ -685,14 +718,15 @@ private function _or($queries) * Add a constraint to the query that requires a particular key's value to * contain each one of the provided list of values. * - * @param string $key The key to check. This key's value must be an array. - * @param array $values The values that will match. + * @param string $key The key to check. This key's value must be an array. + * @param array $values The values that will match. * * @return ParseQuery Returns the query, so you can chain this call. */ public function containsAll($key, $values) { $this->addCondition($key, '$all', $values); + return $this; } @@ -706,6 +740,7 @@ public function containsAll($key, $values) public function exists($key) { $this->addCondition($key, '$exists', true); + return $this; } @@ -719,6 +754,7 @@ public function exists($key) public function doesNotExist($key) { $this->addCondition($key, '$exists', false); + return $this; } @@ -728,7 +764,7 @@ public function doesNotExist($key) * specified in each of the calls will be included. * * @param mixed $key The name(s) of the key(s) to include. It could be - * string, or an Array of string. + * string, or an Array of string. * * @return ParseQuery Returns the query, so you can chain this call. */ @@ -739,6 +775,7 @@ public function select($key) } else { $this->selectedKeys[] = $key; } + return $this; } @@ -747,7 +784,7 @@ public function select($key) * notation to specify which fields in the included object are also fetch. * * @param mixed $key The name(s) of the key(s) to include. It could be - * string, or an Array of string. + * string, or an Array of string. * * @return ParseQuery Returns the query, so you can chain this call. */ @@ -758,19 +795,22 @@ public function includeKey($key) } else { $this->includes[] = $key; } + return $this; } /** * Add constraint for parse relation. + * * @param string $key - * @param mixed $value + * @param mixed $value * * @return ParseQuery Returns the query, so you can chain this call. */ public function relatedTo($key, $value) { $this->addCondition('$relatedTo', $key, $value); + return $this; } } diff --git a/src/Parse/ParseRelation.php b/src/Parse/ParseRelation.php index b3431771..8fcd86ec 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. */ @@ -29,9 +28,9 @@ class ParseRelation { /** * Creates a new Relation for the given parent object, key and class name of target objects. * - * @param ParseObject $parent The parent of this relation. - * @param string $key The key of the relation in the parent object. - * @param string $targetClassName The className of the target objects. + * @param ParseObject $parent The parent of this relation. + * @param string $key The key of the relation in the parent object. + * @param string $targetClassName The className of the target objects. */ public function __construct($parent, $key, $targetClassName = null) { @@ -119,7 +118,8 @@ public function setTargetClass($className) * * @param $parent */ - public function setParent($parent) { + public function setParent($parent) + { $this->parent = $parent; } @@ -133,6 +133,7 @@ public function getQuery() $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 3b6ac04d..50b5db29 100644 --- a/src/Parse/ParseRole.php +++ b/src/Parse/ParseRole.php @@ -2,23 +2,19 @@ namespace Parse; -use Parse\ParseObject; - /** * ParseRole - Representation of an access Role. * - * @package Parse * @author Fosco Marotto */ class ParseRole extends ParseObject { - public static $parseClassName = "_Role"; /** * Create a ParseRole object with a given name and ACL. * - * @param string $name + * @param string $name * @param ParseACL $acl * * @return ParseRole @@ -28,6 +24,7 @@ public static function createRole($name, ParseACL $acl) $role = ParseObject::create(static::$parseClassName); $role->setName($name); $role->setACL($acl); + return $role; } @@ -60,6 +57,7 @@ public function setName($name) "A role's name must be a string." ); } + return $this->set("name", $name); } @@ -99,9 +97,7 @@ public function save($useMasterKey = false) "Roles must have a name." ); } + return parent::save($useMasterKey); } - - - } diff --git a/src/Parse/ParseSession.php b/src/Parse/ParseSession.php index 4e586a8a..ef938dee 100644 --- a/src/Parse/ParseSession.php +++ b/src/Parse/ParseSession.php @@ -2,18 +2,13 @@ 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; @@ -42,10 +37,10 @@ public static function getCurrentSession($useMasterKey = false) $session = new ParseSession(); $session->_mergeAfterFetch($response); $session->handleSaveResult(); + return $session; } - /** * Determines whether the current session token is revocable. * This method is useful for migrating an existing app to use @@ -86,5 +81,4 @@ private function handleSaveResult() } $this->rebuildEstimatedData(); } - } diff --git a/src/Parse/ParseSessionStorage.php b/src/Parse/ParseSessionStorage.php index 9c95fa35..b6450a66 100644 --- a/src/Parse/ParseSessionStorage.php +++ b/src/Parse/ParseSessionStorage.php @@ -5,12 +5,10 @@ /** * 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. */ @@ -24,7 +22,7 @@ public function __construct() ); } if (!isset($_SESSION[$this->storageKey])) { - $_SESSION[$this->storageKey] = array(); + $_SESSION[$this->storageKey] = []; } } @@ -43,12 +41,13 @@ public function get($key) if (isset($_SESSION[$this->storageKey][$key])) { return $_SESSION[$this->storageKey][$key]; } - return null; + + return; } public function clear() { - $_SESSION[$this->storageKey] = array(); + $_SESSION[$this->storageKey] = []; } public function save() @@ -66,5 +65,4 @@ public function getAll() { return $_SESSION[$this->storageKey]; } - } diff --git a/src/Parse/ParseStorageInterface.php b/src/Parse/ParseStorageInterface.php index 8b33b869..533dde7a 100644 --- a/src/Parse/ParseStorageInterface.php +++ b/src/Parse/ParseStorageInterface.php @@ -5,17 +5,15 @@ /** * ParseStorageInterface - Specifies an interface for implementing persistence. * - * @package Parse * @author Fosco Marotto */ interface ParseStorageInterface { - /** * Sets a key-value pair in storage. * - * @param string $key The key to set - * @param mixed $value The value to set + * @param string $key The key to set + * @param mixed $value The value to set * * @return null */ @@ -68,5 +66,4 @@ public function getKeys(); * @return array */ public function getAll(); - } diff --git a/src/Parse/ParseUser.php b/src/Parse/ParseUser.php index 94a7cdd2..27e89439 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"; /** @@ -92,7 +90,7 @@ public function isAuthenticated() /** * 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() { @@ -119,9 +117,9 @@ public function signUp() * @param string $username * @param string $password * - * @return ParseUser - * * @throws ParseException + * + * @return ParseUser */ public static function logIn($username, $password) { @@ -133,12 +131,13 @@ public static function logIn($username, $password) "Cannot log in user with an empty password." ); } - $data = array("username" => $username, "password" => $password); + $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; } @@ -157,13 +156,14 @@ public static function become($sessionToken) $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 */ @@ -219,6 +219,7 @@ public static function getCurrentUser() $userData = $storage->get("user"); if ($userData instanceof ParseUser) { static::$currentUser = $userData; + return $userData; } if (isset($userData["id"]) && isset($userData["_sessionToken"])) { @@ -229,11 +230,13 @@ public static function getCurrentUser() foreach ($userData as $key => $value) { $user->set($key, $value); } - $user->_opSetQueue = array(); + $user->_opSetQueue = []; static::$currentUser = $user; + return $user; } - return null; + + return; } /** @@ -248,7 +251,7 @@ protected static function saveCurrentUser() } /** - * Returns the session token, if available + * Returns the session token, if available. * * @return string|null */ @@ -269,15 +272,16 @@ public function isCurrent() return true; } } + return false; } /** * Save the current user object, unless it is not signed up. * - * @return null - * * @throws ParseException + * + * @return null */ public function save($useMasterKey = false) { @@ -301,7 +305,7 @@ public function save($useMasterKey = false) */ public static function requestPasswordReset($email) { - $json = json_encode(array('email' => $email)); + $json = json_encode(['email' => $email]); ParseClient::_request('POST', '/1/requestPasswordReset', null, $json); } @@ -312,5 +316,4 @@ public static function _clearCurrentUserVariable() { static::$currentUser = null; } - } diff --git a/tests/IncrementTest.php b/tests/IncrementTest.php index ecacd32b..bc33070d 100644 --- a/tests/IncrementTest.php +++ b/tests/IncrementTest.php @@ -1,8 +1,7 @@ increment('randomkeyagain'); $obj->save(); $this->setExpectedException('Parse\ParseException', - 'invalid type for key randomkeyagain, ' . + 'invalid type for key randomkeyagain, '. 'expected number, but got string' ); $objAgain->save(); diff --git a/tests/ParseACLTest.php b/tests/ParseACLTest.php index a79601a6..925f4744 100644 --- a/tests/ParseACLTest.php +++ b/tests/ParseACLTest.php @@ -1,13 +1,14 @@ assertEquals(1, count($query->find())); $object->save(); $object->destroy(); - } public function testACLMakingAnObjectPubliclyReadable() @@ -227,7 +227,6 @@ public function testACLSharingWithAnotherUser() $object->set('foo', 'bar'); $object->save(); $object->destroy(); - } public function testACLSaveAllWithPermissions() @@ -260,7 +259,6 @@ public function testACLSaveAllWithPermissions() $query = new ParseQuery('Object'); $query->equalTo('foo', 'bar'); $this->assertEquals(2, count($query->find())); - } public function testACLModifyingAfterLoad() @@ -285,8 +283,6 @@ public function testACLModifyingAfterLoad() $this->assertTrue($objectAgain->getACL()->getUserWriteAccess($user)); $this->assertTrue($objectAgain->getACL()->getPublicReadAccess()); $this->assertFalse($objectAgain->getACL()->getPublicWriteAccess()); - - } public function testACLRequiresObjectId() @@ -334,7 +330,6 @@ public function testACLRequiresObjectId() $this->fail('Exception should have thrown'); } catch (Exception $e) { } - } public function testIncludedObjectsGetACLs() @@ -385,7 +380,5 @@ public function testIncludedObjectsGetACLWithDefaultACL() $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 f174ea75..e8fec8e1 100644 --- a/tests/ParseAnalyticsTest.php +++ b/tests/ParseAnalyticsTest.php @@ -1,6 +1,5 @@ assertEquals($expectedJSON, $json); - ParseAnalytics::track($event, $params ?: array()); + ParseAnalytics::track($event, $params ?: []); } public function testTrackEvent() @@ -59,21 +58,20 @@ public function testFailsOnEventName3() public function testTrackEventDimensions() { $expected = '{"dimensions":{"foo":"bar","bar":"baz"}}'; - $params = array( + $params = [ 'foo' => 'bar', - 'bar' => 'baz' - ); + 'bar' => 'baz', + ]; $this->assertAnalyticsValidation('testDimensions', $params, $expected); $date = date(DATE_RFC3339); - $expected = '{"dimensions":{"foo":"bar","bar":"baz","someDate":"' . - $date . '"}}'; - $params = array( - 'foo' => 'bar', - 'bar' => 'baz', - 'someDate' => $date - ); + $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 08d410bc..7f8d8034 100644 --- a/tests/ParseBytesTest.php +++ b/tests/ParseBytesTest.php @@ -1,13 +1,13 @@ get($obj->getObjectId()); $this->assertEquals("Grantland", $objAgain->get("byteColumn")); } - } diff --git a/tests/ParseCloudTest.php b/tests/ParseCloudTest.php index a48bf0a3..cb0e7049 100644 --- a/tests/ParseCloudTest.php +++ b/tests/ParseCloudTest.php @@ -1,14 +1,13 @@ set('name', 'Zanzibar'); $obj->save(); - $params = array('key1' => $obj); + $params = ['key1' => $obj]; $this->setExpectedException('\Exception', 'ParseObjects not allowed'); ParseCloud::run('foo', $params); } public function testFunctionsWithGeoPointParamsDoNotThrow() { - $params = array('key1' => new ParseGeoPoint(50, 50)); + $params = ['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'); + $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 47c2cb4c..7fed4208 100644 --- a/tests/ParseConfigTest.php +++ b/tests/ParseConfigTest.php @@ -4,20 +4,20 @@ require_once 'ParseTestHelper.php'; -class ParseConfigMock extends ParseConfig { - public function __construct() { +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")); } - } diff --git a/tests/ParseFileTest.php b/tests/ParseFileTest.php index ff10207d..281b9d4a 100644 --- a/tests/ParseFileTest.php +++ b/tests/ParseFileTest.php @@ -6,8 +6,8 @@ require_once 'ParseTestHelper.php'; -class ParseFileTest extends \PHPUnit_Framework_TestCase { - +class ParseFileTest extends \PHPUnit_Framework_TestCase +{ public static function setUpBeforeClass() { ParseTestHelper::setUp(); @@ -138,5 +138,4 @@ public function testFileDelete() $this->setExpectedException('Parse\ParseException', 'Download failed'); $contents = $fileAgain->getData(); } - } diff --git a/tests/ParseGeoBoxTest.php b/tests/ParseGeoBoxTest.php index 8d8e6788..75959449 100644 --- a/tests/ParseGeoBoxTest.php +++ b/tests/ParseGeoBoxTest.php @@ -1,16 +1,14 @@ withinGeoBox('location', $northeastOfSF, $southwestOfSF); try { $results = $query->find(); - $this->assertTrue(FALSE, 'Query should fail because it crosses dateline'); + $this->assertTrue(false, 'Query should fail because it crosses dateline'); } catch (ParseException $e) { } @@ -68,7 +66,7 @@ public function testGeoBox() $query->withinGeoBox('location', $southeastOfSF, $northwestOfSF); try { $query->find(); - $this->assertTrue(FALSE, 'Query should fail because it crosses dateline'); + $this->assertTrue(false, 'Query should fail because it crosses dateline'); } catch (ParseException $e) { } @@ -77,7 +75,7 @@ public function testGeoBox() $query->withinGeoBox('location', $northwestOfSF, $southeastOfSF); try { $query->find(); - $this->assertTrue(FALSE, 'Query should fail because it makes no sense'); + $this->assertTrue(false, 'Query should fail because it makes no sense'); } catch (ParseException $e) { } } @@ -124,7 +122,7 @@ public function testGeoBoxSmallNearDateLine() $query->ascending('order'); try { $query->find(); - $this->assertTrue(FALSE, 'Query should fail for crossing the date line.'); + $this->assertTrue(false, 'Query should fail for crossing the date line.'); } catch (ParseException $e) { } } @@ -148,9 +146,8 @@ public function testGeoBoxTooLarge() $query->withinGeoBox('location', $southwest, $northeast); try { $query->find(); - $this->assertTrue(FALSE, 'Query should fail for being too large.'); + $this->assertTrue(false, 'Query should fail for being too large.'); } catch (ParseException $e) { } } } - diff --git a/tests/ParseGeoPointTest.php b/tests/ParseGeoPointTest.php index 578b8294..ea17c44b 100644 --- a/tests/ParseGeoPointTest.php +++ b/tests/ParseGeoPointTest.php @@ -1,15 +1,13 @@ find(); $this->assertEquals(1, count($results)); $this->assertEquals(0, $results[0]->get('id')); - } public function testGeoMaxDistanceWithUnits() diff --git a/tests/ParseMemoryStorageTest.php b/tests/ParseMemoryStorageTest.php index 2583ebd6..0b48c074 100644 --- a/tests/ParseMemoryStorageTest.php +++ b/tests/ParseMemoryStorageTest.php @@ -1,15 +1,12 @@ assertEquals('bar', $result['foo3']); $this->assertEquals(3, count($result)); } - } diff --git a/tests/ParseObjectTest.php b/tests/ParseObjectTest.php index 999ed27f..aec9abfe 100644 --- a/tests/ParseObjectTest.php +++ b/tests/ParseObjectTest.php @@ -1,15 +1,13 @@ get($obj->getObjectId()); - $this->assertTrue($returnedObject instanceOf ParseObject, + $this->assertTrue($returnedObject instanceof ParseObject, 'Returned object was not a ParseObject'); $this->assertEquals('bar', $returnedObject->foo, 'Value of foo was not saved.'); @@ -560,7 +558,7 @@ public function testSavingChildrenInArray() $child2 = ParseObject::create("Child"); $child1->set('name', 'tyrian'); $child2->set('name', 'cersei'); - $parent->setArray('children', array($child1, $child2)); + $parent->setArray('children', [$child1, $child2]); $parent->save(); $query = new ParseQuery("Child"); @@ -617,7 +615,7 @@ public function testAddWithAnObject() $parent = ParseObject::create("Person"); $child = ParseObject::create("Person"); $child->save(); - $parent->add("children", array($child)); + $parent->add("children", [$child]); $parent->save(); $query = new ParseQuery("Person"); @@ -731,7 +729,7 @@ public function testDestroyAll() public function testEmptyArray() { $obj = ParseObject::create('TestObject'); - $obj->setArray('baz', array()); + $obj->setArray('baz', []); $obj->save(); $query = new ParseQuery('TestObject'); $returnedObject = $query->get($obj->getObjectId()); @@ -743,9 +741,9 @@ public function testEmptyArray() public function testArraySetAndAdd() { $obj = ParseObject::create('TestObject'); - $obj->setArray('arrayfield', array('a', 'b')); + $obj->setArray('arrayfield', ['a', 'b']); $obj->save(); - $obj->add('arrayfield', array('c', 'd', 'e')); + $obj->add('arrayfield', ['c', 'd', 'e']); $obj->save(); } @@ -792,7 +790,7 @@ public function testObjectIsDirty() $this->assertFalse($queriedObj->isDirty()); // check array - $obj->add($key3, array($value1, $value2, $value1)); + $obj->add($key3, [$value1, $value2, $value1]); $this->assertTrue($obj->isDirty()); $obj->save(); @@ -839,7 +837,7 @@ public function testObjectIsDirtyWithChildren() // check case with array $childArray1->set('random', 'random2'); - $obj->add('arrayKey', array($childArray1, $childArray2)); + $obj->add('arrayKey', [$childArray1, $childArray2]); $this->assertTrue($obj->isDirty()); $childArray1->save(); $childArray2->save(); @@ -859,7 +857,7 @@ public function testObjectIsDirtyWithChildren() public function testSaveAll() { ParseTestHelper::clearClass("TestObject"); - $objs = array(); + $objs = []; for ($i = 1; $i <= 90; $i++) { $obj = ParseObject::create('TestObject'); $obj->set('test', 'test'); @@ -874,10 +872,10 @@ public function testSaveAll() public function testEmptyObjectsAndArrays() { $obj = ParseObject::create('TestObject'); - $obj->setArray('arr', array()); - $obj->setAssociativeArray('obj', array()); - $saveOpArray = new SetOperation(array()); - $saveOpAssoc = new SetOperation(array(), true); + $obj->setArray('arr', []); + $obj->setAssociativeArray('obj', []); + $saveOpArray = new SetOperation([]); + $saveOpAssoc = new SetOperation([], true); $this->assertTrue( is_array($saveOpArray->_encode()), "Value should be array." ); @@ -885,10 +883,10 @@ public function testEmptyObjectsAndArrays() is_object($saveOpAssoc->_encode()), "Value should be object." ); $obj->save(); - $obj->setAssociativeArray('obj', array( + $obj->setAssociativeArray('obj', [ 'foo' => 'bar', - 'baz' => 'yay' - )); + 'baz' => 'yay', + ]); $obj->save(); $query = new ParseQuery('TestObject'); $objAgain = $query->get($obj->getObjectId()); @@ -925,5 +923,4 @@ public function testBatchSaveExceptions() $this->assertContains("invalid field name", $errors[1]['error']); } } - } diff --git a/tests/ParsePushTest.php b/tests/ParsePushTest.php index 7520980c..111f1c0e 100644 --- a/tests/ParsePushTest.php +++ b/tests/ParsePushTest.php @@ -1,14 +1,12 @@ array(''), - 'data' => array('alert' => 'sample message') - )); + ParsePush::send([ + 'channels' => [''], + 'data' => ['alert' => 'sample message'], + ]); } public function testPushToQuery() { $query = ParseInstallation::query(); $query->equalTo('key', 'value'); - ParsePush::send(array( - 'data' => array('alert' => 'iPhone 5 is out!'), - 'where' => $query - )); + ParsePush::send([ + 'data' => ['alert' => 'iPhone 5 is out!'], + 'where' => $query, + ]); } public function testPushDates() { - ParsePush::send(array( - 'data' => array('alert' => 'iPhone 5 is out!'), - 'push_time' => new DateTime(), + ParsePush::send([ + 'data' => ['alert' => 'iPhone 5 is out!'], + 'push_time' => new DateTime(), 'expiration_time' => new DateTime(), - 'channels' => array() - )); + 'channels' => [], + ]); } } diff --git a/tests/ParseQueryTest.php b/tests/ParseQueryTest.php index dd38be83..0136b4af 100644 --- a/tests/ParseQueryTest.php +++ b/tests/ParseQueryTest.php @@ -1,16 +1,14 @@ saveObjects($numberOfObjects, function ($i) { $obj = ParseObject::create('TestObject'); - $obj->set('foo', 'bar' . $i); + $obj->set('foo', 'bar'.$i); + return $obj; }); } @@ -103,7 +102,7 @@ public function testNotEqualTo() $query->notEqualTo('foo', 'bar9'); $results = $query->find(); $this->assertEquals(count($results), 9, - 'Did not find 9 objects, found ' . count($results)); + 'Did not find 9 objects, found '.count($results)); } public function testLessThan() @@ -285,11 +284,12 @@ public function testLessThanGreaterThan() public function testObjectIdEqualTo() { ParseTestHelper::clearClass("BoxedNumber"); - $boxedNumberArray = array(); + $boxedNumberArray = []; $this->saveObjects(5, function ($i) use (&$boxedNumberArray) { $boxedNumber = new ParseObject("BoxedNumber"); $boxedNumber->set("number", $i); $boxedNumberArray[] = $boxedNumber; + return $boxedNumber; }); $query = new ParseQuery("BoxedNumber"); @@ -307,6 +307,7 @@ public function testFindNoElements() $this->saveObjects(5, function ($i) { $boxedNumber = new ParseObject("BoxedNumber"); $boxedNumber->set("number", $i); + return $boxedNumber; }); $query = new ParseQuery("BoxedNumber"); @@ -394,6 +395,7 @@ public function testFirstWithTwoResults() $this->saveObjects(2, function ($i) { $testObject = ParseObject::create("TestObject"); $testObject->set("foo", "bar"); + return $testObject; }); $query = new ParseQuery("TestObject"); @@ -407,14 +409,16 @@ public function testNotEqualToObject() { ParseTestHelper::clearClass("Container"); ParseTestHelper::clearClass("Item"); - $items = array(); + $items = []; $this->saveObjects(2, function ($i) use (&$items) { $items[] = ParseObject::create("Item"); + return $items[$i]; }); $this->saveObjects(2, function ($i) use ($items) { $container = ParseObject::create("Container"); $container->set("item", $items[$i]); + return $container; }); $query = new ParseQuery("Container"); @@ -463,6 +467,7 @@ public function testCount() $this->saveObjects(3, function ($i) { $boxedNumber = ParseObject::create("BoxedNumber"); $boxedNumber->set("x", $i + 1); + return $boxedNumber; }); $query = new ParseQuery("BoxedNumber"); @@ -487,6 +492,7 @@ public function testOrderByAscendingNumber() $this->saveObjects(3, function ($i) use ($numbers) { $boxedNumber = ParseObject::create("BoxedNumber"); $boxedNumber->set("number", $numbers[$i]); + return $boxedNumber; }); $query = new ParseQuery("BoxedNumber"); @@ -507,6 +513,7 @@ public function testOrderByDescendingNumber() $this->saveObjects(3, function ($i) use ($numbers) { $boxedNumber = ParseObject::create("BoxedNumber"); $boxedNumber->set("number", $numbers[$i]); + return $boxedNumber; }); $query = new ParseQuery("BoxedNumber"); @@ -528,6 +535,7 @@ public function provideTestObjectsForQuery($numberOfObjects) $child->set("x", $i); $parent->set("x", 10 + $i); $parent->set("child", $child); + return $parent; }); } @@ -588,6 +596,7 @@ public function provideTestObjectsForKeyInQuery() $restaurant = ParseObject::create("Restaurant"); $restaurant->set("ratings", $restaurantRatings[$i]); $restaurant->set("location", $restaurantLocations[$i]); + return $restaurant; }); @@ -595,6 +604,7 @@ public function provideTestObjectsForKeyInQuery() $person = ParseObject::create("Person"); $person->set("hometown", $personHomeTown[$i]); $person->set("name", $personName[$i]); + return $person; }); } @@ -661,6 +671,7 @@ public function testComplexQueries() $parent = new ParseObject("Parent"); $parent->set("y", $i); $parent->set("child", $child); + return $parent; }); $subQuery = new ParseQuery("Child"); @@ -684,12 +695,13 @@ public function testEach() $this->saveObjects($total, function ($i) { $obj = new ParseObject("Object"); $obj->set("x", $i + 1); + return $obj; }); $query = new ParseQuery("Object"); $query->lessThanOrEqualTo("x", $count); - $values = array(); + $values = []; $query->each(function ($obj) use (&$values) { $values[] = $obj->get("x"); }, 10); @@ -712,6 +724,7 @@ public function testEachFailsWithOrder() $this->saveObjects($total, function ($i) { $obj = new ParseObject("Object"); $obj->set("x", $i + 1); + return $obj; }); $query = new ParseQuery("Object"); @@ -729,6 +742,7 @@ public function testEachFailsWithSkip() $this->saveObjects($total, function ($i) { $obj = new ParseObject("Object"); $obj->set("x", $i + 1); + return $obj; }); $query = new ParseQuery("Object"); @@ -746,6 +760,7 @@ public function testEachFailsWithLimit() $this->saveObjects($total, function ($i) { $obj = new ParseObject("Object"); $obj->set("x", $i + 1); + return $obj; }); $query = new ParseQuery("Object"); @@ -793,17 +808,17 @@ public function testContainsAllStringArrayQueries() public function testContainsAllDateArrayQueries() { ParseTestHelper::clearClass("DateSet"); - $dates1 = array( + $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") - ); + new DateTime("2013-02-04T00:00:00Z"), + ]; $obj1 = ParseObject::create("DateSet"); $obj1->setArray("dates", $dates1); @@ -813,11 +828,11 @@ public function testContainsAllDateArrayQueries() $obj2->save(); $query = new ParseQuery("DateSet"); - $query->containsAll("dates", array( + $query->containsAll("dates", [ 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-03T00:00:00Z"), + ]); $result = $query->find(); $this->assertEquals(1, count($result), 'Did not return correct number of objects.'); @@ -826,10 +841,11 @@ public function testContainsAllDateArrayQueries() public function testContainsAllObjectArrayQueries() { ParseTestHelper::clearClass("MessageSet"); - $messageList = array(); + $messageList = []; $this->saveObjects(4, function ($i) use (&$messageList) { $messageList[] = ParseObject::create("TestObject"); $messageList[$i]->set("i", $i); + return $messageList[$i]; }); $messageSet1 = ParseObject::create("MessageSet"); @@ -837,12 +853,12 @@ public function testContainsAllObjectArrayQueries() $messageSet1->save(); $messageSet2 = ParseObject::create("MessageSet"); $messageSet2->setArray("message", - array($messageList[0], $messageList[1], $messageList[3]) + [$messageList[0], $messageList[1], $messageList[3]] ); $messageSet2->save(); $query = new ParseQuery("MessageSet"); - $query->containsAll("messages", array($messageList[0], $messageList[2])); + $query->containsAll("messages", [$messageList[0], $messageList[2]]); $results = $query->find(); $this->assertEquals(1, count($results), 'Did not return correct number of objects.'); @@ -850,17 +866,18 @@ public function testContainsAllObjectArrayQueries() public function testContainedInObjectArrayQueries() { - $messageList = array(); + $messageList = []; $this->saveObjects(4, function ($i) use (&$messageList) { $message = ParseObject::create("TestObject"); if ($i > 0) { $message->set("prior", $messageList[$i - 1]); } $messageList[] = $message; + return $message; }); $query = new ParseQuery("TestObject"); - $query->containedIn("prior", array($messageList[0], $messageList[2])); + $query->containedIn("prior", [$messageList[0], $messageList[2]]); $results = $query->find(); $this->assertEquals(2, count($results), 'Did not return correct number of objects.'); @@ -872,6 +889,7 @@ public function testContainedInQueries() $this->saveObjects(10, function ($i) { $boxedNumber = ParseObject::create("BoxedNumber"); $boxedNumber->set("number", $i); + return $boxedNumber; }); $query = new ParseQuery("BoxedNumber"); @@ -887,6 +905,7 @@ public function testNotContainedInQueries() $this->saveObjects(10, function ($i) { $boxedNumber = ParseObject::create("BoxedNumber"); $boxedNumber->set("number", $i); + return $boxedNumber; }); $query = new ParseQuery("BoxedNumber"); @@ -899,18 +918,19 @@ public function testNotContainedInQueries() public function testObjectIdContainedInQueries() { ParseTestHelper::clearClass("BoxedNumber"); - $objects = array(); + $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(), $objects[3]->getObjectId(), $objects[0]->getObjectId(), - "NONSENSE"] + "NONSENSE", ] ); $query->ascending("number"); $results = $query->find(); @@ -926,13 +946,14 @@ public function testObjectIdContainedInQueries() public function testStartsWith() { - $someAscii = "\\E' !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTU" . + $someAscii = "\\E' !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTU". "VWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'"; $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"); @@ -1050,11 +1071,12 @@ public function testOrderByCreatedAtDesc() public function testOrderByUpdatedAtAsc() { $numbers = [3, 1, 2]; - $objects = array(); + $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); @@ -1074,11 +1096,12 @@ public function testOrderByUpdatedAtAsc() public function testOrderByUpdatedAtDesc() { $numbers = [3, 1, 2]; - $objects = array(); + $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); @@ -1108,7 +1131,6 @@ public function testSelectKeysQuery() 'Did not return the correct object.'); $this->setExpectedException('\Exception', 'Call fetch()'); $result->get('bar'); - } public function testGetWithoutError() @@ -1135,7 +1157,6 @@ public function testSelectKeysQueryArrayArg() 'Did not return the correct object.'); $this->assertEquals(1, $result->get('bar'), 'Did not return the correct object.'); - } public function testExists() @@ -1147,6 +1168,7 @@ public function testExists() } else { $obj->set('x', $i); } + return $obj; }); $query = new ParseQuery("TestObject"); @@ -1165,6 +1187,7 @@ public function testDoesNotExist() } else { $obj->set('x', $i); } + return $obj; }); $query = new ParseQuery("TestObject"); @@ -1186,6 +1209,7 @@ public function testExistsRelation() $item->set('e', $i); $obj->set('e', $item); } + return $obj; }); $query = new ParseQuery("TestObject"); @@ -1207,6 +1231,7 @@ public function testDoesNotExistRelation() $item->set('x', $i); $obj->set('x', $i); } + return $obj; }); $query = new ParseQuery("TestObject"); @@ -1282,11 +1307,12 @@ public function testIncludeArrayRelation() { ParseTestHelper::clearClass("Child"); ParseTestHelper::clearClass("Parent"); - $children = array(); + $children = []; $this->saveObjects(5, function ($i) use (&$children) { $child = ParseObject::create("Child"); $child->set('x', $i); $children[] = $child; + return $child; }); $parent = ParseObject::create("Parent"); @@ -1361,6 +1387,7 @@ public function testIncludeWhenOnlySomeObjectsHaveChildren() if ($i & 1) { $parent->set('child', $child); } + return $parent; }); @@ -1412,15 +1439,17 @@ public function testEqualToObject() { ParseTestHelper::clearClass("Item"); ParseTestHelper::clearClass("Container"); - $items = array(); + $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) { $container = ParseObject::create("Container"); $container->set('item', $items[$i]); + return $container; }); $query = new ParseQuery("Container"); @@ -1435,6 +1464,7 @@ public function testEqualToNull() $this->saveObjects(10, function ($i) { $obj = ParseObject::create('TestObject'); $obj->set('num', $i); + return $obj; }); $query = new ParseQuery('TestObject'); @@ -1447,15 +1477,17 @@ public function testEqualToNull() public function provideTimeTestObjects() { ParseTestHelper::clearClass("TimeObject"); - $items = array(); + $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; } @@ -1516,5 +1548,4 @@ public function testRestrictedCount() $count = $query->count(true); $this->assertEquals(1, $count); } - } diff --git a/tests/ParseRelationTest.php b/tests/ParseRelationTest.php index 2e93c0cc..720c0fed 100644 --- a/tests/ParseRelationTest.php +++ b/tests/ParseRelationTest.php @@ -2,9 +2,11 @@ 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(); @@ -18,13 +20,13 @@ public function tearDown() /** * This function used as a helper function in test functions to save objects. * - * @param int $numberOfObjects Number of objects you want to save. - * @param callable $callback Function which takes int as a parameter. - * and should return ParseObject. + * @param int $numberOfObjects Number of objects you want to save. + * @param callable $callback Function which takes int as a parameter. + * and should return ParseObject. */ public function saveObjects($numberOfObjects, $callback) { - $allObjects = array(); + $allObjects = []; for ($i = 0; $i < $numberOfObjects; $i++) { $allObjects[] = $callback($i); } @@ -33,11 +35,12 @@ public function saveObjects($numberOfObjects, $callback) public function testParseRelations() { - $children = array(); + $children = []; $this->saveObjects(10, function ($i) use (&$children) { $child = ParseObject::create('ChildObject'); $child->set('x', $i); $children[] = $child; + return $child; }); $parent = ParseObject::create('ParentObject'); @@ -64,7 +67,6 @@ public function testParseRelations() $parent->set('bar', 3); $parent->save(); - $results = $relation->getQuery()->find(); $this->assertEquals(2, count($results)); $this->assertFalse($parent->isDirty()); @@ -74,7 +76,7 @@ public function testParseRelations() $children[5], $children[6], $children[7], - $children[8] + $children[8], ]); $parent->save(); @@ -93,16 +95,16 @@ public function testParseRelations() $results = $query->find(); $this->assertEquals(1, count($results)); $this->assertEquals($children[4]->getObjectId(), $results[0]->getObjectId()); - } public function testQueriesOnRelationFields() { - $children = array(); + $children = []; $this->saveObjects(10, function ($i) use (&$children) { $child = ParseObject::create('ChildObject'); $child->set('x', $i); $children[] = $child; + return $child; }); @@ -112,7 +114,7 @@ public function testQueriesOnRelationFields() $relation->add([ $children[0], $children[1], - $children[2] + $children[2], ]); $parent->save(); $parent2 = ParseObject::create('ParentObject'); @@ -121,7 +123,7 @@ public function testQueriesOnRelationFields() $relation2->add([ $children[4], $children[5], - $children[6] + $children[6], ]); $parent2->save(); $query = new ParseQuery('ParentObject'); @@ -129,7 +131,5 @@ public function testQueriesOnRelationFields() $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 7decdcb2..a3672d18 100644 --- a/tests/ParseRoleTest.php +++ b/tests/ParseRoleTest.php @@ -1,15 +1,15 @@ get($eden['garden']->getObjectId()); $this->fail("Get should have failed."); } catch (\Parse\ParseException $ex) { - if ($ex->getMessage() != "Object not found.") throw $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; + if ($ex->getMessage() != "Object not found.") { + throw $ex; + } } ParseUser::logIn("snake", "snake"); $query->get($eden['garden']->getObjectId()); @@ -149,16 +153,15 @@ public function testAddUserAfterFetch() $roleAgain->save(); } - /** - * Utilities + * Utilities. */ - public function aclPrivateTo($someone) { $acl = new ParseACL(); $acl->setReadAccess($someone, true); $acl->setWriteAccess($someone, true); + return $acl; } @@ -167,6 +170,7 @@ public function aclPublic() $acl = new ParseACL(); $acl->setPublicReadAccess(true); $acl->setPublicWriteAccess(true); + return $acl; } @@ -175,12 +179,13 @@ public function createUser($username) $user = new ParseUser(); $user->setUsername($username); $user->setPassword($username); + return $user; } public function createEden() { - $eden = array(); + $eden = []; $eden['adam'] = $this->createUser('adam'); $eden['eve'] = $this->createUser('eve'); $eden['snake'] = $this->createUser('snake'); @@ -211,7 +216,5 @@ public function createEden() ParseObject::saveAll([$eden['apple'], $eden['garden']]); return $eden; - } - } diff --git a/tests/ParseSessionStorageTest.php b/tests/ParseSessionStorageTest.php index 91d9535e..dd02cb28 100644 --- a/tests/ParseSessionStorageTest.php +++ b/tests/ParseSessionStorageTest.php @@ -1,15 +1,12 @@ assertEquals('bar', $result['foo3']); $this->assertEquals(3, count($result)); } - } diff --git a/tests/ParseSessionTest.php b/tests/ParseSessionTest.php index 04dfb3ac..4206128a 100644 --- a/tests/ParseSessionTest.php +++ b/tests/ParseSessionTest.php @@ -1,16 +1,13 @@ setExpectedException('Parse\ParseException', 'invalid session token'); ParseUser::become($sessionToken); } - } diff --git a/tests/ParseSubclassTest.php b/tests/ParseSubclassTest.php index 5adf8df5..85776945 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')); } - } diff --git a/tests/ParseTestHelper.php b/tests/ParseTestHelper.php index 554bb8da..6aa9f8d9 100644 --- a/tests/ParseTestHelper.php +++ b/tests/ParseTestHelper.php @@ -1,12 +1,11 @@ each(function(ParseObject $obj) { + $query->each(function (ParseObject $obj) { $obj->destroy(true); }, true); } - } diff --git a/tests/ParseUserTest.php b/tests/ParseUserTest.php index d7340ca2..affdd73a 100644 --- a/tests/ParseUserTest.php +++ b/tests/ParseUserTest.php @@ -1,6 +1,5 @@ setExpectedException( 'Parse\ParseAggregateException', 'Errors during batch save.' ); - ParseObject::saveAll(array($item1, $item2, $user)); + ParseObject::saveAll([$item1, $item2, $user]); } public function testCurrentUser() @@ -283,16 +281,16 @@ public function testContainedInUserArrayQueries() { ParseTestHelper::clearClass(ParseUser::$parseClassName); ParseTestHelper::clearClass("TestObject"); - $userList = array(); + $userList = []; for ($i = 0; $i < 4; $i++) { $user = new ParseUser(); - $user->setUsername('user_num_' . $i); + $user->setUsername('user_num_'.$i); $user->setPassword('password'); - $user->set('email', 'asdf_' . $i . '@example.com'); + $user->set('email', 'asdf_'.$i.'@example.com'); $user->signUp(); $userList[] = $user; } - $messageList = array(); + $messageList = []; for ($i = 0; $i < 5; $i++) { $message = ParseObject::create('TestObject'); $toUser = ($i + 1) % 4; @@ -303,7 +301,7 @@ public function testContainedInUserArrayQueries() $messageList[] = $message; } - $inList = array($userList[0], $userList[3], $userList[3]); + $inList = [$userList[0], $userList[3], $userList[3]]; $query = new ParseQuery("TestObject"); $query->containedIn('from', $inList); $results = $query->find(); @@ -426,5 +424,4 @@ public function testCurrentUserIsNotDirty() $userAgain = ParseUser::getCurrentUser(); $this->assertFalse($userAgain->isKeyDirty('bleep')); } - } diff --git a/tests/bootstrap.php b/tests/bootstrap.php index 182cd572..77038556 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -7,7 +7,7 @@ namespace Parse; -require_once __DIR__ . '/../vendor/autoload.php'; +require_once __DIR__.'/../vendor/autoload.php'; $baseDir = str_replace('/tests', '', __DIR__); define('APPLICATION_PATH', $baseDir);