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 60e6cb69..85a84430 100755 --- a/autoload.php +++ b/autoload.php @@ -1,46 +1,44 @@ '; - - // if the file exists, require it - if (file_exists($file)) { - require $file; - } +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/'; + + // 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; + } }); diff --git a/src/Parse/Internal/AddOperation.php b/src/Parse/Internal/AddOperation.php index b8d810ef..219f3832 100755 --- a/src/Parse/Internal/AddOperation.php +++ b/src/Parse/Internal/AddOperation.php @@ -8,102 +8,102 @@ /** * Class AddOperation - FieldOperation for adding object(s) to array fields. * - * @author Fosco Marotto + * @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."); - } - $this->objects = $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."); + } + $this->objects = $objects; + } - /** - * Gets the objects for this operation. - * - * @return mixed - */ - public function getValue() - { - return $this->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 ['__op' => 'Add', - 'objects' => ParseClient::_encode($this->objects, true), ]; - } + /** + * Returns associative array representing encoded operation. + * + * @return array + */ + public function _encode() + { + return ['__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. - * - * @throws ParseException - * - * @return FieldOperation Merged operation. - */ - public function _mergeWithPrevious($previous) - { - if (!$previous) { - return $this; - } - if ($previous instanceof DeleteOperation) { - return new SetOperation($this->objects); - } - if ($previous instanceof SetOperation) { - $oldList = $previous->getValue(); + /** + * Takes a previous operation and returns a merged operation to replace it. + * + * @param FieldOperation $previous Previous operation. + * + * @throws ParseException + * + * @return FieldOperation Merged operation. + */ + public function _mergeWithPrevious($previous) + { + if (!$previous) { + return $this; + } + if ($previous instanceof DeleteOperation) { + return new SetOperation($this->objects); + } + if ($previous instanceof SetOperation) { + $oldList = $previous->getValue(); - return new SetOperation( - array_merge((array) $oldList, (array) $this->objects) - ); - } - if ($previous 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( - 'Operation is invalid after previous operation.' - ); - } + return new SetOperation( + array_merge((array) $oldList, (array) $this->objects) + ); + } + 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); + } } diff --git a/src/Parse/Internal/AddUniqueOperation.php b/src/Parse/Internal/AddUniqueOperation.php index 959ab2e3..76733391 100755 --- a/src/Parse/Internal/AddUniqueOperation.php +++ b/src/Parse/Internal/AddUniqueOperation.php @@ -8,120 +8,120 @@ /** * Class AddUniqueOperation - Operation to add unique objects to an array key. * - * @author Fosco Marotto + * @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."); - } - $this->objects = $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."); + } + $this->objects = $objects; + } - /** - * Returns the values for this operation. - * - * @return mixed - */ - public function getValue() - { - return $this->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 ['__op' => 'AddUnique', - 'objects' => ParseClient::_encode($this->objects, true), ]; - } + /** + * Returns an associative array encoding of this operation. + * + * @return array + */ + public function _encode() + { + return ['__op' => 'AddUnique', + 'objects' => ParseClient::_encode($this->objects, true), ]; + } - /** - * Merge this operation with the previous operation and return the result. - * - * @param FieldOperation $previous Previous Operation. - * - * @throws ParseException - * - * @return FieldOperation Merged Operation. - */ - public function _mergeWithPrevious($previous) - { - if (!$previous) { - return $this; - } - if ($previous instanceof DeleteOperation) { - return new SetOperation($this->objects); - } - if ($previous instanceof SetOperation) { - $oldValue = $previous->getValue(); - $result = $this->_apply($oldValue, null, null); + /** + * Merge this operation with the previous operation and return the result. + * + * @param FieldOperation $previous Previous Operation. + * + * @throws ParseException + * + * @return FieldOperation Merged Operation. + */ + public function _mergeWithPrevious($previous) + { + if (!$previous) { + return $this; + } + if ($previous instanceof DeleteOperation) { + return new SetOperation($this->objects); + } + if ($previous instanceof SetOperation) { + $oldValue = $previous->getValue(); + $result = $this->_apply($oldValue, null, null); - return new SetOperation($result); - } - if ($previous instanceof AddUniqueOperation) { - $oldList = $previous->getValue(); - $result = $this->_apply($oldList, null, null); + return new 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.' - ); - } + return new AddUniqueOperation($result); + } + 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; - } - 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; - } - } - } + /** + * 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; + } + if (!is_array($oldValue)) { + $oldValue = (array) $oldValue; + } + foreach ($this->objects as $object) { + if ($object instanceof ParseObject && $object->getObjectId()) { + if (!$this->isParseObjectInArray($object, $oldValue)) { + $oldValue[] = $object; + } + } elseif (is_object($object)) { + if (!in_array($object, $oldValue, true)) { + $oldValue[] = $object; + } + } else { + if (!in_array($object, $oldValue, true)) { + $oldValue[] = $object; + } + } + } - return $oldValue; - } + return $oldValue; + } private function isParseObjectInArray($parseObject, $oldValue) { diff --git a/src/Parse/Internal/DeleteOperation.php b/src/Parse/Internal/DeleteOperation.php index 509c31cd..a703c80e 100755 --- a/src/Parse/Internal/DeleteOperation.php +++ b/src/Parse/Internal/DeleteOperation.php @@ -5,43 +5,43 @@ /** * Class DeleteOperation - FieldOperation to remove a key from an object. * - * @author Fosco Marotto + * @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 ['__op' => 'Delete']; - } + /** + * Returns an associative array encoding of the current operation. + * + * @return array Associative array encoding the operation. + */ + public function _encode() + { + 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. - * - * @return null - */ - public function _apply($oldValue, $object, $key) - { - return; - } + /** + * 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; + } - /** - * 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; + } } diff --git a/src/Parse/Internal/Encodable.php b/src/Parse/Internal/Encodable.php index 91a0a007..a965c966 100644 --- a/src/Parse/Internal/Encodable.php +++ b/src/Parse/Internal/Encodable.php @@ -6,14 +6,14 @@ * Class Encodable - Interface for Parse Classes which provide an encode * method. * - * @author Fosco Marotto + * @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(); } diff --git a/src/Parse/Internal/FieldOperation.php b/src/Parse/Internal/FieldOperation.php index d8b9b14e..01535072 100755 --- a/src/Parse/Internal/FieldOperation.php +++ b/src/Parse/Internal/FieldOperation.php @@ -5,28 +5,28 @@ /** * Class FieldOperation - Interface for all Parse Field Operations. * - * @author Fosco Marotto + * @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); } diff --git a/src/Parse/Internal/IncrementOperation.php b/src/Parse/Internal/IncrementOperation.php index ab429c72..73726c2a 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. * - * @author Fosco Marotto + * @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; - } + /** + * 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 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 ['__op' => 'Increment', 'amount' => $this->value]; - } + /** + * Get an associative array encoding for this operation. + * + * @return array + */ + public function _encode() + { + 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. - * - * @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.'); - } + /** + * 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. + * + * @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; - } + return $oldValue + $this->value; + } - /** - * Merge this operation with a previous operation and return the - * resulting operation. - * - * @param FieldOperation $previous Previous Operation. - * - * @throws ParseException - * - * @return FieldOperation - */ - public function _mergeWithPrevious($previous) - { - if (!$previous) { - return $this; - } - if ($previous instanceof DeleteOperation) { - return new SetOperation($this->value); - } - if ($previous instanceof SetOperation) { - return new SetOperation($previous->getValue() + $this->value); - } - if ($previous instanceof IncrementOperation) { - return new IncrementOperation( - $previous->getValue() + $this->value - ); - } - throw new ParseException( - 'Operation is invalid after previous operation.' - ); - } + /** + * Merge this operation with a previous operation and return the + * resulting operation. + * + * @param FieldOperation $previous Previous Operation. + * + * @throws ParseException + * + * @return FieldOperation + */ + public function _mergeWithPrevious($previous) + { + if (!$previous) { + return $this; + } + if ($previous instanceof DeleteOperation) { + return new SetOperation($this->value); + } + if ($previous instanceof SetOperation) { + return new SetOperation($previous->getValue() + $this->value); + } + if ($previous instanceof IncrementOperation) { + return new IncrementOperation( + $previous->getValue() + $this->value + ); + } + 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..a3e18a0b 100644 --- a/src/Parse/Internal/ParseRelationOperation.php +++ b/src/Parse/Internal/ParseRelationOperation.php @@ -9,22 +9,22 @@ /** * ParseRelationOperation - A class that is used to manage ParseRelation changes such as object add or remove. * - * @author Mohamed Madbouli + * @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 = []; - /** - * @var array - Array of objects to remove from this relation. - */ - private $relationsToRemove = []; + /** + * @var string - The className of the target objects. + */ + private $targetClassName; + /** + * @var array - Array of objects to add to this relation. + */ + private $relationsToAdd = []; + /** + * @var array - Array of objects to remove from this relation. + */ + private $relationsToRemove = []; public function __construct($objectsToAdd, $objectsToRemove) { @@ -44,238 +44,238 @@ public function __construct($objectsToAdd, $objectsToRemove) } } - /** - * 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 = []; - 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 = []; + 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. - * - * @throws \Exception - * - * @return mixed Result of the operation. - */ - public function _apply($oldValue, $object, $key) - { - if ($oldValue == null) { - return new ParseRelation($object, $key, $this->targetClassName); - } elseif ($oldValue instanceof ParseRelation) { - if ($this->targetClassName != null - && $oldValue->getTargetClass() !== $this->targetClassName) { - throw new \Exception('Related object object must be of class ' - .$this->targetClassName.', but '.$oldValue->getTargetClass() - .' was passed in.'); - } + /** + * 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. + * + * @throws \Exception + * + * @return mixed Result of the operation. + */ + public function _apply($oldValue, $object, $key) + { + if ($oldValue == null) { + return new ParseRelation($object, $key, $this->targetClassName); + } elseif ($oldValue instanceof ParseRelation) { + if ($this->targetClassName != null + && $oldValue->getTargetClass() !== $this->targetClassName) { + throw new \Exception('Related object object must be of class ' + .$this->targetClassName.', but '.$oldValue->getTargetClass() + .' was passed in.'); + } - return $oldValue; - } else { - throw new \Exception("Operation is invalid after previous operation."); - } - } + 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. - * - * @throws \Exception - * - * @return FieldOperation Merged operation result. - */ - 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. + * + * @throws \Exception + * + * @return FieldOperation Merged operation result. + */ + 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); - } - throw new \Exception('Operation is invalid after previous operation.'); - } + return new ParseRelationOperation($newRelationToAdd, + $newRelationToRemove); + } + throw new \Exception('Operation is invalid after previous operation.'); + } - /** - * Returns an associative array encoding of the current operation. - * - * @throws \Exception - * - * @return mixed - */ - public function _encode() - { - $addRelation = []; - $removeRelation = []; - if (!empty($this->relationsToAdd)) { - $addRelation = [ - '__op' => 'AddRelation', - 'objects' => ParseClient::_encode( - self::convertToOneDimensionalArray($this->relationsToAdd), - true - ), - ]; - } - if (!empty($this->relationsToRemove)) { - $removeRelation = [ - '__op' => 'RemoveRelation', - 'objects' => ParseClient::_encode( - self::convertToOneDimensionalArray($this->relationsToRemove), - true - ), - ]; - } - if (!empty($addRelation) && !empty($removeRelation)) { - return [ - '__op' => 'Batch', - 'ops' => [$addRelation, $removeRelation], - ]; - } + /** + * Returns an associative array encoding of the current operation. + * + * @throws \Exception + * + * @return mixed + */ + public function _encode() + { + $addRelation = []; + $removeRelation = []; + if (!empty($this->relationsToAdd)) { + $addRelation = [ + '__op' => 'AddRelation', + 'objects' => ParseClient::_encode( + self::convertToOneDimensionalArray($this->relationsToAdd), + true + ), + ]; + } + if (!empty($this->relationsToRemove)) { + $removeRelation = [ + '__op' => 'RemoveRelation', + 'objects' => ParseClient::_encode( + self::convertToOneDimensionalArray($this->relationsToRemove), + true + ), + ]; + } + if (!empty($addRelation) && !empty($removeRelation)) { + return [ + '__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]; - } - $length = count($array); - for ($i = 0; $i < $length; $i++) { - $exist = false; - foreach ($elements as $element) { - if ($array[$i] == $element) { - $exist = true; - break; - } - } - if ($exist) { - unset($array[$i]); - } - } - $array = array_values($array); - } + /** + * 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]); + } + } + $array = array_values($array); + } - /** - * Convert any array to one dimensional array. - * - * @param array $array - * - * @return 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; - } + /** + * Convert any array to one dimensional array. + * + * @param array $array + * + * @return 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; + } - return $newArray; - } + return $newArray; + } } diff --git a/src/Parse/Internal/RemoveOperation.php b/src/Parse/Internal/RemoveOperation.php index f3c180f5..f38afab9 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. * - * @author Fosco Marotto + * @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."); - } - $this->objects = $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."); + } + $this->objects = $objects; + } - /** - * Gets the objects for this operation. - * - * @return mixed - */ - public function getValue() - { - return $this->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 ['__op' => 'Remove', - 'objects' => ParseClient::_encode($this->objects, true), ]; - } + /** + * Returns associative array representing encoded operation. + * + * @return array + */ + public function _encode() + { + return ['__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. - * - * @throws ParseException - * - * @return FieldOperation Merged operation. - */ - public function _mergeWithPrevious($previous) - { - if (!$previous) { - return $this; - } - if ($previous instanceof DeleteOperation) { - return $previous; - } - if ($previous instanceof SetOperation) { - return new SetOperation( - $this->_apply($previous->getValue(), $this->objects, null) - ); - } - if ($previous instanceof RemoveOperation) { - $oldList = $previous->getValue(); + /** + * Takes a previous operation and returns a merged operation to replace it. + * + * @param FieldOperation $previous Previous operation. + * + * @throws ParseException + * + * @return FieldOperation Merged operation. + */ + public function _mergeWithPrevious($previous) + { + if (!$previous) { + return $this; + } + if ($previous instanceof DeleteOperation) { + return $previous; + } + if ($previous instanceof SetOperation) { + return new SetOperation( + $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.' - ); - } + return new RemoveOperation( + array_merge((array) $oldList, (array) $this->objects) + ); + } + 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 []; - } - $newValue = []; - foreach ($oldValue as $oldObject) { - foreach ($this->objects as $newObject) { - if ($oldObject instanceof ParseObject) { - if ($newObject instanceof ParseObject - && !$oldObject->isDirty() - && $oldObject->getObjectId() == $newObject->getObjectId()) { - // found the object, won't add it. - } else { - $newValue[] = $oldObject; - } - } 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 []; + } + $newValue = []; + foreach ($oldValue as $oldObject) { + foreach ($this->objects as $newObject) { + if ($oldObject instanceof ParseObject) { + if ($newObject instanceof ParseObject + && !$oldObject->isDirty() + && $oldObject->getObjectId() == $newObject->getObjectId()) { + // found the object, won't add it. + } else { + $newValue[] = $oldObject; + } + } else { + if ($oldObject !== $newObject) { + $newValue[] = $oldObject; + } + } + } + } - return $newValue; - } + return $newValue; + } } diff --git a/src/Parse/Internal/SetOperation.php b/src/Parse/Internal/SetOperation.php index aea27255..1c6c7243 100755 --- a/src/Parse/Internal/SetOperation.php +++ b/src/Parse/Internal/SetOperation.php @@ -7,85 +7,85 @@ /** * Class SetOperation - Operation to set a value for an object key. * - * @author Fosco Marotto + * @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); - } + /** + * 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($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; + } } diff --git a/src/Parse/ParseACL.php b/src/Parse/ParseACL.php index f216098d..dfe933b4 100644 --- a/src/Parse/ParseACL.php +++ b/src/Parse/ParseACL.php @@ -12,552 +12,552 @@ * example, any user could read a particular object but only a particular set * of users could write to that object. * - * @author Mohamed Madbouli + * @author Mohamed Madbouli */ class ParseACL implements Encodable { - /* - * @ignore - */ - const PUBLIC_KEY = '*'; - /** - * @var array - - */ - private $permissionsById = []; - /** - * @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. - * - * @throws \Exception - * - * @return ParseACL - * @ignore - */ - public static function _createACLFromJSON($data) - { - $acl = new ParseACL(); - foreach ($data as $id => $permissions) { - if (!is_string($id)) { - throw new \Exception('Tried to create an ACL with an invalid userId.'); - } - foreach ($permissions as $accessType => $value) { - if ($accessType !== 'read' && $accessType !== 'write') { - throw new \Exception( - '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] = []; - } - 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. - * - * @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. - * - * @throws \Exception - */ - public function setWriteAccess($userId, $allowed) - { - if (!$userId) { - throw new \Exception("cannot setWriteAccess for null userId"); - } - $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. - * - * @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. - * - * @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"); - } - $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 - * - * @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()); - } - - /** - * 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); - } - - /** - * 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 - * - * @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()); - } - - /** - * 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."); - } - } - - /** - * 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; - } - } - - /** - * 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; - } + /* + * @ignore + */ + const PUBLIC_KEY = '*'; + /** + * @var array - + */ + private $permissionsById = []; + /** + * @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. + * + * @throws \Exception + * + * @return ParseACL + * @ignore + */ + public static function _createACLFromJSON($data) + { + $acl = new ParseACL(); + foreach ($data as $id => $permissions) { + if (!is_string($id)) { + throw new \Exception('Tried to create an ACL with an invalid userId.'); + } + foreach ($permissions as $accessType => $value) { + if ($accessType !== 'read' && $accessType !== 'write') { + throw new \Exception( + '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] = []; + } + 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. + * + * @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. + * + * @throws \Exception + */ + public function setWriteAccess($userId, $allowed) + { + if (!$userId) { + throw new \Exception("cannot setWriteAccess for null userId"); + } + $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. + * + * @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. + * + * @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"); + } + $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 + * + * @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()); + } + + /** + * 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); + } + + /** + * 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 + * + * @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()); + } + + /** + * 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."); + } + } + + /** + * 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; + } + } + + /** + * 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; + } } diff --git a/src/Parse/ParseAggregateException.php b/src/Parse/ParseAggregateException.php index caa16623..24b0748b 100644 --- a/src/Parse/ParseAggregateException.php +++ b/src/Parse/ParseAggregateException.php @@ -5,32 +5,32 @@ /** * ParseAggregateException - Multiple error condition. * - * @author Fosco Marotto + * @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 = [], $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 = [], $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; + } } diff --git a/src/Parse/ParseAnalytics.php b/src/Parse/ParseAnalytics.php index 40160958..f6a8bff0 100644 --- a/src/Parse/ParseAnalytics.php +++ b/src/Parse/ParseAnalytics.php @@ -7,69 +7,69 @@ /** * ParseAnalytics - Handles sending app-open and custom analytics events. * - * @author Fosco Marotto + * @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 = []) - { - $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.'); - } - } + /** + * 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 = []) + { + $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) - ); - } + return ParseClient::_request( + 'POST', + '/1/events/'.$name, + null, + static::_toSaveJSON($dimensions) + ); + } - /** - * @ignore - */ - public static function _toSaveJSON($data) - { - return json_encode( - [ - 'dimensions' => $data, - ], - JSON_FORCE_OBJECT - ); - } + /** + * @ignore + */ + public static function _toSaveJSON($data) + { + return json_encode( + [ + 'dimensions' => $data, + ], + JSON_FORCE_OBJECT + ); + } } diff --git a/src/Parse/ParseBytes.php b/src/Parse/ParseBytes.php index e2bd517b..4799fbd6 100644 --- a/src/Parse/ParseBytes.php +++ b/src/Parse/ParseBytes.php @@ -5,44 +5,44 @@ /** * ParseBytes - Representation of a Byte array for storage on a Parse Object. * - * @author Fosco Marotto + * @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); + /** + * 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; - } + 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); + /** + * 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; - } + return $bytes; + } private function setBase64Data($base64Data) { @@ -55,22 +55,22 @@ 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 [ - '__type' => 'Bytes', - 'base64' => base64_encode($data), - ]; - } + return [ + '__type' => 'Bytes', + 'base64' => base64_encode($data), + ]; + } } diff --git a/src/Parse/ParseClient.php b/src/Parse/ParseClient.php index 5574c336..716bd2fd 100755 --- a/src/Parse/ParseClient.php +++ b/src/Parse/ParseClient.php @@ -7,411 +7,411 @@ /** * ParseClient - Main class for Parse initialization and communication. * - * @author Fosco Marotto + * @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 - * - * @throws \Exception - * - * @return mixed Encoded results. - * - * @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.'); - } - - 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; - } - - /** - * 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)); + /** + * 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()); + } } } - if (!$data && !is_array($data)) { - return; - } - - 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 = []; - foreach ($data as $key => $value) { - $newDict[$key] = static::_decode($value); - } - - return $newDict; - } - - 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 = []; - 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. - * - * @throws \Exception - * - * @return mixed Result from Parse API Call. - * @ignore - */ - public static function _request($method, $relativeUrl, $sessionToken = null, - $data = null, $useMasterKey = false) - { - if ($data === '[]') { - $data = '{}'; - } - self::assertParseInitialized(); - $headers = self::_getRequestHeaders($sessionToken, $useMasterKey); - - $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; - } - - /** - * 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; - } + /** + * ParseClient::_encode, internal method for encoding object values. + * + * @param mixed $value Value to encode + * @param bool $allowParseObjects Allow nested objects + * + * @throws \Exception + * + * @return mixed Encoded results. + * + * @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.'); + } + + 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; + } + + /** + * 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; + } + + 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 = []; + foreach ($data as $key => $value) { + $newDict[$key] = static::_decode($value); + } + + return $newDict; + } + + 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 = []; + 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. + * + * @throws \Exception + * + * @return mixed Result from Parse API Call. + * @ignore + */ + public static function _request($method, $relativeUrl, $sessionToken = null, + $data = null, $useMasterKey = false) + { + if ($data === '[]') { + $data = '{}'; + } + self::assertParseInitialized(); + $headers = self::_getRequestHeaders($sessionToken, $useMasterKey); + + $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; + } + + /** + * 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.' - ); + 'You must call Parse::initialize() before making any requests.' + ); + } + } + + /** + * @param $sessionToken + * @param $useMasterKey + * + * @return array + * @ignore + */ + 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'; + } + /* + * 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; } - /** - * @param $sessionToken - * @param $useMasterKey - * - * @return array - * @ignore - */ - 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'; - } - /* - * 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/ + /** + * 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 */ - $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 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; + } } diff --git a/src/Parse/ParseCloud.php b/src/Parse/ParseCloud.php index 61274fc3..b0db92ba 100644 --- a/src/Parse/ParseCloud.php +++ b/src/Parse/ParseCloud.php @@ -5,33 +5,33 @@ /** * ParseCloud - Facilitates calling Parse Cloud functions. * - * @author Fosco Marotto + * @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 = [], $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 - ); + /** + * 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 = [], $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']); - } + return ParseClient::_decode($response['result']); + } } diff --git a/src/Parse/ParseConfig.php b/src/Parse/ParseConfig.php index 963b0cc9..43858032 100644 --- a/src/Parse/ParseConfig.php +++ b/src/Parse/ParseConfig.php @@ -5,20 +5,20 @@ /** * ParseConfig - For accessing Parse Config settings. * - * @author Fosco Marotto + * @author Fosco Marotto */ class ParseConfig { - private $currentConfig; - - /** - * Creates. - */ - public function __construct() - { - $result = ParseClient::_request("GET", "/1/config"); - $this->setConfig($result['params']); - } + private $currentConfig; + + /** + * Creates. + */ + public function __construct() + { + $result = ParseClient::_request("GET", "/1/config"); + $this->setConfig($result['params']); + } public function get($key) { diff --git a/src/Parse/ParseException.php b/src/Parse/ParseException.php index acca6526..b4e7a9a3 100644 --- a/src/Parse/ParseException.php +++ b/src/Parse/ParseException.php @@ -5,20 +5,20 @@ /** * ParseException - Wrapper for \Exception class. * - * @author Fosco Marotto + * @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); + } } diff --git a/src/Parse/ParseFile.php b/src/Parse/ParseFile.php index 9cf90920..62485275 100755 --- a/src/Parse/ParseFile.php +++ b/src/Parse/ParseFile.php @@ -5,190 +5,190 @@ /** * ParseFile - Representation of a Parse File object. * - * @author Fosco Marotto + * @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. - * - * @throws ParseException - * - * @return mixed - */ - 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 the data for the file, downloading it if not already present. + * + * @throws ParseException + * + * @return mixed + */ + 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; - } + return $this->data; + } - /** - * Return the URL for the file, if saved. - * - * @return string|null - */ - public function getURL() - { - return $this->url; - } + /** + * 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; - } + /** + * 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."); - } + /** + * 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."); + } - $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); + } - /** - * Return the mimeType for the file, if set. - * - * @return string|null - */ - public function getMimeType() - { - return $this->mimeType; - } + /** + * Return the mimeType for the file, if set. + * + * @return string|null + */ + public function getMimeType() + { + return $this->mimeType; + } - /** - * 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; + /** + * 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 $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"); + /** + * 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); - } + 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; + /** + * 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; - } + return $file; + } - /** - * Encode to associative array representation. - * - * @return string - * @ignore - */ - public function _encode() - { - return [ - '__type' => 'File', - 'url' => $this->url, - 'name' => $this->name, - ]; - } + /** + * Encode to associative array representation. + * + * @return string + * @ignore + */ + public function _encode() + { + return [ + '__type' => 'File', + 'url' => $this->url, + 'name' => $this->name, + ]; + } - /** - * 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']; - } + /** + * 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 true; + } private function upload() { @@ -219,8 +219,8 @@ private function upload() $decoded = json_decode($response, true); if (isset($decoded['error'])) { throw new ParseException($decoded['error'], - isset($decoded['code']) ? $decoded['code'] : 0 - ); + isset($decoded['code']) ? $decoded['code'] : 0 + ); } return $decoded; @@ -250,195 +250,195 @@ private function download() private function getMimeTypeForExtension($extension) { $knownTypes = [ - "ai" => "application/postscript", - "aif" => "audio/x-aiff", - "aifc" => "audio/x-aiff", - "aiff" => "audio/x-aiff", - "asc" => "text/plain", - "atom" => "application/atom+xml", - "au" => "audio/basic", - "avi" => "video/x-msvideo", - "bcpio" => "application/x-bcpio", - "bin" => "application/octet-stream", - "bmp" => "image/bmp", - "cdf" => "application/x-netcdf", - "cgm" => "image/cgm", - "class" => "application/octet-stream", - "cpio" => "application/x-cpio", - "cpt" => "application/mac-compactpro", - "csh" => "application/x-csh", - "css" => "text/css", - "dcr" => "application/x-director", - "dif" => "video/x-dv", - "dir" => "application/x-director", - "djv" => "image/vnd.djvu", - "djvu" => "image/vnd.djvu", - "dll" => "application/octet-stream", - "dmg" => "application/octet-stream", - "dms" => "application/octet-stream", - "doc" => "application/msword", - "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document", - "dotx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.template", - "docm" => "application/vnd.ms-word.document.macroEnabled.12", - "dotm" => "application/vnd.ms-word.template.macroEnabled.12", - "dtd" => "application/xml-dtd", - "dv" => "video/x-dv", - "dvi" => "application/x-dvi", - "dxr" => "application/x-director", - "eps" => "application/postscript", - "etx" => "text/x-setext", - "exe" => "application/octet-stream", - "ez" => "application/andrew-inset", - "gif" => "image/gif", - "gram" => "application/srgs", - "grxml" => "application/srgs+xml", - "gtar" => "application/x-gtar", - "hdf" => "application/x-hdf", - "hqx" => "application/mac-binhex40", - "htm" => "text/html", - "html" => "text/html", - "ice" => "x-conference/x-cooltalk", - "ico" => "image/x-icon", - "ics" => "text/calendar", - "ief" => "image/ief", - "ifb" => "text/calendar", - "iges" => "model/iges", - "igs" => "model/iges", - "jnlp" => "application/x-java-jnlp-file", - "jp2" => "image/jp2", - "jpe" => "image/jpeg", - "jpeg" => "image/jpeg", - "jpg" => "image/jpeg", - "js" => "application/x-javascript", - "kar" => "audio/midi", - "latex" => "application/x-latex", - "lha" => "application/octet-stream", - "lzh" => "application/octet-stream", - "m3u" => "audio/x-mpegurl", - "m4a" => "audio/mp4a-latm", - "m4b" => "audio/mp4a-latm", - "m4p" => "audio/mp4a-latm", - "m4u" => "video/vnd.mpegurl", - "m4v" => "video/x-m4v", - "mac" => "image/x-macpaint", - "man" => "application/x-troff-man", - "mathml" => "application/mathml+xml", - "me" => "application/x-troff-me", - "mesh" => "model/mesh", - "mid" => "audio/midi", - "midi" => "audio/midi", - "mif" => "application/vnd.mif", - "mov" => "video/quicktime", - "movie" => "video/x-sgi-movie", - "mp2" => "audio/mpeg", - "mp3" => "audio/mpeg", - "mp4" => "video/mp4", - "mpe" => "video/mpeg", - "mpeg" => "video/mpeg", - "mpg" => "video/mpeg", - "mpga" => "audio/mpeg", - "ms" => "application/x-troff-ms", - "msh" => "model/mesh", - "mxu" => "video/vnd.mpegurl", - "nc" => "application/x-netcdf", - "oda" => "application/oda", - "ogg" => "application/ogg", - "pbm" => "image/x-portable-bitmap", - "pct" => "image/pict", - "pdb" => "chemical/x-pdb", - "pdf" => "application/pdf", - "pgm" => "image/x-portable-graymap", - "pgn" => "application/x-chess-pgn", - "pic" => "image/pict", - "pict" => "image/pict", - "png" => "image/png", - "pnm" => "image/x-portable-anymap", - "pnt" => "image/x-macpaint", - "pntg" => "image/x-macpaint", - "ppm" => "image/x-portable-pixmap", - "ppt" => "application/vnd.ms-powerpoint", - "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation", - "potx" => "application/vnd.openxmlformats-officedocument.presentationml.template", - "ppsx" => "application/vnd.openxmlformats-officedocument.presentationml.slideshow", - "ppam" => "application/vnd.ms-powerpoint.addin.macroEnabled.12", - "pptm" => "application/vnd.ms-powerpoint.presentation.macroEnabled.12", - "potm" => "application/vnd.ms-powerpoint.template.macroEnabled.12", - "ppsm" => "application/vnd.ms-powerpoint.slideshow.macroEnabled.12", - "ps" => "application/postscript", - "qt" => "video/quicktime", - "qti" => "image/x-quicktime", - "qtif" => "image/x-quicktime", - "ra" => "audio/x-pn-realaudio", - "ram" => "audio/x-pn-realaudio", - "ras" => "image/x-cmu-raster", - "rdf" => "application/rdf+xml", - "rgb" => "image/x-rgb", - "rm" => "application/vnd.rn-realmedia", - "roff" => "application/x-troff", - "rtf" => "text/rtf", - "rtx" => "text/richtext", - "sgm" => "text/sgml", - "sgml" => "text/sgml", - "sh" => "application/x-sh", - "shar" => "application/x-shar", - "silo" => "model/mesh", - "sit" => "application/x-stuffit", - "skd" => "application/x-koan", - "skm" => "application/x-koan", - "skp" => "application/x-koan", - "skt" => "application/x-koan", - "smi" => "application/smil", - "smil" => "application/smil", - "snd" => "audio/basic", - "so" => "application/octet-stream", - "spl" => "application/x-futuresplash", - "src" => "application/x-wais-source", - "sv4cpio" => "application/x-sv4cpio", - "sv4crc" => "application/x-sv4crc", - "svg" => "image/svg+xml", - "swf" => "application/x-shockwave-flash", - "t" => "application/x-troff", - "tar" => "application/x-tar", - "tcl" => "application/x-tcl", - "tex" => "application/x-tex", - "texi" => "application/x-texinfo", - "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", - ]; + "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]; diff --git a/src/Parse/ParseGeoPoint.php b/src/Parse/ParseGeoPoint.php index 300a07e7..25941000 100755 --- a/src/Parse/ParseGeoPoint.php +++ b/src/Parse/ParseGeoPoint.php @@ -5,95 +5,95 @@ /** * ParseGeoPoint - Representation of a Parse GeoPoint object. * - * @author Fosco Marotto + * @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]"); - } - $this->latitude = $lat; - } + /** + * 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; + } - /** - * 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]" - ); - } - $this->longitude = $lon; - } + /** + * 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; + } - /** - * Encode to associative array representation. - * - * @return array - * @ignore - */ - public function _encode() - { - return [ - '__type' => 'GeoPoint', - 'latitude' => $this->latitude, - 'longitude' => $this->longitude, - ]; - } + /** + * Encode to associative array representation. + * + * @return array + * @ignore + */ + public function _encode() + { + return [ + '__type' => 'GeoPoint', + 'latitude' => $this->latitude, + 'longitude' => $this->longitude, + ]; + } } diff --git a/src/Parse/ParseInstallation.php b/src/Parse/ParseInstallation.php index 0ba5a0d6..70793c44 100644 --- a/src/Parse/ParseInstallation.php +++ b/src/Parse/ParseInstallation.php @@ -5,9 +5,9 @@ /** * ParseInstallation - Representation of an Installation stored on Parse. * - * @author Fosco Marotto + * @author Fosco Marotto */ class ParseInstallation extends ParseObject { - public static $parseClassName = "_Installation"; + public static $parseClassName = "_Installation"; } diff --git a/src/Parse/ParseMemoryStorage.php b/src/Parse/ParseMemoryStorage.php index 4c4983d6..fb0881c3 100644 --- a/src/Parse/ParseMemoryStorage.php +++ b/src/Parse/ParseMemoryStorage.php @@ -6,14 +6,14 @@ * ParseMemoryStorage - Uses non-persisted memory for storage. * This is used by default if a PHP Session is not active. * - * @author Fosco Marotto + * @author Fosco Marotto */ class ParseMemoryStorage implements ParseStorageInterface { - /** - * @var array - */ - private $storage = []; + /** + * @var array + */ + private $storage = []; public function set($key, $value) { @@ -42,7 +42,7 @@ public function clear() public function save() { // No action required. - return; + return; } public function getKeys() diff --git a/src/Parse/ParseObject.php b/src/Parse/ParseObject.php index 2eca2467..3d4e7fdd 100755 --- a/src/Parse/ParseObject.php +++ b/src/Parse/ParseObject.php @@ -15,683 +15,683 @@ /** * ParseObject - Representation of an object stored on Parse. * - * @author Fosco Marotto + * @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 = []; - - /** - * 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 = []; - $this->operationSet = []; - $this->estimatedData = []; - $this->dataAvailability = []; - 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. - * - * @throws Exception - * - * @return null - * @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.'); - } - } - - /** - * 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. - * - * @throws \Exception - * - * @return mixed - */ - public function get($key) - { - 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; - } - - /** - * 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()); - } + /** + * @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 = []; + + /** + * 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 = []; + $this->operationSet = []; + $this->estimatedData = []; + $this->dataAvailability = []; + 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. + * + * @throws Exception + * + * @return null + * @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.'); + } + } + + /** + * 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. + * + * @throws \Exception + * + * @return mixed + */ + public function get($key) + { + 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; + } + + /** + * 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; - } - } - }); + if ($object instanceof ParseObject) { + if ($object->isDirty()) { + $result = true; + } + } + }); 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. - * - * @throws Exception - * - * @return null - */ - public function set($key, $value) - { - if (!$key) { - throw new Exception('key may not be null.'); - } - if (is_array($value)) { - throw new Exception( - 'Must use setArray() or setAssociativeArray() for this 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 - */ - 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)); - } - - /** - * 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. - * - * @throws Exception - * - * @return null - */ - public function setAssociativeArray($key, $value) - { - if (!$key) { - throw new Exception('key may not be null.'); - } - if (!is_array($value)) { - throw new Exception( - 'Must use set() for non-array values.' - ); - } - $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. - * - * @throws Exception - * - * @return null - */ - public function remove($key, $value) - { - if (!$key) { - throw new Exception('key may not be null.'); - } - if (!is_array($value)) { - $value = [$value]; - } - $this->_performOperation($key, new RemoveOperation($value)); - } - - /** - * Revert all unsaved operations. - * - * @return null - */ - public function revert() - { - $this->operationSet = []; - $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); - } - } - - /** - * 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; - } elseif (isset($this->estimatedData[$key])) { - unset($this->estimatedData[$key]); - } - - if (isset($this->operationSet[$key])) { - $oldOperations = $this->operationSet[$key]; - $newOperations = $operation->_mergeWithPrevious($oldOperations); - $this->operationSet[$key] = $newOperations; - } else { - $this->operationSet[$key] = $operation; - } - $this->dataAvailability[$key] = true; - } - - /** - * 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; - } + /** + * 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. + * + * @throws Exception + * + * @return null + */ + public function set($key, $value) + { + if (!$key) { + throw new Exception('key may not be null.'); + } + if (is_array($value)) { + throw new Exception( + 'Must use setArray() or setAssociativeArray() for this 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 + */ + 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)); + } + + /** + * 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. + * + * @throws Exception + * + * @return null + */ + public function setAssociativeArray($key, $value) + { + if (!$key) { + throw new Exception('key may not be null.'); + } + if (!is_array($value)) { + throw new Exception( + 'Must use set() for non-array values.' + ); + } + $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. + * + * @throws Exception + * + * @return null + */ + public function remove($key, $value) + { + if (!$key) { + throw new Exception('key may not be null.'); + } + if (!is_array($value)) { + $value = [$value]; + } + $this->_performOperation($key, new RemoveOperation($value)); + } + + /** + * Revert all unsaved operations. + * + * @return null + */ + public function revert() + { + $this->operationSet = []; + $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); + } + } + + /** + * 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; + } elseif (isset($this->estimatedData[$key])) { + unset($this->estimatedData[$key]); + } + + if (isset($this->operationSet[$key])) { + $oldOperations = $this->operationSet[$key]; + $newOperations = $operation->_mergeWithPrevious($oldOperations); + $this->operationSet[$key] = $newOperations; + } else { + $this->operationSet[$key] = $operation; + } + $this->dataAvailability[$key] = true; + } + + /** + * 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); - } - } - - /** - * 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); - } - - /** - * 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 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); + } + } + + /** + * 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); + } + + /** + * 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 = []; + $this->dataAvailability = []; + $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; + } + } + + /** + * 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; + } + } + + /** + * 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 = []; + foreach ($this->serverData as $key => $value) { + $this->estimatedData[$key] = $value; + } + $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; + } } } - $this->serverData = []; - $this->dataAvailability = []; - $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; - } - } - - /** - * 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; - } - } - - /** - * 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 = []; - foreach ($this->serverData as $key => $value) { - $this->estimatedData[$key] = $value; - } - $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; - } - } - } - - /** - * 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; - } - $sessionToken = null; - if (ParseUser::getCurrentUser()) { - $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); - } - 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; - } - } - if (count($errors)) { - throw new ParseAggregateException( - "Errors during batch destroy.", $errors + + /** + * 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; + } + $sessionToken = null; + if (ParseUser::getCurrentUser()) { + $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); + } + ParseClient::_request( + 'DELETE', '/1/classes/'.$this->className. + '/'.$this->objectId, $sessionToken, null, $useMasterKey ); - } - } + } - return; - } + /** + * 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; + } private static function destroyBatch(array $objects, $useMasterKey = false) { @@ -699,457 +699,457 @@ private static function destroyBatch(array $objects, $useMasterKey = false) $errors = []; foreach ($objects as $object) { $data[] = [ - "method" => "DELETE", - "path" => "/1/classes/".$object->getClassName(). - "/".$object->getObjectId(), - ]; + "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(["requests" => $data]), - $useMasterKey - ); + "POST", "/1/batch", $sessionToken, + json_encode(["requests" => $data]), + $useMasterKey + ); foreach ($objects as $key => $object) { if (isset($result[$key]['error'])) { $error = $result[$key]['error']['error']; $code = isset($result[$key]['error']['code']) ? - $result[$key]['error']['code'] : -1; + $result[$key]['error']['code'] : -1; $errors[] = [ - 'error' => $error, - 'code' => $code, - ]; + 'error' => $error, + '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. - * - * @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 = []; - if ($this->objectId) { - $out['objectId'] = $this->objectId; - } - if ($this->createdAt) { - $out['createdAt'] = $this->createdAt; - } - if ($this->updatedAt) { - $out['updatedAt'] = $this->updatedAt; - } - foreach ($this->serverData as $key => $value) { - $out[$key] = $value; - } - foreach ($this->estimatedData as $key => $value) { - if (is_object($value) && $value instanceof \Parse\Internal\Encodable) { - $out[$key] = $value->_encode(); - } elseif (is_array($value)) { - $out[$key] = []; - foreach ($value as $item) { - if (is_object($item) && $item instanceof \Parse\Internal\Encodable) { - $out[$key][] = $item->_encode(); - } else { - $out[$key][] = $item; - } - } - } else { - $out[$key] = $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; - } - 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. - * - * @throws ParseException - * - * @return null - */ - private static function deepSave($target, $useMasterKey = false) - { - $unsavedChildren = []; - $unsavedFiles = []; - static::findUnsavedChildren($target, $unsavedChildren, $unsavedFiles); - $sessionToken = null; - if (ParseUser::getCurrentUser()) { - $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); - } - - foreach ($unsavedFiles as &$file) { - $file->save(); - } - - $objects = []; - // Get the set of unique objects among the children. - foreach ($unsavedChildren as &$obj) { - if (!in_array($obj, $objects, true)) { - $objects[] = $obj; + /** + * 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 = []; + if ($this->objectId) { + $out['objectId'] = $this->objectId; + } + if ($this->createdAt) { + $out['createdAt'] = $this->createdAt; + } + if ($this->updatedAt) { + $out['updatedAt'] = $this->updatedAt; + } + foreach ($this->serverData as $key => $value) { + $out[$key] = $value; } + foreach ($this->estimatedData as $key => $value) { + if (is_object($value) && $value instanceof \Parse\Internal\Encodable) { + $out[$key] = $value->_encode(); + } elseif (is_array($value)) { + $out[$key] = []; + foreach ($value as $item) { + if (is_object($item) && $item instanceof \Parse\Internal\Encodable) { + $out[$key][] = $item->_encode(); + } else { + $out[$key][] = $item; + } + } + } else { + $out[$key] = $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; + } + 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. + * + * @throws ParseException + * + * @return null + */ + private static function deepSave($target, $useMasterKey = false) + { + $unsavedChildren = []; + $unsavedFiles = []; + static::findUnsavedChildren($target, $unsavedChildren, $unsavedFiles); + $sessionToken = null; + if (ParseUser::getCurrentUser()) { + $sessionToken = ParseUser::getCurrentUser()->getSessionToken(); + } + + foreach ($unsavedFiles as &$file) { + $file->save(); + } + + $objects = []; + // Get the set of unique objects among the children. + foreach ($unsavedChildren as &$obj) { + if (!in_array($obj, $objects, true)) { + $objects[] = $obj; + } + } + $remaining = $objects; + + while (count($remaining) > 0) { + $batch = []; + $newRemaining = []; + + foreach ($remaining as $key => &$object) { + if (count($batch) > 40) { + $newRemaining[] = $object; + continue; + } + if ($object->canBeSerialized()) { + $batch[] = $object; + } else { + $newRemaining[] = $object; + } + } + $remaining = $newRemaining; + + if (count($batch) === 0) { + throw new Exception("Tried to save a batch with a cycle."); + } + + $requests = []; + foreach ($batch as $obj) { + $json = $obj->getSaveJSON(); + $method = 'POST'; + $path = '/1/classes/'.$obj->getClassName(); + if ($obj->getObjectId()) { + $path .= '/'.$obj->getObjectId(); + $method = 'PUT'; + } + $requests[] = ['method' => $method, + 'path' => $path, + 'body' => $json, + ]; + } + + if (count($requests) === 1) { + $req = $requests[0]; + $result = ParseClient::_request($req['method'], + $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']) ? + $response['error']['code'] : -1; + $errorCollection[] = [ + 'error' => $error, + 'code' => $code, + 'object' => $obj, + ]; + } else { + $errorCollection[] = [ + 'error' => 'Unknown error in batch save.', + 'code' => -1, + 'object' => $obj, + ]; + } + } + if (count($errorCollection)) { + throw new ParseAggregateException( + "Errors during batch save.", $errorCollection + ); + } + } + } + } + + /** + * 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; + } + } elseif ($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 = []) + { + if ($object instanceof ParseObject) { + if (in_array($object, $seen, true)) { + return; + } + $seen[] = $object; + if ($deep) { + self::traverse( + $deep, $object->estimatedData, $mapFunction, $seen + ); + } + + return $mapFunction($object); + } + 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); + } + + /** + * 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; + } + } + }); + + 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 = []; + $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; + } + + /** + * Gets a Pointer referencing this Object. + * + * @throws \Exception + * + * @return array + * + * @ignore + */ + public function _toPointer() + { + if (!$this->objectId) { + throw new \Exception("Can't serialize an unsaved Parse.Object"); + } + + return [ + '__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); } - $remaining = $objects; - - while (count($remaining) > 0) { - $batch = []; - $newRemaining = []; - - foreach ($remaining as $key => &$object) { - if (count($batch) > 40) { - $newRemaining[] = $object; - continue; - } - if ($object->canBeSerialized()) { - $batch[] = $object; - } else { - $newRemaining[] = $object; - } - } - $remaining = $newRemaining; - - if (count($batch) === 0) { - throw new Exception("Tried to save a batch with a cycle."); - } - - $requests = []; - foreach ($batch as $obj) { - $json = $obj->getSaveJSON(); - $method = 'POST'; - $path = '/1/classes/'.$obj->getClassName(); - if ($obj->getObjectId()) { - $path .= '/'.$obj->getObjectId(); - $method = 'PUT'; - } - $requests[] = ['method' => $method, - 'path' => $path, - 'body' => $json, - ]; - } - - if (count($requests) === 1) { - $req = $requests[0]; - $result = ParseClient::_request($req['method'], - $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']) ? - $response['error']['code'] : -1; - $errorCollection[] = [ - 'error' => $error, - 'code' => $code, - 'object' => $obj, - ]; - } else { - $errorCollection[] = [ - 'error' => 'Unknown error in batch save.', - 'code' => -1, - 'object' => $obj, - ]; - } - } - if (count($errorCollection)) { - throw new ParseAggregateException( - "Errors during batch save.", $errorCollection - ); - } - } - } - } - - /** - * 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; - } - } elseif ($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 = []) - { - if ($object instanceof ParseObject) { - if (in_array($object, $seen, true)) { - return; - } - $seen[] = $object; - if ($deep) { - self::traverse( - $deep, $object->estimatedData, $mapFunction, $seen - ); - } - - return $mapFunction($object); - } - 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); - } - - /** - * 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; - } - } - }); - - 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 = []; - $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; - } - - /** - * Gets a Pointer referencing this Object. - * - * @throws \Exception - * - * @return array - * - * @ignore - */ - public function _toPointer() - { - if (!$this->objectId) { - throw new \Exception("Can't serialize an unsaved Parse.Object"); - } - - return [ - '__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) { @@ -1164,55 +1164,55 @@ private function getACLWithCopy($mayCopy) 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" - ); - } - } - - /** - * 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. - * - * @throws \Exception - * - * @return ParseQuery - */ - 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. + * + * @throws \Exception + * + * @return ParseQuery + */ + 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 43c9c385..fd039ef2 100644 --- a/src/Parse/ParsePush.php +++ b/src/Parse/ParsePush.php @@ -5,63 +5,63 @@ /** * ParsePush - Handles sending push notifications with Parse. * - * @author Fosco Marotto + * @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' - ); - } - } - 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']; - } + /** + * 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 - ); - } + return ParseClient::_request( + 'POST', + '/1/push', + null, + json_encode($data), + $useMasterKey + ); + } } diff --git a/src/Parse/ParseQuery.php b/src/Parse/ParseQuery.php index d8c824fd..7ee96b2e 100755 --- a/src/Parse/ParseQuery.php +++ b/src/Parse/ParseQuery.php @@ -5,812 +5,812 @@ /** * ParseQuery - Handles querying data from Parse. * - * @author Fosco Marotto + * @author Fosco Marotto */ class ParseQuery { - /** - * @var - Class Name for data stored on Parse. - */ - private $className; - /** - * @var array - Where constraints. - */ - private $where = []; - /** - * @var array - Order By keys. - */ - private $orderBy = []; - /** - * @var array - Include nested objects. - */ - private $includes = []; - /** - * @var array - Include certain keys only. - */ - private $selectedKeys = []; - /** - * @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 - * - * @throws ParseException - * - * @return array - */ - public function get($objectId, $useMasterKey = false) - { - $this->equalTo('objectId', $objectId); - $result = $this->first($useMasterKey); - if (empty($result)) { - throw new ParseException("Object not found.", 101); - } - - return $result; - } - - /** - * 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] = []; - } - $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 = []; - 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; - } - - /** - * 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 []; - } - } - - /** - * 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 = []; - 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 = []; - - 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 = []; - - 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. - * - * @throws \Exception If all queries don't have same class. - * - * @return ParseQuery The query that is the OR of the passed in queries. - */ - public static function orQueries($queryObjects) - { - $className = null; - $length = count($queryObjects); - for ($i = 0; $i < $length; $i++) { - if (is_null($className)) { - $className = $queryObjects[$i]->className; - } - if ($className != $queryObjects[$i]->className) { - throw new \Exception("All queries must be for the same class"); - } - } - $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'] = []; - $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 = []; + /** + * @var array - Order By keys. + */ + private $orderBy = []; + /** + * @var array - Include nested objects. + */ + private $includes = []; + /** + * @var array - Include certain keys only. + */ + private $selectedKeys = []; + /** + * @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 + * + * @throws ParseException + * + * @return array + */ + public function get($objectId, $useMasterKey = false) + { + $this->equalTo('objectId', $objectId); + $result = $this->first($useMasterKey); + if (empty($result)) { + throw new ParseException("Object not found.", 101); + } + + return $result; + } + + /** + * 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] = []; + } + $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 = []; + 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; + } + + /** + * 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 []; + } + } + + /** + * 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 = []; + 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 = []; + + 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 = []; + + 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. + * + * @throws \Exception If all queries don't have same class. + * + * @return ParseQuery The query that is the OR of the passed in queries. + */ + public static function orQueries($queryObjects) + { + $className = null; + $length = count($queryObjects); + for ($i = 0; $i < $length; $i++) { + if (is_null($className)) { + $className = $queryObjects[$i]->className; + } + if ($className != $queryObjects[$i]->className) { + throw new \Exception("All queries must be for the same class"); + } + } + $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'] = []; + $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 31df589e..8fcd86ec 100644 --- a/src/Parse/ParseRelation.php +++ b/src/Parse/ParseRelation.php @@ -8,132 +8,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. * - * @author Mohamed Madbouli + * @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; - } + /** + * 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; - } - 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]; - } - $operation = new ParseRelationOperation($objects, null); - $this->targetClassName = $operation->_getTargetClass(); - $this->parent->_performOperation($this->key, $operation); - } + /** + * 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); + } - /** - * 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); - } + /** + * 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); + } - /** - * 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); + /** + * 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; - } + return $query; + } } diff --git a/src/Parse/ParseRole.php b/src/Parse/ParseRole.php index 97dbdbc6..50b5db29 100644 --- a/src/Parse/ParseRole.php +++ b/src/Parse/ParseRole.php @@ -5,97 +5,97 @@ /** * ParseRole - Representation of an access Role. * - * @author Fosco Marotto + * @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); + /** + * 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; - } + return $role; + } - /** - * Returns the role name. - * - * @return string - */ - public function getName() - { - return $this->get("name"); - } + /** + * 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." - ); - } - if (!is_string($name)) { - throw new ParseException( - "A role's name must be a string." - ); - } + /** + * 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); - } + 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"); - } + /** + * 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"); + } - /** - * 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 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"); + } public function save($useMasterKey = false) { if (!$this->getACL()) { throw new ParseException( - "Roles must have an ACL." - ); + "Roles must have an ACL." + ); } if (!$this->getName() || !is_string($this->getName())) { throw new ParseException( - "Roles must have a name." - ); + "Roles must have a name." + ); } return parent::save($useMasterKey); diff --git a/src/Parse/ParseSession.php b/src/Parse/ParseSession.php index 8fa8f41f..ef938dee 100644 --- a/src/Parse/ParseSession.php +++ b/src/Parse/ParseSession.php @@ -5,80 +5,80 @@ /** * ParseSession - Representation of an expiring user session. * - * @author Fosco Marotto + * @author Fosco Marotto */ class ParseSession extends ParseObject { - public static $parseClassName = "_Session"; + public static $parseClassName = "_Session"; 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(); + /** + * 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; - } + 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']); - } - $this->rebuildEstimatedData(); - } + /** + * 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(); + } } diff --git a/src/Parse/ParseSessionStorage.php b/src/Parse/ParseSessionStorage.php index 7aec9c1a..b6450a66 100644 --- a/src/Parse/ParseSessionStorage.php +++ b/src/Parse/ParseSessionStorage.php @@ -5,21 +5,21 @@ /** * ParseSessionStorage - Uses PHP session support for persistent storage. * - * @author Fosco Marotto + * @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.' - ); + 'PHP session_start() must be called first.' + ); } if (!isset($_SESSION[$this->storageKey])) { $_SESSION[$this->storageKey] = []; @@ -52,8 +52,8 @@ public function clear() public function save() { - // No action required. PHP handles persistence for $_SESSION. - return; + // No action required. PHP handles persistence for $_SESSION. + return; } public function getKeys() diff --git a/src/Parse/ParseStorageInterface.php b/src/Parse/ParseStorageInterface.php index 0f24c178..533dde7a 100644 --- a/src/Parse/ParseStorageInterface.php +++ b/src/Parse/ParseStorageInterface.php @@ -5,65 +5,65 @@ /** * ParseStorageInterface - Specifies an interface for implementing persistence. * - * @author Fosco Marotto + * @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(); } diff --git a/src/Parse/ParseUser.php b/src/Parse/ParseUser.php index 5dfb6b5e..27e89439 100644 --- a/src/Parse/ParseUser.php +++ b/src/Parse/ParseUser.php @@ -5,315 +5,315 @@ /** * ParseUser - Representation of a user object stored on Parse. * - * @author Fosco Marotto + * @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"); - } + /** + * 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 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); - } + /** + * 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"); - } + /** + * 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); - } + /** + * 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; - } + /** + * 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." - ); - } - if ($this->getObjectId()) { - throw new ParseException( - "Cannot sign up an already existing user." - ); - } - parent::save(); - $this->handleSaveResult(true); - } + /** + * 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); + } - /** - * Logs in a and returns a valid ParseUser, or throws if invalid. - * - * @param string $username - * @param string $password - * - * @throws ParseException - * - * @return ParseUser - */ - public static function logIn($username, $password) - { - if (!$username) { - throw new ParseException("Cannot log in user with an empty name"); - } - if (!$password) { - throw new ParseException( - "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); + /** + * Logs in a and returns a valid ParseUser, or throws if invalid. + * + * @param string $username + * @param string $password + * + * @throws ParseException + * + * @return ParseUser + */ + public static function logIn($username, $password) + { + if (!$username) { + throw new ParseException("Cannot log in user with an empty name"); + } + if (!$password) { + throw new ParseException( + "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; - } + 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); + /** + * 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; - } + 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. - * - * @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'); - } + /** + * 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'); + } - /** - * 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(); - } + /** + * 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(); + } - /** - * 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; + /** + * 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 = []; - static::$currentUser = $user; + return $userData; + } + if (isset($userData["id"]) && isset($userData["_sessionToken"])) { + $user = ParseUser::create("_User", $userData["id"]); + unset($userData["id"]); + $user->_sessionToken = $userData["_sessionToken"]; + unset($userData["_sessionToken"]); + foreach ($userData as $key => $value) { + $user->set($key, $value); + } + $user->_opSetQueue = []; + static::$currentUser = $user; - return $user; - } + return $user; + } - return; - } + return; + } - /** - * 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. - * - * @throws ParseException - * - * @return null - */ - 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. + * + * @throws ParseException + * + * @return null + */ + 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(['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(['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; + } } diff --git a/tests/IncrementTest.php b/tests/IncrementTest.php index c1ef34f8..bc33070d 100644 --- a/tests/IncrementTest.php +++ b/tests/IncrementTest.php @@ -8,10 +8,10 @@ class IncrementTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } public function tearDown() { @@ -146,8 +146,8 @@ public function testIncrementNonNumber() $obj->set('foo', 'bar'); $obj->save(); $this->setExpectedException( - 'Parse\ParseException', 'Cannot increment a non-number type' - ); + 'Parse\ParseException', 'Cannot increment a non-number type' + ); $obj->increment('foo'); $obj->save(); } @@ -163,8 +163,8 @@ public function testIncrementOnDeletedField() $query->equalTo('objectId', $obj->getObjectId()); $result = $query->first(); $this->assertEquals( - $result->get('yo'), 1, 'Error in increment on deleted field' - ); + $result->get('yo'), 1, 'Error in increment on deleted field' + ); } public function testIncrementEmptyFieldOnFreshObject() @@ -176,8 +176,8 @@ public function testIncrementEmptyFieldOnFreshObject() $query->equalTo('objectId', $obj->getObjectId()); $result = $query->first(); $this->assertEquals($result->get('yo'), 1, - 'Error in increment on empty field of fresh object' - ); + 'Error in increment on empty field of fresh object' + ); } public function testIncrementEmptyField() @@ -195,8 +195,8 @@ public function testIncrementEmptyField() $queryAgain->equalTo('objectId', $objAgain->getObjectId()); $objectAgainTwo = $queryAgain->first(); $this->assertEquals($objectAgainTwo->get('yo'), 2, - 'Error in increment on empty field' - ); + 'Error in increment on empty field' + ); } public function testIncrementEmptyFieldAndTypeConflict() @@ -210,8 +210,8 @@ public function testIncrementEmptyFieldAndTypeConflict() $obj->save(); $objAgain->increment('randomkey'); $this->setExpectedException('Parse\ParseException', - "invalid type for key" - ); + "invalid type for key" + ); $objAgain->save(); } @@ -226,9 +226,9 @@ public function testIncrementEmptyFieldSolidifiesType() $obj->increment('randomkeyagain'); $obj->save(); $this->setExpectedException('Parse\ParseException', - 'invalid type for key randomkeyagain, '. - 'expected number, but got string' - ); + 'invalid type for key randomkeyagain, '. + 'expected number, but got string' + ); $objAgain->save(); } } diff --git a/tests/ParseACLTest.php b/tests/ParseACLTest.php index ae3425b6..925f4744 100644 --- a/tests/ParseACLTest.php +++ b/tests/ParseACLTest.php @@ -9,10 +9,10 @@ class ParseACLTest extends \PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } public function setUp() { diff --git a/tests/ParseAnalyticsTest.php b/tests/ParseAnalyticsTest.php index 309f7dc1..e8fec8e1 100644 --- a/tests/ParseAnalyticsTest.php +++ b/tests/ParseAnalyticsTest.php @@ -6,10 +6,10 @@ class ParseAnalyticsTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } public function tearDown() { @@ -19,8 +19,8 @@ public function 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 ?: []); + // doesn't throw an exception. + $json = ParseAnalytics::_toSaveJSON($params ?: []); $this->assertEquals($expectedJSON, $json); ParseAnalytics::track($event, $params ?: []); } @@ -34,44 +34,44 @@ public function testTrackEvent() public function testFailsOnEventName1() { $this->setExpectedException( - 'Exception', 'A name for the custom event must be provided.' - ); + '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(' '); + '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"); + 'Exception', 'A name for the custom event must be provided.' + ); + ParseAnalytics::track(" \n"); } public function testTrackEventDimensions() { $expected = '{"dimensions":{"foo":"bar","bar":"baz"}}'; $params = [ - 'foo' => 'bar', - 'bar' => 'baz', - ]; + 'foo' => 'bar', + 'bar' => 'baz', + ]; $this->assertAnalyticsValidation('testDimensions', $params, $expected); $date = date(DATE_RFC3339); $expected = '{"dimensions":{"foo":"bar","bar":"baz","someDate":"'. - $date.'"}}'; + $date.'"}}'; $params = [ - 'foo' => 'bar', - 'bar' => 'baz', - 'someDate' => $date, - ]; + 'foo' => 'bar', + 'bar' => 'baz', + 'someDate' => $date, + ]; $this->assertAnalyticsValidation('testDate', $params, $expected); } } diff --git a/tests/ParseBytesTest.php b/tests/ParseBytesTest.php index 88773d8f..7f8d8034 100644 --- a/tests/ParseBytesTest.php +++ b/tests/ParseBytesTest.php @@ -8,10 +8,10 @@ class ParseBytesTest extends \PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } public function setUp() { diff --git a/tests/ParseCloudTest.php b/tests/ParseCloudTest.php index 0ce9b824..cb0e7049 100644 --- a/tests/ParseCloudTest.php +++ b/tests/ParseCloudTest.php @@ -8,10 +8,10 @@ class ParseCloudTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } public function testFunctionsWithObjectParamsFails() { diff --git a/tests/ParseConfigTest.php b/tests/ParseConfigTest.php index 8b6939c0..7fed4208 100644 --- a/tests/ParseConfigTest.php +++ b/tests/ParseConfigTest.php @@ -6,18 +6,18 @@ 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")); + } } diff --git a/tests/ParseFileTest.php b/tests/ParseFileTest.php index 9532459a..281b9d4a 100644 --- a/tests/ParseFileTest.php +++ b/tests/ParseFileTest.php @@ -8,10 +8,10 @@ class ParseFileTest extends \PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } public function tearDown() { @@ -24,16 +24,16 @@ public function testParseFileFactories() $file = ParseFile::_createFromServer("hi.txt", "http://"); $file2 = ParseFile::createFromData("hello", "hi.txt"); $file3 = ParseFile::createFromFile("ParseFileTest.php", - "file.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 - ); + strpos( + $file3->getData(), 'i am looking for myself' + ) !== false + ); } public function testParseFileUpload() @@ -41,8 +41,8 @@ public function testParseFileUpload() $file = ParseFile::createFromData("Fosco", "test.txt"); $file->save(); $this->assertTrue( - strpos($file->getURL(), 'http') !== false - ); + strpos($file->getURL(), 'http') !== false + ); $this->assertNotEquals("test.txt", $file->getName()); } @@ -51,8 +51,8 @@ public function testParseFileDownload() $file = ParseFile::_createFromServer("index.html", "http://example.com"); $data = $file->getData(); $this->assertTrue( - strpos($data, 'Example Domain') !== false - ); + strpos($data, 'Example Domain') !== false + ); } public function testParseFileRoundTrip() diff --git a/tests/ParseGeoBoxTest.php b/tests/ParseGeoBoxTest.php index 93622d39..75959449 100644 --- a/tests/ParseGeoBoxTest.php +++ b/tests/ParseGeoBoxTest.php @@ -9,10 +9,10 @@ class ParseGeoBoxTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } public function setUp() { @@ -42,15 +42,15 @@ public function testGeoBox() $southwestOfSF = new ParseGeoPoint(37.708813, -122.526398); $northeastOfSF = new ParseGeoPoint(37.822802, -122.373962); - // Try a correct query - $query = new ParseQuery('TestObject'); + // 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'); + // Switch order of args, should fail because it crosses the dateline + $query = new ParseQuery('TestObject'); $query->withinGeoBox('location', $northeastOfSF, $southwestOfSF); try { $results = $query->find(); @@ -61,8 +61,8 @@ public function testGeoBox() $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'); + // Switch just longitude, should fail because it crosses the dateline + $query = new ParseQuery('TestObject'); $query->withinGeoBox('location', $southeastOfSF, $northwestOfSF); try { $query->find(); @@ -70,8 +70,8 @@ public function testGeoBox() } catch (ParseException $e) { } - // Switch just the latitude, should fail because it doesnt make sense - $query = new ParseQuery('TestObject'); + // Switch just the latitude, should fail because it doesnt make sense + $query = new ParseQuery('TestObject'); $query->withinGeoBox('location', $northwestOfSF, $southeastOfSF); try { $query->find(); @@ -138,11 +138,11 @@ public function testGeoBoxTooLarge() $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'); + // 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(); diff --git a/tests/ParseGeoPointTest.php b/tests/ParseGeoPointTest.php index 04be1421..ea17c44b 100644 --- a/tests/ParseGeoPointTest.php +++ b/tests/ParseGeoPointTest.php @@ -8,10 +8,10 @@ class ParseGeoPointTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } public function setUp() { @@ -32,19 +32,19 @@ public function testGeoPointBase() $obj->set('name', 'Ferndale'); $obj->save(); - // Non geo query - $query = new ParseQuery('TestObject'); + // 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'); + // 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); + // nearsphere + $point->setLatitude(66.0); $query = new ParseQuery('TestObject'); $query->near('location', $point); $results = $query->find(); @@ -82,34 +82,34 @@ public function testGeoMaxDistance() $obj->save(); } - // baseline all - $query = new ParseQuery('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'); + // 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'); + // all + $query = new ParseQuery('TestObject'); $query->withinRadians('location', $point, 3.14); $results = $query->find(); $this->assertEquals(3, count($results)); - // 2 - $query = new ParseQuery('TestObject'); + // 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'); + // 1 + $query = new ParseQuery('TestObject'); $query->withinRadians('location', $point, 3.14 * 0.25); $results = $query->find(); $this->assertEquals(1, count($results)); @@ -119,84 +119,84 @@ public function testGeoMaxDistance() public function testGeoMaxDistanceWithUnits() { ParseTestHelper::clearClass("PlaceObject"); - // [SAC] 38.52 -121.50 Sacramento,CA - $sacramento = new ParseGeoPoint(38.52, -121.50); + // [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); + // [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); + // [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); + // test point SFO + $point = new ParseGeoPoint(37.6189722, -122.3748889); - // Kilometers - // baseline all - $query = new ParseQuery('PlaceObject'); + // 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'); + // 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'); + // 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'); + // 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'); + // 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'); + // 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'); + // 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'); + // 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'); + // 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 9e6c4f5f..0b48c074 100644 --- a/tests/ParseMemoryStorageTest.php +++ b/tests/ParseMemoryStorageTest.php @@ -7,10 +7,10 @@ class ParseMemoryStorageTest extends PHPUnit_Framework_TestCase { - /** - * @var ParseMemoryStorage - */ - private static $parseStorage; + /** + * @var ParseMemoryStorage + */ + private static $parseStorage; public static function setUpBeforeClass() { @@ -27,8 +27,8 @@ public function tearDown() public function testIsUsingDefaultStorage() { $this->assertTrue( - self::$parseStorage instanceof Parse\ParseMemoryStorage - ); + self::$parseStorage instanceof Parse\ParseMemoryStorage + ); } public function testSetAndGet() diff --git a/tests/ParseObjectTest.php b/tests/ParseObjectTest.php index 96158a24..aec9abfe 100644 --- a/tests/ParseObjectTest.php +++ b/tests/ParseObjectTest.php @@ -8,10 +8,10 @@ class ParseObjectTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } public function tearDown() { @@ -33,7 +33,7 @@ public function testUpdate() $obj->set('foo', 'changed'); $obj->save(); $this->assertEquals($obj->foo, 'changed', - 'Update should have succeeded'); + 'Update should have succeeded'); } public function testSaveCycle() @@ -60,9 +60,9 @@ public function testReturnedObjectIsAParseObject() $query = new ParseQuery('TestObject'); $returnedObject = $query->get($obj->getObjectId()); $this->assertTrue($returnedObject instanceof ParseObject, - 'Returned object was not a ParseObject'); + 'Returned object was not a ParseObject'); $this->assertEquals('bar', $returnedObject->foo, - 'Value of foo was not saved.'); + 'Value of foo was not saved.'); } public function testFetch() @@ -213,8 +213,8 @@ public function testCreatedAtDoesNotChange() $objAgain = ParseObject::create('TestObject', $obj->getObjectId()); $objAgain->fetch(); $this->assertEquals( - $obj->getCreatedAt(), $objAgain->getCreatedAt() - ); + $obj->getCreatedAt(), $objAgain->getCreatedAt() + ); } public function testUpdatedAtGetsUpdated() @@ -224,8 +224,8 @@ public function testUpdatedAtGetsUpdated() $obj->save(); $this->assertNotNull($obj->getUpdatedAt()); $firstUpdate = $obj->getUpdatedAt(); - // Parse is so fast, this test was flaky as the \DateTimes were equal. - sleep(1); + // 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); @@ -239,11 +239,11 @@ public function testCreatedAtIsReasonable() $obj->save(); $endTime = new \DateTime(); $startDiff = abs( - $startTime->getTimestamp() - $obj->getCreatedAt()->getTimestamp() - ); + $startTime->getTimestamp() - $obj->getCreatedAt()->getTimestamp() + ); $endDiff = abs( - $endTime->getTimestamp() - $obj->getCreatedAt()->getTimestamp() - ); + $endTime->getTimestamp() - $obj->getCreatedAt()->getTimestamp() + ); $this->assertLessThan(5000, $startDiff); $this->assertLessThan(5000, $endDiff); } @@ -278,7 +278,7 @@ public function testInvalidKeyName() $obj = ParseObject::create("TestItem"); $obj->set('foo^bar', 'baz'); $this->setExpectedException('Parse\ParseException', - 'invalid field name'); + 'invalid field name'); $obj->save(); } @@ -622,8 +622,8 @@ public function testAddWithAnObject() $parentAgain = $query->get($parent->getObjectId()); $children = $parentAgain->get("children"); $this->assertEquals( - $child->getObjectId(), $children[0]->getObjectId() - ); + $child->getObjectId(), $children[0]->getObjectId() + ); } public function testAddUnique() @@ -734,7 +734,7 @@ public function testEmptyArray() $query = new ParseQuery('TestObject'); $returnedObject = $query->get($obj->getObjectId()); $this->assertTrue(is_array($returnedObject->get('baz')), - 'Value was not stored as an array.'); + 'Value was not stored as an array.'); $this->assertEquals(0, count($returnedObject->get('baz'))); } @@ -776,8 +776,8 @@ public function testObjectIsDirty() $this->assertEquals($value1, $queriedObj->get($key1)); $this->assertFalse($queriedObj->get($key2) === $value2); - // check dirtiness of queried item - $this->assertFalse($queriedObj->isKeyDirty($key1)); + // check dirtiness of queried item + $this->assertFalse($queriedObj->isKeyDirty($key1)); $this->assertFalse($queriedObj->isKeyDirty($key2)); $this->assertFalse($queriedObj->isDirty()); @@ -789,8 +789,8 @@ public function testObjectIsDirty() $this->assertFalse($queriedObj->isKeyDirty($key2)); $this->assertFalse($queriedObj->isDirty()); - // check array - $obj->add($key3, [$value1, $value2, $value1]); + // check array + $obj->add($key3, [$value1, $value2, $value1]); $this->assertTrue($obj->isDirty()); $obj->save(); @@ -822,8 +822,8 @@ public function testObjectIsDirtyWithChildren() $this->assertTrue($obj->isKeyDirty($childKey)); $this->assertTrue($obj->isDirty()); - // check when child is saved, parent should still be dirty - $child->save(); + // check when child is saved, parent should still be dirty + $child->save(); $this->assertFalse($child->isDirty()); $this->assertTrue($obj->isDirty()); @@ -835,8 +835,8 @@ public function testObjectIsDirtyWithChildren() $obj->set($childSimultaneousKey, $childSimultaneous); $this->assertTrue($obj->isDirty()); - // check case with array - $childArray1->set('random', 'random2'); + // check case with array + $childArray1->set('random', 'random2'); $obj->add('arrayKey', [$childArray1, $childArray2]); $this->assertTrue($obj->isDirty()); $childArray1->save(); @@ -848,8 +848,8 @@ public function testObjectIsDirtyWithChildren() $obj->save(); $this->assertFalse($obj->isDirty()); - // check simultaneous save - $obj->save(); + // check simultaneous save + $obj->save(); $this->assertFalse($obj->isDirty()); $this->assertFalse($childSimultaneous->isDirty()); } @@ -877,16 +877,16 @@ public function testEmptyObjectsAndArrays() $saveOpArray = new SetOperation([]); $saveOpAssoc = new SetOperation([], true); $this->assertTrue( - is_array($saveOpArray->_encode()), "Value should be array." - ); + is_array($saveOpArray->_encode()), "Value should be array." + ); $this->assertTrue( - is_object($saveOpAssoc->_encode()), "Value should be object." - ); + is_object($saveOpAssoc->_encode()), "Value should be object." + ); $obj->save(); $obj->setAssociativeArray('obj', [ - 'foo' => 'bar', - 'baz' => 'yay', - ]); + 'foo' => 'bar', + 'baz' => 'yay', + ]); $obj->save(); $query = new ParseQuery('TestObject'); $objAgain = $query->get($obj->getObjectId()); diff --git a/tests/ParsePushTest.php b/tests/ParsePushTest.php index 3582461a..111f1c0e 100644 --- a/tests/ParsePushTest.php +++ b/tests/ParsePushTest.php @@ -7,10 +7,10 @@ class ParsePushTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } public function tearDown() { @@ -20,9 +20,9 @@ public function tearDown() public function testBasicPush() { ParsePush::send([ - 'channels' => [''], - 'data' => ['alert' => 'sample message'], - ]); + 'channels' => [''], + 'data' => ['alert' => 'sample message'], + ]); } public function testPushToQuery() @@ -30,18 +30,18 @@ public function testPushToQuery() $query = ParseInstallation::query(); $query->equalTo('key', 'value'); ParsePush::send([ - 'data' => ['alert' => 'iPhone 5 is out!'], - 'where' => $query, - ]); + 'data' => ['alert' => 'iPhone 5 is out!'], + 'where' => $query, + ]); } public function testPushDates() { ParsePush::send([ - 'data' => ['alert' => 'iPhone 5 is out!'], - 'push_time' => new DateTime(), - 'expiration_time' => new DateTime(), - 'channels' => [], - ]); + 'data' => ['alert' => 'iPhone 5 is out!'], + 'push_time' => new DateTime(), + 'expiration_time' => new DateTime(), + 'channels' => [], + ]); } } diff --git a/tests/ParseQueryTest.php b/tests/ParseQueryTest.php index f714af03..0136b4af 100644 --- a/tests/ParseQueryTest.php +++ b/tests/ParseQueryTest.php @@ -9,10 +9,10 @@ class ParseQueryTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } public function setUp() { @@ -24,30 +24,30 @@ 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 = []; - for ($i = 0; $i < $numberOfObjects; $i++) { - $allObjects[] = $callback($i); - } - ParseObject::saveAll($allObjects); - } + /** + * 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 = []; + 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); + $obj = ParseObject::create('TestObject'); + $obj->set('foo', 'bar'.$i); - return $obj; - }); + return $obj; + }); } public function testBasicQuery() @@ -63,9 +63,9 @@ public function testBasicQuery() $query->equalTo("foo", "baz"); $results = $query->find(); $this->assertEquals(1, count($results), - 'Did not find object.'); + 'Did not find object.'); $this->assertEquals("baz", $results[0]->get("foo"), - 'Did not return the correct object.'); + 'Did not return the correct object.'); } public function testQueryWithLimit() @@ -81,7 +81,7 @@ public function testQueryWithLimit() $query->limit(1); $results = $query->find(); $this->assertEquals(1, count($results), - 'Did not return correct number of objects.'); + 'Did not return correct number of objects.'); } public function testEqualTo() @@ -102,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() @@ -112,9 +112,9 @@ public function testLessThan() $query->lessThan('foo', 'bar1'); $results = $query->find(); $this->assertEquals(count($results), 1, - 'LessThan function did not return correct number of objects.'); + 'LessThan function did not return correct number of objects.'); $this->assertEquals($results[0]->get('foo'), 'bar0', - 'LessThan function did not return the correct object'); + 'LessThan function did not return the correct object'); } public function testLessThanOrEqualTo() @@ -124,9 +124,9 @@ public function testLessThanOrEqualTo() $query->lessThanOrEqualTo('foo', 'bar0'); $results = $query->find(); $this->assertEquals(count($results), 1, - 'LessThanOrEqualTo function did not return correct number of objects.'); + 'LessThanOrEqualTo function did not return correct number of objects.'); $this->assertEquals($results[0]->get('foo'), 'bar0', - 'LessThanOrEqualTo function did not return the correct object.'); + 'LessThanOrEqualTo function did not return the correct object.'); } public function testStartsWithSingle() @@ -136,9 +136,9 @@ public function testStartsWithSingle() $query->startsWith('foo', 'bar0'); $results = $query->find(); $this->assertEquals(count($results), 1, - 'StartsWith function did not return correct number of objects.'); + 'StartsWith function did not return correct number of objects.'); $this->assertEquals($results[0]->get('foo'), 'bar0', - 'StartsWith function did not return the correct object.'); + 'StartsWith function did not return the correct object.'); } public function testStartsWithMultiple() @@ -148,7 +148,7 @@ public function testStartsWithMultiple() $query->startsWith('foo', 'bar'); $results = $query->find(); $this->assertEquals(count($results), 10, - 'StartsWith function did not return correct number of objects.'); + 'StartsWith function did not return correct number of objects.'); } public function testStartsWithMiddle() @@ -158,7 +158,7 @@ public function testStartsWithMiddle() $query->startsWith('foo', 'ar'); $results = $query->find(); $this->assertEquals(count($results), 0, - 'StartsWith function did not return correct number of objects.'); + 'StartsWith function did not return correct number of objects.'); } public function testStartsWithRegexDelimiters() @@ -170,11 +170,11 @@ public function testStartsWithRegexDelimiters() $query->startsWith('foo', 'foob\E'); $results = $query->find(); $this->assertEquals(count($results), 1, - 'StartsWith function did not return correct number of objects.'); + '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.'); + 'StartsWith function did not return correct number of objects.'); } public function testStartsWithRegexDot() @@ -186,15 +186,15 @@ public function testStartsWithRegexDot() $query->startsWith('foo', 'foo(.)*'); $results = $query->find(); $this->assertEquals(count($results), 0, - 'StartsWith function did not return correct number of objects.'); + '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.'); + '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.'); + 'StartsWith function did not return correct number of objects.'); } public function testStartsWithRegexSlash() @@ -206,11 +206,11 @@ public function testStartsWithRegexSlash() $query->startsWith('foo', 'foo/bar'); $results = $query->find(); $this->assertEquals(count($results), 0, - 'StartsWith function did not return correct number of objects.'); + '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.'); + 'StartsWith function did not return correct number of objects.'); } public function testStartsWithRegexQuestionmark() @@ -222,15 +222,15 @@ public function testStartsWithRegexQuestionmark() $query->startsWith('foo', 'foox?bar'); $results = $query->find(); $this->assertEquals(count($results), 0, - 'StartsWith function did not return correct number of objects.'); + '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.'); + '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.'); + 'StartsWith function did not return correct number of objects.'); } public function testGreaterThan() @@ -240,9 +240,9 @@ public function testGreaterThan() $query->greaterThan('foo', 'bar8'); $results = $query->find(); $this->assertEquals(count($results), 1, - 'GreaterThan function did not return correct number of objects.'); + 'GreaterThan function did not return correct number of objects.'); $this->assertEquals($results[0]->get('foo'), 'bar9', - 'GreaterThan function did not return the correct object.'); + 'GreaterThan function did not return the correct object.'); } public function testGreaterThanOrEqualTo() @@ -252,9 +252,9 @@ public function testGreaterThanOrEqualTo() $query->greaterThanOrEqualTo('foo', 'bar9'); $results = $query->find(); $this->assertEquals(count($results), 1, - 'GreaterThanOrEqualTo function did not return correct number of objects.'); + 'GreaterThanOrEqualTo function did not return correct number of objects.'); $this->assertEquals($results[0]->get('foo'), 'bar9', - 'GreaterThanOrEqualTo function did not return the correct object.'); + 'GreaterThanOrEqualTo function did not return the correct object.'); } public function testLessThanOrEqualGreaterThanOrEqual() @@ -265,7 +265,7 @@ public function testLessThanOrEqualGreaterThanOrEqual() $query->greaterThanOrEqualTo('foo', 'bar2'); $results = $query->find(); $this->assertEquals(3, count($results), - 'LessThanGreaterThan did not return correct number of objects.'); + 'LessThanGreaterThan did not return correct number of objects.'); } public function testLessThanGreaterThan() @@ -276,9 +276,9 @@ public function testLessThanGreaterThan() $query->greaterThan('foo', 'bar3'); $results = $query->find(); $this->assertEquals(1, count($results), - 'LessThanGreaterThan did not return correct number of objects.'); + 'LessThanGreaterThan did not return correct number of objects.'); $this->assertEquals('bar4', $results[0]->get('foo'), - 'LessThanGreaterThan did not return the correct object.'); + 'LessThanGreaterThan did not return the correct object.'); } public function testObjectIdEqualTo() @@ -286,35 +286,35 @@ public function testObjectIdEqualTo() ParseTestHelper::clearClass("BoxedNumber"); $boxedNumberArray = []; $this->saveObjects(5, function ($i) use (&$boxedNumberArray) { - $boxedNumber = new ParseObject("BoxedNumber"); - $boxedNumber->set("number", $i); - $boxedNumberArray[] = $boxedNumber; + $boxedNumber = new ParseObject("BoxedNumber"); + $boxedNumber->set("number", $i); + $boxedNumberArray[] = $boxedNumber; - return $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.'); + 'Did not find object.'); $this->assertEquals(4, $results[0]->get("number"), - 'Did not return the correct object.'); + '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); + $boxedNumber = new ParseObject("BoxedNumber"); + $boxedNumber->set("number", $i); - return $boxedNumber; - }); + 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.'); + 'Did not return correct number of objects.'); } public function testFindWithError() @@ -333,9 +333,9 @@ public function testGet() $query = new ParseQuery("TestObject"); $result = $query->get($testObj->getObjectId()); $this->assertEquals($testObj->getObjectId(), $result->getObjectId(), - 'Did not return the correct object.'); + 'Did not return the correct object.'); $this->assertEquals("bar", $result->get("foo"), - 'Did not return the correct object.'); + 'Did not return the correct object.'); } public function testGetError() @@ -367,7 +367,7 @@ public function testFirst() $query->equalTo("foo", "bar"); $result = $query->first(); $this->assertEquals("bar", $result->get("foo"), - 'Did not return the correct object.'); + 'Did not return the correct object.'); } public function testFirstWithError() @@ -387,22 +387,22 @@ public function testFirstNoResult() $query->equalTo("foo", "baz"); $result = $query->first(); $this->assertTrue(empty($result), - 'Did not return correct number of objects.'); + 'Did not return correct number of objects.'); } public function testFirstWithTwoResults() { $this->saveObjects(2, function ($i) { - $testObject = ParseObject::create("TestObject"); - $testObject->set("foo", "bar"); + $testObject = ParseObject::create("TestObject"); + $testObject->set("foo", "bar"); - return $testObject; - }); + 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.'); + 'Did not return the correct object.'); } public function testNotEqualToObject() @@ -411,70 +411,70 @@ public function testNotEqualToObject() ParseTestHelper::clearClass("Item"); $items = []; $this->saveObjects(2, function ($i) use (&$items) { - $items[] = ParseObject::create("Item"); + $items[] = ParseObject::create("Item"); - return $items[$i]; - }); + return $items[$i]; + }); $this->saveObjects(2, function ($i) use ($items) { - $container = ParseObject::create("Container"); - $container->set("item", $items[$i]); + $container = ParseObject::create("Container"); + $container->set("item", $items[$i]); - return $container; - }); + 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.'); + 'Did not return the correct object.'); } public function testSkip() { $this->saveObjects(2, function ($i) { - return ParseObject::create("TestObject"); - }); + 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.'); + 'Did not return the correct object.'); $query->skip(3); $result = $query->find(); $this->assertEquals(0, count($result), - 'Did not return the correct object.'); + 'Did not return the correct object.'); } public function testSkipDoesNotAffectCount() { $this->saveObjects(2, function ($i) { - return ParseObject::create("TestObject"); - }); + return ParseObject::create("TestObject"); + }); $query = new ParseQuery("TestObject"); $count = $query->count(); $this->assertEquals(2, $count, - 'Did not return correct number of objects.'); + 'Did not return correct number of objects.'); $query->skip(1); $this->assertEquals(2, $count, - 'Did not return correct number of objects.'); + 'Did not return correct number of objects.'); $query->skip(3); $this->assertEquals(2, $count, - 'Did not return correct number of objects.'); + '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); + $boxedNumber = ParseObject::create("BoxedNumber"); + $boxedNumber->set("x", $i + 1); - return $boxedNumber; - }); + return $boxedNumber; + }); $query = new ParseQuery("BoxedNumber"); $query->greaterThan("x", 1); $count = $query->count(); $this->assertEquals(2, $count, - 'Did not return correct number of objects.'); + 'Did not return correct number of objects.'); } public function testCountError() @@ -490,19 +490,19 @@ 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]); + $boxedNumber = ParseObject::create("BoxedNumber"); + $boxedNumber->set("number", $numbers[$i]); - return $boxedNumber; - }); + return $boxedNumber; + }); $query = new ParseQuery("BoxedNumber"); $query->ascending("number"); $results = $query->find(); $this->assertEquals(3, count($results), - 'Did not return correct number of objects.'); + '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.'); + 'Did not return the correct object.'); } } @@ -511,33 +511,33 @@ 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]); + $boxedNumber = ParseObject::create("BoxedNumber"); + $boxedNumber->set("number", $numbers[$i]); - return $boxedNumber; - }); + return $boxedNumber; + }); $query = new ParseQuery("BoxedNumber"); $query->descending("number"); $results = $query->find(); $this->assertEquals(3, count($results), - 'Did not return correct number of objects.'); + '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.'); + '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); + $parent = ParseObject::create("ParentObject"); + $child = ParseObject::create("ChildObject"); + $child->set("x", $i); + $parent->set("x", 10 + $i); + $parent->set("child", $child); - return $parent; - }); + return $parent; + }); } public function testMatchesQuery() @@ -552,10 +552,10 @@ public function testMatchesQuery() $results = $query->find(); $this->assertEquals(4, count($results), - 'Did not return correct number of objects.'); + 'Did not return correct number of objects.'); foreach ($results as $parentObj) { $this->assertGreaterThan(15, $parentObj->get("x"), - 'Did not return the correct object.'); + 'Did not return the correct object.'); } } @@ -571,12 +571,12 @@ public function testDoesNotMatchQuery() $results = $query->find(); $this->assertEquals(6, count($results), - 'Did not return the correct object.'); + 'Did not return the correct object.'); foreach ($results as $parentObj) { $this->assertLessThanOrEqual(15, $parentObj->get("x"), - 'Did not return the correct object.'); + 'Did not return the correct object.'); $this->assertGreaterThanOrEqual(10, $parentObj->get("x"), - 'Did not return the correct object.'); + 'Did not return the correct object.'); } } @@ -593,20 +593,20 @@ public function provideTestObjectsForKeyInQuery() $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]); + $restaurant = ParseObject::create("Restaurant"); + $restaurant->set("ratings", $restaurantRatings[$i]); + $restaurant->set("location", $restaurantLocations[$i]); - return $restaurant; - }); + return $restaurant; + }); $this->saveObjects($numberOfPersonObjects, function ($i) use ($personHomeTown, $personName) { - $person = ParseObject::create("Person"); - $person->set("hometown", $personHomeTown[$i]); - $person->set("name", $personName[$i]); + $person = ParseObject::create("Person"); + $person->set("hometown", $personHomeTown[$i]); + $person->set("name", $personName[$i]); - return $person; - }); + return $person; + }); } public function testMatchesKeyInQuery() @@ -620,9 +620,9 @@ public function testMatchesKeyInQuery() $results = $query->find(); $this->assertEquals(1, count($results), - 'Did not return correct number of objects.'); + 'Did not return correct number of objects.'); $this->assertEquals("Bob", $results[0]->get("name"), - 'Did not return the correct object.'); + 'Did not return the correct object.'); } public function testDoesNotMatchKeyInQuery() @@ -636,9 +636,9 @@ public function testDoesNotMatchKeyInQuery() $results = $query->find(); $this->assertEquals(1, count($results), - 'Did not return correct number of objects.'); + 'Did not return correct number of objects.'); $this->assertEquals("Billy", $results[0]->get("name"), - 'Did not return the correct object.'); + 'Did not return the correct object.'); } public function testOrQueries() @@ -653,11 +653,11 @@ public function testOrQueries() $results = $mainQuery->find(); $length = count($results); $this->assertEquals(6, $length, - 'Did not return correct number of objects.'); + '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.'); + $results[$i]->get("foo") > "bar5", + 'Did not return the correct object.'); } } @@ -666,14 +666,14 @@ 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; - }); + $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"); @@ -684,7 +684,7 @@ public function testComplexQueries() $orQuery = ParseQuery::orQueries([$query1, $query2]); $results = $orQuery->find(); $this->assertEquals(3, count($results), - 'Did not return correct number of objects.'); + 'Did not return correct number of objects.'); } public function testEach() @@ -693,26 +693,26 @@ public function testEach() $total = 50; $count = 25; $this->saveObjects($total, function ($i) { - $obj = new ParseObject("Object"); - $obj->set("x", $i + 1); + $obj = new ParseObject("Object"); + $obj->set("x", $i + 1); - return $obj; - }); + return $obj; + }); $query = new ParseQuery("Object"); $query->lessThanOrEqualTo("x", $count); $values = []; $query->each(function ($obj) use (&$values) { - $values[] = $obj->get("x"); - }, 10); + $values[] = $obj->get("x"); + }, 10); $valuesLength = count($values); $this->assertEquals($count, $valuesLength, - 'Did not return correct number of objects.'); + '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.'); + 'Did not return the correct object.'); } } @@ -722,17 +722,17 @@ public function testEachFailsWithOrder() $total = 50; $count = 25; $this->saveObjects($total, function ($i) { - $obj = new ParseObject("Object"); - $obj->set("x", $i + 1); + $obj = new ParseObject("Object"); + $obj->set("x", $i + 1); - return $obj; - }); + return $obj; + }); $query = new ParseQuery("Object"); $query->lessThanOrEqualTo("x", $count); $query->ascending("x"); $this->setExpectedException('\Exception', 'sort'); $query->each(function ($obj) { - }); + }); } public function testEachFailsWithSkip() @@ -740,17 +740,17 @@ public function testEachFailsWithSkip() $total = 50; $count = 25; $this->saveObjects($total, function ($i) { - $obj = new ParseObject("Object"); - $obj->set("x", $i + 1); + $obj = new ParseObject("Object"); + $obj->set("x", $i + 1); - return $obj; - }); + return $obj; + }); $query = new ParseQuery("Object"); $query->lessThanOrEqualTo("x", $count); $query->skip(5); $this->setExpectedException('\Exception', 'skip'); $query->each(function ($obj) { - }); + }); } public function testEachFailsWithLimit() @@ -758,17 +758,17 @@ public function testEachFailsWithLimit() $total = 50; $count = 25; $this->saveObjects($total, function ($i) { - $obj = new ParseObject("Object"); - $obj->set("x", $i + 1); + $obj = new ParseObject("Object"); + $obj->set("x", $i + 1); - return $obj; - }); + return $obj; + }); $query = new ParseQuery("Object"); $query->lessThanOrEqualTo("x", $count); $query->limit(5); $this->setExpectedException('\Exception', 'limit'); $query->each(function ($obj) { - }); + }); } public function testContainsAllNumberArrayQueries() @@ -785,7 +785,7 @@ public function testContainsAllNumberArrayQueries() $query->containsAll("numbers", [1, 2, 3]); $results = $query->find(); $this->assertEquals(1, count($results), - 'Did not return correct number of objects.'); + 'Did not return correct number of objects.'); } public function testContainsAllStringArrayQueries() @@ -802,23 +802,23 @@ public function testContainsAllStringArrayQueries() $query->containsAll("strings", ["a", "b", "c"]); $results = $query->find(); $this->assertEquals(1, count($results), - 'Did not return correct number of objects.'); + 'Did not return correct number of objects.'); } public function testContainsAllDateArrayQueries() { ParseTestHelper::clearClass("DateSet"); $dates1 = [ - new DateTime("2013-02-01T00:00:00Z"), - new DateTime("2013-02-02T00:00:00Z"), - new DateTime("2013-02-03T00:00:00Z"), - new DateTime("2013-02-04T00:00:00Z"), - ]; + 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-01T00:00:00Z"), - new DateTime("2013-02-03T00:00:00Z"), - new DateTime("2013-02-04T00:00:00Z"), - ]; + 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); @@ -829,13 +829,13 @@ public function testContainsAllDateArrayQueries() $query = new ParseQuery("DateSet"); $query->containsAll("dates", [ - new DateTime("2013-02-01T00:00:00Z"), - new DateTime("2013-02-02T00:00:00Z"), - new DateTime("2013-02-03T00:00:00Z"), - ]); + 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.'); + 'Did not return correct number of objects.'); } public function testContainsAllObjectArrayQueries() @@ -843,76 +843,76 @@ public function testContainsAllObjectArrayQueries() ParseTestHelper::clearClass("MessageSet"); $messageList = []; $this->saveObjects(4, function ($i) use (&$messageList) { - $messageList[] = ParseObject::create("TestObject"); - $messageList[$i]->set("i", $i); + $messageList[] = ParseObject::create("TestObject"); + $messageList[$i]->set("i", $i); - return $messageList[$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]] - ); + [$messageList[0], $messageList[1], $messageList[3]] + ); $messageSet2->save(); $query = new ParseQuery("MessageSet"); $query->containsAll("messages", [$messageList[0], $messageList[2]]); $results = $query->find(); $this->assertEquals(1, count($results), - 'Did not return correct number of objects.'); + 'Did not return correct number of objects.'); } public function testContainedInObjectArrayQueries() { $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; - }); + $message = ParseObject::create("TestObject"); + if ($i > 0) { + $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), - 'Did not return correct number of objects.'); + '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); + $boxedNumber = ParseObject::create("BoxedNumber"); + $boxedNumber->set("number", $i); - return $boxedNumber; - }); + 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.'); + '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); + $boxedNumber = ParseObject::create("BoxedNumber"); + $boxedNumber->set("number", $i); - return $boxedNumber; - }); + 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.'); + 'Did not return correct number of objects.'); } public function testObjectIdContainedInQueries() @@ -920,47 +920,47 @@ public function testObjectIdContainedInQueries() ParseTestHelper::clearClass("BoxedNumber"); $objects = []; $this->saveObjects(5, function ($i) use (&$objects) { - $boxedNumber = ParseObject::create("BoxedNumber"); - $boxedNumber->set("number", $i); - $objects[] = $boxedNumber; + $boxedNumber = ParseObject::create("BoxedNumber"); + $boxedNumber->set("number", $i); + $objects[] = $boxedNumber; - return $boxedNumber; - }); + return $boxedNumber; + }); $query = new ParseQuery("BoxedNumber"); $query->containedIn("objectId", [$objects[2]->getObjectId(), - $objects[3]->getObjectId(), - $objects[0]->getObjectId(), - "NONSENSE", ] - ); + $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.'); + 'Did not return correct number of objects.'); $this->assertEquals(0, $results[0]->get("number"), - 'Did not return the correct object.'); + 'Did not return the correct object.'); $this->assertEquals(2, $results[1]->get("number"), - 'Did not return the correct object.'); + 'Did not return the correct object.'); $this->assertEquals(3, $results[2]->get("number"), - 'Did not return the correct object.'); + 'Did not return the correct object.'); } public function testStartsWith() { $someAscii = "\\E' !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTU". - "VWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'"; + "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 = ParseObject::create("TestObject"); + $obj->set("myString", $prefixes[$i].$someAscii.$suffixes[$i]); - return $obj; - }); + 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.'); + 'Did not return correct number of objects.'); } public function provideTestObjectsForOrderBy() @@ -984,12 +984,12 @@ public function testOrderByAscNumberThenDescString() $results = $query->find(); $expected = [[1, 'b'], [2, 'd'], [3, 'c'], [3, 'a']]; $this->assertEquals(4, count($results), - 'Did not return correct number of objects.'); + '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.'); + 'Did not return the correct object.'); $this->assertEquals($expected[$i][1], $results[$i]->get('string'), - 'Did not return the correct object.'); + 'Did not return the correct object.'); } } @@ -1001,12 +1001,12 @@ public function testOrderByDescNumberThenAscString() $results = $query->find(); $expected = [[3, 'a'], [3, 'c'], [2, 'd'], [1, 'b']]; $this->assertEquals(4, count($results), - 'Did not return correct number of objects.'); + '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.'); + 'Did not return the correct object.'); $this->assertEquals($expected[$i][1], $results[$i]->get('string'), - 'Did not return the correct object.'); + 'Did not return the correct object.'); } } @@ -1018,12 +1018,12 @@ public function testOrderByDescNumberAndString() $results = $query->find(); $expected = [[3, 'c'], [3, 'a'], [2, 'd'], [1, 'b']]; $this->assertEquals(4, count($results), - 'Did not return correct number of objects.'); + '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.'); + 'Did not return the correct object.'); $this->assertEquals($expected[$i][1], $results[$i]->get('string'), - 'Did not return the correct object.'); + 'Did not return the correct object.'); } } @@ -1044,11 +1044,11 @@ public function testOrderByCreatedAtAsc() $query->find(); $results = $query->find(); $this->assertEquals(4, count($results), - 'Did not return correct number of objects.'); + '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.'); + 'Did not return the correct object.'); } } @@ -1060,11 +1060,11 @@ public function testOrderByCreatedAtDesc() $query->find(); $results = $query->find(); $this->assertEquals(4, count($results), - 'Did not return correct number of objects.'); + '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.'); + 'Did not return the correct object.'); } } @@ -1073,23 +1073,23 @@ public function testOrderByUpdatedAtAsc() $numbers = [3, 1, 2]; $objects = []; $this->saveObjects(3, function ($i) use ($numbers, &$objects) { - $obj = ParseObject::create("TestObject"); - $obj->set('number', $numbers[$i]); - $objects[] = $obj; + $obj = ParseObject::create("TestObject"); + $obj->set('number', $numbers[$i]); + $objects[] = $obj; - return $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.'); + '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.'); + 'Did not return the correct object.'); } } @@ -1098,23 +1098,23 @@ public function testOrderByUpdatedAtDesc() $numbers = [3, 1, 2]; $objects = []; $this->saveObjects(3, function ($i) use ($numbers, &$objects) { - $obj = ParseObject::create("TestObject"); - $obj->set('number', $numbers[$i]); - $objects[] = $obj; + $obj = ParseObject::create("TestObject"); + $obj->set('number', $numbers[$i]); + $objects[] = $obj; - return $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.'); + '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.'); + 'Did not return the correct object.'); } } @@ -1128,7 +1128,7 @@ public function testSelectKeysQuery() $query->select('foo'); $result = $query->first(); $this->assertEquals('baz', $result->get('foo'), - 'Did not return the correct object.'); + 'Did not return the correct object.'); $this->setExpectedException('\Exception', 'Call fetch()'); $result->get('bar'); } @@ -1139,9 +1139,9 @@ public function testGetWithoutError() $obj->set('foo', 'baz'); $obj->set('bar', 1); $this->assertEquals('baz', $obj->get('foo'), - 'Did not return the correct object.'); + 'Did not return the correct object.'); $this->assertEquals(1, $obj->get('bar'), - 'Did not return the correct object.'); + 'Did not return the correct object.'); $obj->save(); } public function testSelectKeysQueryArrayArg() @@ -1154,91 +1154,91 @@ public function testSelectKeysQueryArrayArg() $query->select(['foo', 'bar']); $result = $query->first(); $this->assertEquals('baz', $result->get('foo'), - 'Did not return the correct object.'); + 'Did not return the correct object.'); $this->assertEquals(1, $result->get('bar'), - 'Did not return the correct object.'); + '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; - }); + $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.'); + '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; - }); + $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.'); + '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; - }); + $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.'); + '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; - }); + $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.'); + 'Did not return correct number of objects.'); } public function testDoNotIncludeRelation() @@ -1271,9 +1271,9 @@ public function testIncludeRelation() $query->includeKey('child'); $result = $query->first(); $this->assertEquals($result->get('y'), $result->get('child')->get('x'), - 'Object should be fetched.'); + 'Object should be fetched.'); $this->assertEquals(1, $result->get('child')->get('x'), - 'Object should be fetched.'); + 'Object should be fetched.'); } public function testNestedIncludeRelation() @@ -1297,10 +1297,10 @@ public function testNestedIncludeRelation() $query->includeKey('parent.child'); $result = $query->first(); $this->assertEquals($result->get('z'), $result->get('parent')->get('y'), - 'Object should be fetched.'); + 'Object should be fetched.'); $this->assertEquals($result->get('z'), - $result->get('parent')->get('child')->get('x'), - 'Object should be fetched.'); + $result->get('parent')->get('child')->get('x'), + 'Object should be fetched.'); } public function testIncludeArrayRelation() @@ -1309,12 +1309,12 @@ public function testIncludeArrayRelation() ParseTestHelper::clearClass("Parent"); $children = []; $this->saveObjects(5, function ($i) use (&$children) { - $child = ParseObject::create("Child"); - $child->set('x', $i); - $children[] = $child; + $child = ParseObject::create("Child"); + $child->set('x', $i); + $children[] = $child; - return $child; - }); + return $child; + }); $parent = ParseObject::create("Parent"); $parent->setArray('children', $children); $parent->save(); @@ -1323,12 +1323,12 @@ public function testIncludeArrayRelation() $query->includeKey('children'); $result = $query->find(); $this->assertEquals(1, count($result), - 'Did not return correct number of objects.'); + '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.'); + 'Object should be fetched.'); } } @@ -1340,7 +1340,7 @@ public function testIncludeWithNoResults() $query->includeKey('children'); $result = $query->find(); $this->assertEquals(0, count($result), - 'Did not return correct number of objects.'); + 'Did not return correct number of objects.'); } public function testIncludeWithNonExistentKey() @@ -1355,7 +1355,7 @@ public function testIncludeWithNonExistentKey() $query->includeKey('child'); $results = $query->find(); $this->assertEquals(1, count($results), - 'Did not return correct number of objects.'); + 'Did not return correct number of objects.'); } public function testIncludeOnTheWrongKeyType() @@ -1371,7 +1371,7 @@ public function testIncludeOnTheWrongKeyType() $this->setExpectedException('Parse\ParseException', '', 102); $results = $query->find(); $this->assertEquals(1, count($results), - 'Did not return correct number of objects.'); + 'Did not return correct number of objects.'); } public function testIncludeWhenOnlySomeObjectsHaveChildren() @@ -1382,29 +1382,29 @@ public function testIncludeWhenOnlySomeObjectsHaveChildren() $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 = ParseObject::create('Parent'); + $parent->set('num', $i); + if ($i & 1) { + $parent->set('child', $child); + } - return $parent; - }); + 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.'); + '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'); + 'Object should be fetched'); } else { $this->assertEquals(null, $results[$i]->get('child'), - 'Should not have child'); + 'Should not have child'); } } } @@ -1430,9 +1430,9 @@ public function testIncludeMultipleKeys() $query->includeKey(['foofoo', 'barbar']); $result = $query->first(); $this->assertEquals('oof', $result->get('foofoo')->get('rev'), - 'Object should be fetched'); + 'Object should be fetched'); $this->assertEquals('rab', $result->get('barbar')->get('rev'), - 'Object should be fetched'); + 'Object should be fetched'); } public function testEqualToObject() @@ -1441,37 +1441,37 @@ public function testEqualToObject() ParseTestHelper::clearClass("Container"); $items = []; $this->saveObjects(2, function ($i) use (&$items) { - $items[] = ParseObject::create("Item"); - $items[$i]->set('x', $i); + $items[] = ParseObject::create("Item"); + $items[$i]->set('x', $i); - return $items[$i]; - }); + return $items[$i]; + }); $this->saveObjects(2, function ($i) use ($items) { - $container = ParseObject::create("Container"); - $container->set('item', $items[$i]); + $container = ParseObject::create("Container"); + $container->set('item', $items[$i]); - return $container; - }); + 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.'); + 'Did not return the correct object.'); } public function testEqualToNull() { $this->saveObjects(10, function ($i) { - $obj = ParseObject::create('TestObject'); - $obj->set('num', $i); + $obj = ParseObject::create('TestObject'); + $obj->set('num', $i); - return $obj; - }); + 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.'); + 'Did not return correct number of objects.'); } public function provideTimeTestObjects() @@ -1479,14 +1479,14 @@ public function provideTimeTestObjects() ParseTestHelper::clearClass("TimeObject"); $items = []; $this->saveObjects(3, function ($i) use (&$items) { - $timeObject = ParseObject::create('TimeObject'); - $timeObject->set('name', 'item'.$i); - $timeObject->set('time', new DateTime()); - sleep(1); - $items[] = $timeObject; + $timeObject = ParseObject::create('TimeObject'); + $timeObject->set('name', 'item'.$i); + $timeObject->set('time', new DateTime()); + sleep(1); + $items[] = $timeObject; - return $timeObject; - }); + return $timeObject; + }); return $items; } @@ -1498,7 +1498,7 @@ public function testTimeEquality() $query->equalTo('time', $items[1]->get('time')); $results = $query->find(); $this->assertEquals(1, count($results), - 'Did not return correct number of objects.'); + 'Did not return correct number of objects.'); $this->assertEquals('item1', $results[0]->get('name')); } @@ -1509,7 +1509,7 @@ public function testTimeLessThan() $query->lessThan('time', $items[2]->get('time')); $results = $query->find(); $this->assertEquals(2, count($results), - 'Did not return correct number of objects.'); + 'Did not return correct number of objects.'); } public function testRestrictedGetFailsWithoutMasterKey() diff --git a/tests/ParseRelationTest.php b/tests/ParseRelationTest.php index c0aad55d..720c0fed 100644 --- a/tests/ParseRelationTest.php +++ b/tests/ParseRelationTest.php @@ -7,42 +7,42 @@ class ParseRelationTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } + 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 = []; - for ($i = 0; $i < $numberOfObjects; $i++) { - $allObjects[] = $callback($i); - } - ParseObject::saveAll($allObjects); - } + /** + * 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 = []; + for ($i = 0; $i < $numberOfObjects; $i++) { + $allObjects[] = $callback($i); + } + ParseObject::saveAll($allObjects); + } public function testParseRelations() { $children = []; $this->saveObjects(10, function ($i) use (&$children) { - $child = ParseObject::create('ChildObject'); - $child->set('x', $i); - $children[] = $child; + $child = ParseObject::create('ChildObject'); + $child->set('x', $i); + $children[] = $child; - return $child; - }); + return $child; + }); $parent = ParseObject::create('ParentObject'); $relation = $parent->getRelation('children'); $relation->add($children[0]); @@ -73,11 +73,11 @@ public function testParseRelations() $relation->remove($children[5]); $relation->add([ - $children[5], - $children[6], - $children[7], - $children[8], - ]); + $children[5], + $children[6], + $children[7], + $children[8], + ]); $parent->save(); $results = $relation->getQuery()->find(); @@ -101,30 +101,30 @@ public function testQueriesOnRelationFields() { $children = []; $this->saveObjects(10, function ($i) use (&$children) { - $child = ParseObject::create('ChildObject'); - $child->set('x', $i); - $children[] = $child; + $child = ParseObject::create('ChildObject'); + $child->set('x', $i); + $children[] = $child; - return $child; - }); + return $child; + }); $parent = ParseObject::create('ParentObject'); $parent->set('x', 4); $relation = $parent->getRelation('children'); $relation->add([ - $children[0], - $children[1], - $children[2], - ]); + $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], - ]); + $children[4], + $children[5], + $children[6], + ]); $parent2->save(); $query = new ParseQuery('ParentObject'); $query->containedIn('children', [$children[4], $children[9]]); diff --git a/tests/ParseRoleTest.php b/tests/ParseRoleTest.php index 92b166af..a3672d18 100644 --- a/tests/ParseRoleTest.php +++ b/tests/ParseRoleTest.php @@ -10,10 +10,10 @@ class ParseRoleTest extends \PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } public function setUp() { @@ -153,17 +153,17 @@ public function testAddUserAfterFetch() $roleAgain->save(); } - /** - * Utilities. - */ - public function aclPrivateTo($someone) - { - $acl = new ParseACL(); - $acl->setReadAccess($someone, true); - $acl->setWriteAccess($someone, true); + /** + * Utilities. + */ + public function aclPrivateTo($someone) + { + $acl = new ParseACL(); + $acl->setReadAccess($someone, true); + $acl->setWriteAccess($someone, true); - return $acl; - } + return $acl; + } public function aclPublic() { @@ -196,8 +196,8 @@ public function createEden() $eden['humans']->getUsers()->add($eden['adam']); $eden['humans']->getUsers()->add($eden['eve']); $eden['creatures'] = ParseRole::createRole( - "creatures", $this->aclPublic() - ); + "creatures", $this->aclPublic() + ); $eden['creatures']->getUsers()->add($eden['snake']); ParseObject::saveAll([$eden['humans'], $eden['creatures']]); $eden['edenkin'] = ParseRole::createRole("edenkin", $this->aclPublic()); diff --git a/tests/ParseSessionStorageTest.php b/tests/ParseSessionStorageTest.php index efa97639..dd02cb28 100644 --- a/tests/ParseSessionStorageTest.php +++ b/tests/ParseSessionStorageTest.php @@ -7,10 +7,10 @@ class ParseSessionStorageTest extends PHPUnit_Framework_TestCase { - /** - * @var ParseSessionStorage - */ - private static $parseStorage; + /** + * @var ParseSessionStorage + */ + private static $parseStorage; public static function setUpBeforeClass() { diff --git a/tests/ParseSessionTest.php b/tests/ParseSessionTest.php index 59afc240..4206128a 100644 --- a/tests/ParseSessionTest.php +++ b/tests/ParseSessionTest.php @@ -8,12 +8,12 @@ class ParseSessionTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - ParseTestHelper::clearClass(ParseUser::$parseClassName); - ParseTestHelper::clearClass(ParseSession::$parseClassName); - } + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + ParseTestHelper::clearClass(ParseUser::$parseClassName); + ParseTestHelper::clearClass(ParseSession::$parseClassName); + } public function tearDown() { diff --git a/tests/ParseSubclassTest.php b/tests/ParseSubclassTest.php index ecac3483..85776945 100644 --- a/tests/ParseSubclassTest.php +++ b/tests/ParseSubclassTest.php @@ -7,10 +7,10 @@ class ParseSubclassTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - } + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + } public function tearDown() { diff --git a/tests/ParseTestHelper.php b/tests/ParseTestHelper.php index e3eee7ab..6aa9f8d9 100644 --- a/tests/ParseTestHelper.php +++ b/tests/ParseTestHelper.php @@ -6,17 +6,17 @@ 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() { @@ -26,7 +26,7 @@ public static function clearClass($class) { $query = new ParseQuery($class); $query->each(function (ParseObject $obj) { - $obj->destroy(true); - }, true); + $obj->destroy(true); + }, true); } } diff --git a/tests/ParseUserTest.php b/tests/ParseUserTest.php index 78e0ff4e..affdd73a 100644 --- a/tests/ParseUserTest.php +++ b/tests/ParseUserTest.php @@ -8,11 +8,11 @@ class ParseUserTest extends PHPUnit_Framework_TestCase { - public static function setUpBeforeClass() - { - ParseTestHelper::setUp(); - ParseTestHelper::clearClass(ParseUser::$parseClassName); - } + public static function setUpBeforeClass() + { + ParseTestHelper::setUp(); + ParseTestHelper::clearClass(ParseUser::$parseClassName); + } public function tearDown() { @@ -89,8 +89,8 @@ public function testCannotAlterOtherUser() $this->assertEquals(ParseUser::getCurrentUser(), $otherUser); $this->setExpectedException( - 'Parse\ParseException', 'UserCannotBeAlteredWithoutSession' - ); + 'Parse\ParseException', 'UserCannotBeAlteredWithoutSession' + ); $user->setUsername('changed'); $user->save(); } @@ -110,8 +110,8 @@ public function testCannotDeleteOtherUser() $this->assertEquals(ParseUser::getCurrentUser(), $otherUser); $this->setExpectedException( - 'Parse\ParseException', 'UserCannotBeAlteredWithoutSession' - ); + 'Parse\ParseException', 'UserCannotBeAlteredWithoutSession' + ); $user->destroy(); } @@ -142,8 +142,8 @@ public function testCannotSaveAllWithOtherUser() $item2->set('num', 2); $user->setUsername('changed'); $this->setExpectedException( - 'Parse\ParseAggregateException', 'Errors during batch save.' - ); + 'Parse\ParseAggregateException', 'Errors during batch save.' + ); ParseObject::saveAll([$item1, $item2, $user]); } @@ -229,8 +229,8 @@ public function testPasswordReset() public function testPasswordResetFails() { $this->setExpectedException( - 'Parse\ParseException', 'no user found with email' - ); + 'Parse\ParseException', 'no user found with email' + ); ParseUser::requestPasswordReset('non_existent@example.com'); } @@ -256,8 +256,8 @@ public function testUserAssociations() $this->assertEquals($userAgain->getObjectId(), $user->getObjectId()); $this->assertEquals( - $userAgain->get('child')->getObjectId(), $child->getObjectId() - ); + $userAgain->get('child')->getObjectId(), $child->getObjectId() + ); } public function testUserQueries() diff --git a/tests/bootstrap.php b/tests/bootstrap.php index b2634320..77038556 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -1,16 +1,13 @@ \ 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!'); + } });