Skip to content

Added a basic version of a JSON service #383

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

Merged
Merged
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@
[#379](https://github.com./nextcloud/cookbook/pull/379/) @seyfeb
- Selectable keywords for filtering in recipe lists
[#375](https://github.com./nextcloud/cookbook/pull/375/) @seyfeb
- Service to handle schema.org JSON data in strings easier
[#383](https://github.com./nextcloud/cookbook/pull/383/) @christianlupus

### Changed
- Switch of project ownership to neextcloud organization in GitHub
Expand Down
65 changes: 65 additions & 0 deletions lib/Service/JsonService.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
<?php

namespace OCA\Cookbook;

/**
* A collection of useful functions to handle schema.org JSON data
*
* @author Christian Wolf <[email protected]>
*
*/
class JsonService
{

/**
* Check if an object is a JSON representation of a schema.org object
*
* The type of the object can be optionally checked using the second parameter.
*
* @param mixed $obj The object to check
* @param string $type The type to check for. If null or '' no type chek is performed
* @return bool true, if $obj is an object and optionally satisfies the type check
*/
public function isSchemaObject($obj, string $type = null) : bool
{
if(! is_array($obj))
{
// Objects must bve encoded as arrays in JSON
return false;
}

if(!isset($obj['@type']))
{
// Objects must have a property @type
return false;
}

// We have an object

if($type === null || $type === '')
{
// No typecheck was requested. So return true
return true;
}

// Check if type matches
return (strcmp($obj['@type'], $type) == 0);
}

/**
* Check if $obj is a schema.org object and contains a named property.
*
* @param mixed $obj The object to check
* @param string $property The name of the property to check for
* @return bool true, if $obj is a object and has the property given
*/
public function hasProperty($obj, string $property) : bool
{
if(!$this->isSchemaObject($obj))
{
return false;
}

return array_key_exists($property, $obj);
}
}