getkirby / kirby

Kirby's core application folder
https://getkirby.com
Other
1.32k stars 168 forks source link

site.update.after hook caused by $site->update() is called with the default translation #1604

Closed hdodov closed 5 years ago

hdodov commented 5 years ago

Describe the bug I've developed a plugin that uses the site.update.after hook. It works as expected from within the panel, but does not when the site is updated via the API.

If the panel calls the hook, the site.update.after callback gets the correct translation - if you update the default language data, you get the English $page. If you update a translation, you get that translation's $page (Bulgarian in my case). However, if the hook is triggered by the API:

$site->update([
  'test' => 'foo'
], 'bg');

You always get the English translation.

To Reproduce Steps to reproduce the behavior:

  1. Create a plugin with the following options:
'hooks' => [
  'site.update:after' => function ($site) {
    var_dump($site->translation()->code());
  }
],
'api' => [
  'routes' => [
    [
      'pattern' => 'testUpdate',
      'method' => 'GET',
      'action' => function () {
        site()->update(['test' => 'bar'], 'bg');
      }
    ]
  ]
]
  1. Add a new language. For example, Bulgarian (code bg).

  2. Open the panel and edit something in the Site in the Bulgarian translation.

  3. You should get an error in the panel:

The JSON response from the API could not be parsed. Please check your API connection.

That's because of the var_dump() in the hook. The response would no longer be valid JSON. You should inspect that response in the Network tab of your DevTools. There, the result of that var_dump() should be bg, as expected, because you're editing the Bulgarian translation of the page.

  1. Go to the testUpdate route of the API:
http://localhost/kirby/api/testUpdate?csrf=9e1534bfa938023d64360efbfedb4ed29fa2bf7e1d41b71efc5d96d66c34d964
  1. The output of var_dump() will be en instead of bg.

Expected behavior The hook should receive the correct translation when triggered by the API.

Kirby Version 3.1.0

Desktop (please complete the following information):

bastianallgeier commented 5 years ago

I double-checked and this isn't really a bug, but the way the API handles languages.

$site->translation() "listens" to the currently active language. The currently active language is set with $kirby->setCurrentLanguage('bg'); The API only sets the currently active language if it finds a "x-language" header. In your manual API call example, the header is not set. That means that English is still the active language.