Skip to content

Rebuilding Format class #3149

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 16 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 3 additions & 30 deletions app/Config/Format.php
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
<?php namespace Config;
<?php

namespace Config;

use CodeIgniter\Config\BaseConfig;

Expand Down Expand Up @@ -39,33 +41,4 @@ class Format extends BaseConfig
'application/xml' => \CodeIgniter\Format\XMLFormatter::class,
'text/xml' => \CodeIgniter\Format\XMLFormatter::class,
];

//--------------------------------------------------------------------

/**
* A Factory method to return the appropriate formatter for the given mime type.
*
* @param string $mime
*
* @return \CodeIgniter\Format\FormatterInterface
*/
public function getFormatter(string $mime)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can't remove this. It would be a BC change.

This should use Services::format() under the hood and have a phpdoc comment that points out this method is deprecated since we have a new Format class now.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't remove it completely i just relocated it in system/Format/Format.php under CodeIgniter\Format namespace and now all Format instances runs throw \Config\Services::format()

about tests I actually don't know how to do it on the right way, may i get help or something

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I'm aware that you moved it to the Format class, but it doesn't change the fact that some people might use this method already in their code (just like we do in some of our tests). If we remove this method from here it will break their code - it has to stay.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I got your point, but i think we can solve this problem by hinting new changes in next version changelog or something like that, any ideas?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, sorry. It has to stay - it was a public method. Removing it will be a breaking compatibility change.

{
if (! array_key_exists($mime, $this->formatters))
{
throw new \InvalidArgumentException('No Formatter defined for mime type: ' . $mime);
}

$class = $this->formatters[$mime];

if (! class_exists($class))
{
throw new \BadMethodCallException($class . ' is not a valid Formatter.');
}

return new $class();
}

//--------------------------------------------------------------------

}
30 changes: 15 additions & 15 deletions system/API/ResponseTrait.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
namespace CodeIgniter\API;

use CodeIgniter\HTTP\Response;
use Config\Format;
use Config\Services;

/**
* Response trait.
Expand Down Expand Up @@ -134,8 +134,7 @@ public function respond($data = null, int $status = null, string $message = '')
$output = $this->format($data);
}

return $this->response->setBody($output)
->setStatusCode($status, $message);
return $this->response->setBody($output)->setStatusCode($status, $message);
}

//--------------------------------------------------------------------
Expand Down Expand Up @@ -386,30 +385,31 @@ protected function format($data = null)
return $data;
}

$config = new Format();
$format = "application/$this->format";
$mime = "application/$this->format";

$format = Services::format();

// Determine correct response type through content negotiation if not explicitly declared
if (empty($this->format) || ! in_array($this->format, ['json', 'xml']))
{
$format = $this->request->negotiate('media', $config->supportedResponseFormats, false);
$mime = $this->request->negotiate('media', $format->getConfig()->supportedResponseFormats);
}

$this->response->setContentType($format);
$this->response->setContentType($mime);

// if we don't have a formatter, make one
if (! isset($this->formatter))
{
// if no formatter, use the default
$this->formatter = $config->getFormatter($format);
}

if ($format !== 'application/json')
if ($mime !== 'application/json')
{
// Recursively convert objects into associative arrays
// Conversion not required for JSONFormatter
$data = json_decode(json_encode($data), true);
}

// if we don't have a formatter, make one
if (! isset($this->formatter))
{
// if no formatter, use the default
$this->formatter = $format->getFormatter($mime);
}

return $this->formatter->format($data);
}
Expand Down
26 changes: 26 additions & 0 deletions system/Config/Services.php
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
use CodeIgniter\Encryption\EncrypterInterface;
use CodeIgniter\Encryption\Encryption;
use CodeIgniter\Filters\Filters;
use CodeIgniter\Format\Format;
use CodeIgniter\Honeypot\Honeypot;
use CodeIgniter\HTTP\CLIRequest;
use CodeIgniter\HTTP\CURLRequest;
Expand Down Expand Up @@ -310,6 +311,31 @@ public static function filters($config = null, bool $getShared = true)

//--------------------------------------------------------------------

/**
* The Format class works as a factory for formatters.
*
* @param mixed $config
* @param boolean $getShared
*
* @return \CodeIgniter\Format\Format
*/
public static function format($config = null, bool $getShared = true)
{
if ($getShared)
{
return static::getSharedInstance('format', $config);
}

if (is_null($config))
{
$config = new \Config\Format();
}

return new Format($config);
}

//--------------------------------------------------------------------

/**
* The Honeypot provides a secret input on forms that bots should NOT
* fill in, providing an additional safeguard when accepting user input.
Expand Down
17 changes: 15 additions & 2 deletions system/Format/Exceptions/FormatException.php
Original file line number Diff line number Diff line change
@@ -1,14 +1,27 @@
<?php namespace CodeIgniter\Format\Exceptions;
<?php

namespace CodeIgniter\Format\Exceptions;

use CodeIgniter\Exceptions\ExceptionInterface;
use RuntimeException;

class FormatException extends \RuntimeException implements ExceptionInterface
class FormatException extends RuntimeException implements ExceptionInterface
{
public static function forInvalidFormatter(string $class)
{
return new static(lang('Format.invalidFormatter', [$class]));
}

public static function forInvalidJSON(string $error = null)
{
return new static(lang('Format.invalidJSON', [$error]));
}

public static function forInvalidMime(string $mime)
{
return new static(lang('Format.invalidMime', [$mime]));
}

/**
* This will never be thrown in travis-ci
*
Expand Down
110 changes: 110 additions & 0 deletions system/Format/Format.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
<?php

/**
* CodeIgniter
*
* An open source application development framework for PHP
*
* This content is released under the MIT License (MIT)
*
* Copyright (c) 2014-2019 British Columbia Institute of Technology
* Copyright (c) 2019-2020 CodeIgniter Foundation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* @package CodeIgniter
* @author CodeIgniter Dev Team
* @copyright 2019-2020 CodeIgniter Foundation
* @license https://opensource.org/licenses/MIT MIT License
* @link https://codeigniter.com
* @since Version 4.0.0
*/

namespace CodeIgniter\Format;

use CodeIgniter\Format\Exceptions\FormatException;

/**
* Format Class
*
* @package CodeIgniter\Format
*/
class Format
{

/**
* Configuration class instance.
*
* @var \Config\Format
*/
protected $config;

//--------------------------------------------------------------------

/**
* Constructor
*
* @param \Config\Format $config
*/
public function __construct($config)
{
$this->config = $config;
}

//--------------------------------------------------------------------

/**
* A Factory method to return the appropriate formatter for the given mime type.
*
* @param string $mime
*
* @return CodeIgniter\Format\FormatterInterface
*/
public function getFormatter(string $mime): FormatterInterface
{
if (! array_key_exists($mime, $this->config->formatters))
{
throw FormatException::forInvalidMime($mime);
}

$class = $this->config->formatters[$mime];

if (! class_exists($class))
{
throw FormatException::forInvalidFormatter($class);
}

return new $class();
}

/**
* Get instance of format configuration class
*
* @return \Config\Format
*/
public function getConfig(): object
{
if (! $this->config instanceof \Config\Format)
{
return $this->config;
}

return new \Config\Format();
}
}
26 changes: 4 additions & 22 deletions system/HTTP/Response.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@
use CodeIgniter\HTTP\Exceptions\HTTPException;
use CodeIgniter\Pager\PagerInterface;
use Config\App;
use Config\Format;
use Config\Services;

/**
* Representation of an outgoing, getServer-side response.
Expand Down Expand Up @@ -467,13 +467,7 @@ public function getJSON()

if ($this->bodyFormat !== 'json')
{
/**
* @var Format $config
*/
$config = config(Format::class);
$formatter = $config->getFormatter('application/json');

$body = $formatter->format($body);
$body = Services::format()->getFormatter('application/json')->format($body);
}

return $body ?: null;
Expand Down Expand Up @@ -509,13 +503,7 @@ public function getXML()

if ($this->bodyFormat !== 'xml')
{
/**
* @var Format $config
*/
$config = config(Format::class);
$formatter = $config->getFormatter('application/xml');

$body = $formatter->format($body);
$body = Services::format()->getFormatter('application/xml')->format($body);
}

return $body;
Expand All @@ -542,13 +530,7 @@ protected function formatBody($body, string $format)
// Nothing much to do for a string...
if (! is_string($body) || $format === 'json-unencoded')
{
/**
* @var Format $config
*/
$config = config(Format::class);
$formatter = $config->getFormatter($mime);

$body = $formatter->format($body);
$body = Services::format()->getFormatter($mime)->format($body);
}

return $body;
Expand Down
2 changes: 2 additions & 0 deletions system/Language/en/Format.php
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
*/

return [
'invalidFormatter' => '"{0}" is not a valid Formatter.',
'invalidJSON' => 'Failed to parse json string, error: "{0}".',
'invalidMime' => 'No Formatter defined for mime type: "{0}".',
'missingExtension' => 'The SimpleXML extension is required to format XML.',
];
7 changes: 3 additions & 4 deletions system/Test/FeatureResponse.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@

use CodeIgniter\HTTP\RedirectResponse;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Format;
use Config\Services;
use PHPUnit\Framework\TestCase;

/**
Expand Down Expand Up @@ -414,9 +414,8 @@ public function assertJSONExact($test)

if (is_array($test))
{
$config = new Format();
$formatter = $config->getFormatter('application/json');
$test = $formatter->format($test);
$format = Services::format();
$test = $format->getFormatter('application/json')->format($test);
}

$this->assertJsonStringEqualsJsonString($test, $json, 'Response does not contain matching JSON.');
Expand Down
Loading