Coder Social home page Coder Social logo

firestore-php's Introduction

Firestore Client for PHP

Latest Version on Packagist Total Downloads License

This package is totally based on Firestore REST API

Authentication / Generate API Key

  1. Visit Google Cloud Firestore API
  2. Select your desired project.
  3. Select Credentials from left menu and select API Key from Server key or Create your own credentials

Installation

You can install the package via composer:

composer require ahsankhatri/firestore-php

or install it by adding it to composer.json then run composer update

"require": {
    "ahsankhatri/firestore-php": "^2.0",
}

Dependencies

The bindings require the following extensions in order to work properly:

If you use Composer, these dependencies should be handled automatically. If you install manually, you'll want to make sure that these extensions are available.

Usage

Initialization

$firestoreClient = new FirestoreClient('project-id', 'AIzaxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx', [
    'database' => '(default)',
]);

Adding a document

$firestoreClient->addDocument($collection, [
    'booleanTrue' => true,
    'booleanFalse' => false,
    'null' => null,
    'string' => 'abc123',
    'integer' => 123456,
    'arrayRaw' => [
        'string' => 'abc123',
    ],
    'bytes' => new FirestoreBytes('bytesdata'),
    'array' => new FirestoreArray([
        'string' => 'abc123',
    ]),
    'reference' => new FirestoreReference('/users/23'),
    'object' => new FirestoreObject(['nested1' => new FirestoreObject(['nested2' => new FirestoreObject(['nested3' => 'test'])])]),
    'timestamp' => new FirestoreTimestamp,
    'geopoint' => new FirestoreGeoPoint(1,1),
]);

NOTE: Pass third argument if you want your custom document id to set else auto-id will generate it for you.

Or

$document = new FirestoreDocument;
$document->setObject('sdf', new FirestoreObject(['nested1' => new FirestoreObject(['nested2' => new FirestoreObject(['nested3' => 'test'])])]));
$document->setBoolean('booleanTrue', true);
$document->setBoolean('booleanFalse', false);
$document->setNull('null', null);
$document->setString('string', 'abc123');
$document->setInteger('integer', 123456);
$document->setArray('arrayRaw', ['string'=>'abc123']);
$document->setBytes('bytes', new FirestoreBytes('bytesdata'));
$document->setArray('arrayObject', new FirestoreArray(['string' => 'abc123']));
$document->setTimestamp('timestamp', new FirestoreTimestamp);
$document->setGeoPoint('geopoint', new FirestoreGeoPoint(1.11,1.11));

$firestoreClient->addDocument($collection, $document, 'customDocumentId');

And..

$document->fillValues([
    'string' => 'abc123',
    'boolean' => true,
]);

Inserting/Updating a document

  • Update (Merge) or Insert document

Following will merge document (if exist) else insert the data.

$firestoreClient->updateDocument($documentRoot, [
    'newFieldToAdd' => new FirestoreTimestamp(new DateTime('2018-04-20 15:00:00')),
    'existingFieldToRemove' => new FirestoreDeleteAttribute
]);

NOTE: Passing 3rd argument as a boolean true will force check that document must exist and vice-versa in order to perform update operation.

For example: If you want to update document only if exist else MrShan0\PHPFirestore\Exceptions\Client\NotFound (Exception) will be thrown.

$firestoreClient->updateDocument($documentPath, [
    'newFieldToAdd' => new FirestoreTimestamp(new DateTime('2018-04-20 15:00:00')),
    'existingFieldToRemove' => new FirestoreDeleteAttribute
], true);
  • Overwirte or Insert document
$firestoreClient->setDocument($collection, $documentId, [
    'newFieldToAdd' => new FirestoreTimestamp(new DateTime('2018-04-20 15:00:00')),
    'existingFieldToRemove' => new FirestoreDeleteAttribute
], [
    'exists' => true, // Indicate document must exist
]);

Deleting a document

$collection = 'collection/document/innerCollection';
$firestoreClient->deleteDocument($collection, $documentId);

List documents with pagination (or custom parameters)

$collections = $firestoreClient->listDocuments('users', [
    'pageSize' => 1,
    'pageToken' => 'nextpagetoken'
]);

Note: You can pass custom parameters as supported by firestore list document

Get field from document

$document->get('bytes')->parseValue(); // will return bytes decoded value.

// Catch field that doesn't exist in document
try {
    $document->get('allowed_notification');
} catch (\MrShan0\PHPFirestore\Exceptions\Client\FieldNotFound $e) {
    // Set default value
}

Firebase Authentication

Sign in with Email and Password.

$firestoreClient
    ->authenticator()
    ->signInEmailPassword('[email protected]', 'abc123');

Sign in Anonymously.

$firestoreClient
    ->authenticator()
    ->signInAnonymously();

Retrieve Auth Token

$authToken = $firestoreClient->authenticator()->getAuthToken();

TODO

  • Added delete attribute support.
  • Add Support for Object, Boolean, Null, String, Integer, Array, Timestamp, GeoPoint, Bytes
  • Add Exception Handling.
  • List all documents.
  • List all collections.
  • Filters and pagination support.
  • Structured Query support.
  • Transaction support.
  • Indexes support.
  • Entire collection delete support.

Testing

composer test

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

firestore-php's People

Contributors

ahsankhatri avatar baha2odeh avatar cristirusu avatar edruid avatar mowcixo avatar p-blomberg avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

firestore-php's Issues

How to get id of new document

I've been looking at the docs and the code but I can't find a way to get the id of a new document. Is it possible?
Here's an example:

$firestoreClient = new FirestoreClient('xxx', 'yyyyyyyyyyyyyyyyyyyyyyy', [
     'database' => '(default)',
]);
$document = new FirestoreDocument;
$document->fillValues($data);
$firestoreClient->addDocument('my-collection', $document);
$newdocid = ??????

How to use or get FirestoreClient Library before Initialization FirestoreClient

i am using your this code i am getting an error
error: Class 'App\Http\Controllers\FirestoreClient' not found

and when i sue this:
use Ahsankhatri\Firestore\FirestoreClient;

then again i got an error
error: Class 'Ahsankhatri\Firestore\FirestoreClient' not found

please help me how fix it please help me please

i am new actually so that's why m not able to understand that how to solve it

Dependency issue

I got the following error:
Problem 1
- morrislaptop/firestore-php[v2.2.0, ..., v2.2.2] require kreait/firebase-php ^4.15 -> found kreait/firebase-php[4.15.0, ..., 4.x-dev] but it conflicts with your root composer.json require (^5.17).
- Root composer.json requires morrislaptop/firestore-php ^2.2 -> satisfiable by morrislaptop/firestore-php[v2.2.0, v2.2.1, v2.2.2].

Custom filter

Custom filter.
Does it accept any other search attribute than collection id ?
Ex name, date or any other key / value combination.

How to Query Documents by ID

$companies $this->firestoreClient->listDocuments('companies');

So far this is im stuck with, but i dont want to select all the documents under companies collection, and i dont see any way in the documentation to only select specific documents from a collection of documents.

Dependency upgrade to guzzlehttp/guzzle ~7.x planned?

In my project I have already guzzlehttp/guzzle ~7.x installed which I don't want to downgrade. Composer dependencies here says guzzlehttp/guzzle ~6.0|~5.0|~4.0 which do not satisfy my needs.

Is there an dependency upgrade planned for this?

Thanks for short info - appreciate your work!!

Authentication with Service Account

According to official Google library its the best way how to work with resources (at least for beginners). I can try write PR, but please tell me your opinion for this. Thanks.

Do not use API keys for local or production applications. For almost all cases, you should use service accounts. (Authentication DOC)

Does not handle native nested arrays (payload is empty / deleted)

      $val = [
         'timestamp' => new FirestoreTimestamp,
         'a' => ['b'=>['c'=>'test']],
      ];
      $ret = $firestoreClient->updateDocument($path, $val);

Unable to handle nested native arrays.
This code will fail, and add no fields to the document, if the given fields are present they will be deleted, there is no exception raised, payload will just be empty.

Laravel 7 Authentication Issue

Hello --

What am I missing here:

        $firestoreClient = new FirestoreClient('test-project-123', 'AIzXXXXX', [
            'database' => '(default)',
        ]);

        $collections = $firestoreClient->listDocuments('test', [
            'pageSize' => 1,
            'pageToken' => 'nextpagetoken'
        ]);
MrShan0\PHPFirestore\Exceptions\Client\Forbidden 

  You do not have permission to access the requested resource.  Response: {
  "error": {
    "code": 403,
    "message": "Missing or insufficient permissions.",
    "status": "PERMISSION_DENIED"
  }
}

I checked my API keys, everything looks good.

How to update an object in a field of document

image

I have this set of collection, and all fields of my document contains an array of objects. now i need to know if it is possible and how to update only one object from the array of objects from the field of a document.

How to send auth property in FirebaseClient creation?

Hi, I'm adding the auth property in the FirestoreClient constructor function to fulfill a security rule in my Firestore project in this way,

$this->firestoreClient = new FirestoreClient('my_project_id', 'my_api_key', [
            'database' => '(default)',
            'auth' => '{ uid: "some_number" }'
        ]);

but I always get 'PERMISSION DENIED' 'Missing or insufficient permissions'.

What is the proper way to add this to the initial config object?

pageSize not working in listDocuments function

$collections = $firestoreClient->listDocuments('users', [
'pageSize' => 1,
'pageToken' => 'nextpagetoken'
]);

in this if i try to set pageSize as 2 then i am not getting any response.

Error: PERMISSION_DENIED: Missing or insufficient permissions

I tried to write to FireStore but the server responded 403 PERMISSION_DENIED: Missing or insufficient permissions.

The database rule is:

service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow read, write: if request.auth.uid != null;
    }
  }
}

If I change rule to allow read, write: if true; (turn off database security), it's OK.

How to update document

Hi! i'm trying to update the document using $firestoreClient->setDocument(). But it's giving me an error "The path you have defined is invalid. Path: categories". Please help me what i'm missing. Thank you
Here is my code
$collection = "categories"; $documentId = $id; $firestoreClient->setDocument($collection, $documentId, [ 'name' => $request->name, 'description' => $request->description, 'picture' => $filename, ], [ 'exists' => true, // Indicate document must exist ] );

Call to undefined method FirestoreAuthentication::setLastResponse()

Hi,

When I am trying to auth:

 $firestoreClient
    ->authenticator()
    ->signInAnonymously();

I am getting
Call to undefined method MrShan0\PHPFirestore\Authentication\FirestoreAuthentication::setLastResponse() at ahsankhatri\\firestore-php\\src\\Authentication\\FirestoreAuthentication.php:155

Any ideas?

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.