lithium\net\http\Media::encode PHP Метод

encode() публичный статический Метод

For media types registered in $_handlers which include an 'encode' setting, encodes data according to the specified media type.
См. также: lithium\net\http\Media::type()
public static encode ( mixed $handler, mixed $data, object &$response = null ) : mixed
$handler mixed Specifies the media type into which `$data` will be encoded. This media type must have an `'encode'` setting specified in `Media::$_handlers`. Alternatively, `$type` can be an array, in which case it is used as the type handler configuration. See the `type()` method for information on adding type handlers, and the available configuration keys.
$data mixed Arbitrary data you wish to encode. Note that some encoders can only handle arrays or objects.
$response object A reference to the `Response` object for this dispatch cycle.
Результат mixed Returns the result of `$data`, encoded with the encoding configuration specified by `$type`, the result of which is usually a string.
    public static function encode($handler, $data, &$response = null)
    {
        $params = array('response' => &$response) + compact('handler', 'data');
        return static::_filter(__FUNCTION__, $params, function ($self, $params) {
            $data = $params['data'];
            $handler = $params['handler'];
            $response =& $params['response'];
            $handler = is_array($handler) ? $handler : $self::handlers($handler);
            if (!$handler || empty($handler['encode'])) {
                return null;
            }
            $cast = function ($data) {
                if (!is_object($data)) {
                    return $data;
                }
                return method_exists($data, 'to') ? $data->to('array') : get_object_vars($data);
            };
            if (!isset($handler['cast']) || $handler['cast']) {
                $data = is_object($data) ? $cast($data) : $data;
                $data = is_array($data) ? array_map($cast, $data) : $data;
            }
            $method = $handler['encode'];
            return is_string($method) ? $method($data) : $method($data, $handler, $response);
        });
    }

Usage Example

Пример #1
0
 public function testEncodeRecordSet()
 {
     $data = new RecordSet(array('data' => array(1 => new Record(array('data' => array('id' => 1, 'foo' => 'bar'))), 2 => new Record(array('data' => array('id' => 2, 'foo' => 'baz'))), 3 => new Record(array('data' => array('id' => 3, 'baz' => 'dib'))))));
     $json = '{"1":{"id":1,"foo":"bar"},"2":{"id":2,"foo":"baz"},"3":{"id":3,"baz":"dib"}}';
     $this->assertEqual($json, Media::encode(array('encode' => 'json_encode'), $data));
 }
All Usage Examples Of lithium\net\http\Media::encode