1: <?php
2: /**
3: * This file is part of the Pipeliner API client library for PHP
4: *
5: * Copyright 2014 Pipelinersales, Inc. All Rights Reserved.
6: * For the full license information, see the attached LICENSE file.
7: */
8:
9: namespace PipelinerSales\ApiClient\Query;
10:
11: /**
12: * A convenient wrapper for generating the sort string for queries.
13: *
14: * For details, see the {@link http://workspace.pipelinersales.com/community/api/data/Querying_rest.html
15: * API documentation}.
16: *
17: * All the magic methods can also be called statically, e.g.
18: * <code>
19: * Sort::asc('NAME')->desc('MODIFIED')
20: * </code>
21: *
22: * @method static Sort asc(string $fieldName) sorts by a field in ascending order
23: * @method static Sort desc(string $fieldName) sorts by a field in descending order
24: * @method static Sort raw(string $sortString) appends a separator (|) followed
25: * by a raw string to the current sort string
26: */
27: class Sort
28: {
29:
30: private $sortString = '';
31:
32: /**
33: * Constructor, optionally copies an existing sort string into this object.
34: * @param mixed $sort either a sort string or another Sort object
35: */
36: public function __construct($sort = '')
37: {
38: if ($sort instanceof Sort) {
39: $this->sortString = $sort->sortString;
40: } else {
41: $this->raw($sort);
42: }
43: }
44:
45: public function __call($name, $arguments)
46: {
47: if ($name === 'asc' or $name === 'desc' or $name === 'raw') {
48: if (!empty($this->sortString)) {
49: $this->sortString .= '|';
50: }
51:
52: if ($name === 'desc') {
53: $this->sortString .= '-';
54: }
55:
56: $this->sortString .= $arguments[0];
57: return $this;
58: }
59: throw new \BadMethodCallException('Call to a non-existent method \'' . $name . '\'');
60: }
61:
62: public static function __callStatic($name, $arguments)
63: {
64: if ($name === 'asc' or $name === 'desc' or $name === 'raw') {
65: $sort = new Sort();
66: $sort->$name($arguments[0]);
67: return $sort;
68: }
69: throw new \BadMethodCallException('Call to a non-existent static method \'' . $name . '\'');
70: }
71:
72: /**
73: * Returns the resulting sort string.
74: * @return string
75: */
76: public function getString()
77: {
78: return $this->sortString;
79: }
80: }
81: