All Projects → ksassnowski → csv-schema

ksassnowski / csv-schema

Licence: MIT license
Parse a CSV file into PHP objects based on a schema.

Programming Languages

PHP
23972 projects - #3 most used programming language

Projects that are alternatives of or similar to csv-schema

applink
A simple router based on scheme for Android
Stars: ✭ 21 (-8.7%)
Mutual labels:  schema
pulsar-io-kafka
Pulsar IO Kafka Connector
Stars: ✭ 24 (+4.35%)
Mutual labels:  schema
linkifier
Database reverse engineering
Stars: ✭ 32 (+39.13%)
Mutual labels:  schema
schemify
Automatically generate Schema.org JSON-LD markup for WordPress content.
Stars: ✭ 58 (+152.17%)
Mutual labels:  schema
upscheme
Database migrations and schema updates made easy
Stars: ✭ 737 (+3104.35%)
Mutual labels:  schema
examples
Apache Pulsar examples and demos
Stars: ✭ 41 (+78.26%)
Mutual labels:  schema
graphql-go-tools
Like apollo-tools for graphql-go
Stars: ✭ 22 (-4.35%)
Mutual labels:  schema
scheriff
Schema Sheriff: yet another Kubernetes manifests validation tool
Stars: ✭ 15 (-34.78%)
Mutual labels:  schema
serde
🚝 (unmaintained) A framework for defining, serializing, deserializing, and validating data structures
Stars: ✭ 49 (+113.04%)
Mutual labels:  schema
Workshop-GraphQL
A GraphQL Server made for the workshop
Stars: ✭ 22 (-4.35%)
Mutual labels:  schema
hodur-visualizer-schema
Hodur is a domain modeling approach and collection of libraries to Clojure. By using Hodur you can define your domain model as data, parse and validate it, and then either consume your model via an API or use one of the many plugins to help you achieve mechanical results faster and in a purely functional manner.
Stars: ✭ 16 (-30.43%)
Mutual labels:  schema
arrest
Swagger REST framework for Node.js, with support for MongoDB and JSON-Schema
Stars: ✭ 17 (-26.09%)
Mutual labels:  schema
popoto-examples
Contains a list of Popoto.js examples
Stars: ✭ 121 (+426.09%)
Mutual labels:  schema
joyce
Joyce is a highly scalable event-driven Cloud Native Data Hub.
Stars: ✭ 37 (+60.87%)
Mutual labels:  schema
openapi4j
OpenAPI 3 parser, JSON schema and request validator.
Stars: ✭ 92 (+300%)
Mutual labels:  schema
xml-core
xml-core is a set of classes that make it easier to work with XML within the browser and node.
Stars: ✭ 18 (-21.74%)
Mutual labels:  schema
pykafarr
A high-performance Python Kafka client. Efficiently from Kafka to Pandas and back.
Stars: ✭ 32 (+39.13%)
Mutual labels:  schema
performify
Service object which makes you better.
Stars: ✭ 14 (-39.13%)
Mutual labels:  schema
srclient
Golang Client for Schema Registry
Stars: ✭ 188 (+717.39%)
Mutual labels:  schema
classicpress-seo
Classic SEO is the first SEO plugin built specifically to work with ClassicPress. A fork of Rank Math, the plugin contains many essential SEO tools to help optimize your website.
Stars: ✭ 18 (-21.74%)
Mutual labels:  schema

CSV Schema Parser

Build Status Code Climate Scrutinizer Code Quality SensioLabsInsight GitHub license Current Release

Have you ever wanted to have something like an ORM but for CSV files? No? Well now you can!

Introducing CSV Schema Parser. The number one way to turn your boring old CSV files into kick-ass PHP objects. And as if that wasn't amazing enough, it also casts your data to the correct data type! How cool is that? Not very cool you say? Well I disagree!

Installation

composer require sassnowski/csv-schema

Usage

First we have to define the schema of the CSV file we're about to parse. The schema is an associative array where the keys define what properties will be named on the resulting object. The values specify the data type of that column. The schema is ordered, meaning the first entry in the schema will correspond to the first column in the CSV and so on.

<?php

$config = [
    'schema' => [
        'first_name' => 'string',
        'last_name' => 'string',
        'age' => 'integer',
        'coolness_factor' => 'float',
    ]
];

After we defined the schema, we can instantiate a new parser from it.

<?php

// continuing from above..

$parser = new Sassnowski\CsvSchema\Parser($config);

Reading from a string

The parser provides a fromString method that will turn any CSV string into an array of objects. The objects will be structured according to our schema.

<?php

public Parser::fromString(string $input): array

Example

<?php

// Using our parser from above..

$input = "Kai,Sassnowski,26,0.3\nJohn,Doe,38,7.8";

$rows = $parser->fromString($input);

var_dump($rows[0]->firstname);
// string(3) "Kai"

var_dump($rows[0]->age);
// int(26)

var_dump($rows[0]->coolness_factor);
// float(0.3)

Reading from a file

More often than not you will parse your CSV from a file. For this the Parser provides the fromFile method.

<?php

public Parser::fromFile(string $filename): array

Example

<?php

// Using our parser from above..

// Assuming our file contains the same data as the string example.
$rows = $parser->fromFile('somefile.csv');

var_dump($rows[1]->firstname);
// string(4) "John"

var_dump($rows[1]->coolness_factor);
// float(7.8)

Configuration

The configuration array provides a way to overwrite the default settings of the parser. You can set the delimiter, the enclosure character, the escape character and the encoding of the input file.

<?php

$config = [
    'delimiter' => ',',
    'enclosure' => '"',
    'escape' => '\\',
    'skipTitle' => false,
    'encoding' => 'UTF-8',
    'schema' => [ /* Your schema */ ],
];

Available Column Types

You can parse a column to string, float, integer and array.

Parsing arrays

Assuming you have multiple values in a column (sometimes we cannot choose our data...) you might want to parse that column into an array instead. You can do this by specifying array:<delimiter> as the column type in your schema.

<?php

$config = [
    'schema' => [
        'name' => 'string',
        'friends' => 'array:|'
    ],
];

$input = 'Kai Sassnowski,Lots|and|lots|of|friends';

$parser = new Sassnowski\CsvSchema\Parser($config);

$rows = $parser->fromString($input);

var_dump($rows[0])->friends);

// array(5) {
//    [0]=>
//    string(4) "Lots"
//    [1]=>
//    string(3) "and"
//    [2]=>
//    string(4) "lots"
//    [3]=>
//    string(2) "of"
//    [4]=>
//    string(7) "friends"
// }

Adding custom types

Sometimes you might want a bit more control than the built-in types give you. For instance, you might want to query your database based on an integer in one of your columns and return a model instead. You can easily register arbitrarily complex types by using the static registerType method on the Parser class.

<?php

public static registerType(string $type, callable $callback)

The provided callback receives the column's value and should return its parsed representation.

<?php

Parser::registerType('foo', function ($value) {
    return $value.'foo';
});

$config = [
    'schema' => [
        'custom' => 'foo'
    ]
];

$parser = new \Sassnowski\CsvSchema\Parser($config);

$rows = $parser->fromString("hello\nworld");

var_dump($rows[0]->custom);
// string(8) "hellofoo"

var_dump($rows[1]->custom);
// string(8) "worldfoo"

Adding parameters to custom types

You can add additional parameters to your types by specifying them in the following format in your schema <type>:<parameter>. In this case, the callback function gets passed a second parameter containing the parameter specified in the schema. This allows you to reuse your types instead of defining all sorts of variations of the same type (like querying the database, but using a different table/model).

<?php

Parser::registerType('model', function ($value, $table) {
    // Pseudo code, assuming some library.
    return DB::table($table)->findById($value);
});

$config = [
    'schema' => [
        'author' => 'model:authors',
        'uploaded_by' => 'model:users',
    ]
];

$input = "5,13";

$parser = new \Sassnowski\CsvSchema\Parser($config);

$rows = $parser->fromString($input);

var_dump($rows[0]->author);
// object(Author)#1 (15) {
//    ["id"]=>
//    int(5)
//    ...
// }

var_dump($rows[1]->uploaded_by);
// object(User)#1 (12) {
//    ["id"]=>
//    int(13)
//    ...
// }
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].