### Initialize Storage Component Source: https://github.com/kreait/firebase-php/blob/7.x/docs/cloud-storage.rst Demonstrates how to create a Storage instance using the Firebase Factory. This is the primary way to get started with the Cloud Storage component. ```php $storage = $factory->createStorage(); ``` -------------------------------- ### Install google/cloud-firestore Source: https://github.com/kreait/firebase-php/blob/7.x/docs/cloud-firestore.rst Installs the Google Cloud Firestore package as a project dependency using Composer. ```bash composer require google/cloud-firestore ``` -------------------------------- ### Firebase SDK Factory Debug Info Example Source: https://github.com/kreait/firebase-php/blob/7.x/docs/troubleshooting.rst An example output of the `getDebugInfo()` method, showing the configuration details of the Firebase SDK factory, including credentials, database URL, and project ID. ```text Array ( [credentialsType] => Google\Auth\Credentials\ServiceAccountCredentials [databaseUrl] => https://project-id-default-rtdb.firebaseio.com [defaultStorageBucket] => [projectId] => project-id [serviceAccount] => Array ( [type] => service_account [project_id] => project-id [private_key_id] => a1b2c3d4e5f6g7h8i9j0 [private_key] => {exists, redacted} [client_email] => project-id-xyz@beste-firebase.iam.gserviceaccount.com [client_id] => 1234567890987654321 [auth_uri] => https://accounts.google.com/o/oauth2/auth [token_uri] => https://oauth2.googleapis.com/token [auth_provider_x509_cert_url] => https://www.googleapis.com/oauth2/v1/certs [client_x509_cert_url] => https://www.googleapis.com/robot/v1/metadata/x509/project-id-xyz%40beste-firebase.iam.gserviceaccount.com ) ) ``` -------------------------------- ### Get Storage Client and Buckets Source: https://github.com/kreait/firebase-php/blob/7.x/docs/cloud-storage.rst Provides examples of how to obtain the underlying Google Cloud Storage client and access the default or a specific named storage bucket. ```php $storageClient = $storage->getStorageClient(); $defaultBucket = $storage->getBucket(); $anotherBucket = $storage->getBucket('another-bucket'); ``` -------------------------------- ### Install Firebase PHP SDK with Composer Source: https://github.com/kreait/firebase-php/blob/7.x/docs/overview.rst Installs the Firebase Admin SDK using Composer, the recommended dependency manager for PHP projects. This command adds the SDK as a project dependency. ```bash composer require kreait/firebase-php ``` -------------------------------- ### Initialize Storage with Laravel App Helper Source: https://github.com/kreait/firebase-php/blob/7.x/docs/cloud-storage.rst Illustrates how to retrieve the Storage instance using Laravel's global `app()` helper function, provided the `kreait/laravel-firebase` package is installed. ```php $storage = app('firebase.storage'); ``` -------------------------------- ### Install Firebase Admin PHP SDK Source: https://github.com/kreait/firebase-php/blob/7.x/README.md This command installs the Firebase Admin PHP SDK version 7.0 or higher using Composer, the dependency manager for PHP. ```bash composer require "kreait/firebase-php:^7.0" ``` -------------------------------- ### Comprehensive Error Handling Example Source: https://github.com/kreait/firebase-php/blob/7.x/docs/cloud-messaging.rst An example showing how to catch multiple specific messaging exceptions in a single try-catch block, demonstrating a robust error handling strategy. ```php use Kreait\Firebase\Exception\Messaging as MessagingErrors; use Kreait\Firebase\Exception\MessagingException; try { $messaging->send($message); } catch (MessagingErrors\NotFound $e) { echo 'The target device could not be found.'; } catch (MessagingErrors\InvalidMessage $e) { echo 'The given message is malformatted.'; } catch (MessagingErrors\ServerUnavailable $e) { $retryAfter = $e->retryAfter(); echo 'The FCM servers are currently unavailable. Retrying at '.$retryAfter->format(DATE_ATOM); // This is just an example. Using `sleep()` will block your script execution, don't do this. } ``` -------------------------------- ### Firebase Admin SDK Initialization with Emulator Source: https://github.com/kreait/firebase-php/blob/7.x/docs/testing.rst Example of how to initialize the Firebase Admin SDK in PHP to connect to the emulators. This involves setting the project ID and potentially other emulator host variables. ```php // Assuming GOOGLE_CLOUD_PROJECT is set or passed directly // $projectId = 'your-emulator-project-id'; // For Auth Emulator: // $auth = $firebaseFactory->createAuth($projectId); // For Realtime Database Emulator: // $database = $firebaseFactory->createDatabase($projectId); ``` -------------------------------- ### Create New Remote Config Template Source: https://github.com/kreait/firebase-php/blob/7.x/docs/remote-config.rst Provides an example of creating a new, empty Remote Config template. ```php use Kreait\Firebase\RemoteConfig; $template = RemoteConfig\Template::new(); ``` -------------------------------- ### Get Firestore Database Instance Source: https://github.com/kreait/firebase-php/blob/7.x/docs/cloud-firestore.rst Obtains the Firestore client instance, which is an object of `Google\Cloud\Firestore\FirestoreClient`. ```php $database = $firestore->database(); ``` -------------------------------- ### Verifying OpenSSL PHP Extension Source: https://github.com/kreait/firebase-php/blob/7.x/docs/troubleshooting.rst Shows how to check if the OpenSSL PHP extension is installed and accessible. This is necessary for cryptographic operations used by the SDK. ```php var_dump(openssl_get_cert_locations()); ``` -------------------------------- ### Firebase Admin SDK Initialization Source: https://github.com/kreait/firebase-php/blob/7.x/docs/index.rst Initializes the Firebase Admin SDK for PHP using service account credentials and a database URI. This setup allows access to various Firebase services like Authentication, Realtime Database, Cloud Messaging, and more. ```php use Kreait\Firebase\Factory; $factory = (new Factory) ->withServiceAccount('/path/to/firebase_credentials.json') ->withDatabaseUri('https://my-project-default-rtdb.firebaseio.com'); $auth = $factory->createAuth(); $realtimeDatabase = $factory->createDatabase(); $cloudMessaging = $factory->createMessaging(); $remoteConfig = $factory->createRemoteConfig(); $cloudStorage = $factory->createStorage(); $firestore = $factory->createFirestore(); ``` -------------------------------- ### Shallow Query Example Source: https://github.com/kreait/firebase-php/blob/7.x/docs/realtime-database.rst Demonstrates how to perform a shallow query to retrieve only the keys of children at a specific location, useful for large datasets. This limits the depth of the returned data. ```php $database->getReference('currencies') ->shallow() ->getSnapshot(); ``` -------------------------------- ### Managing Firebase Realtime Database Rules Source: https://github.com/kreait/firebase-php/blob/7.x/docs/realtime-database.rst Provides examples of how to manage Firebase Realtime Database rules using the PHP SDK. It covers creating default, public, private, and custom rule sets, and updating them via the SDK. ```php use Kreait\Firebase\Database\RuleSet; // The default rules allow full read and write access to authenticated users of your app $ruleSet = RuleSet::default(); // This level of access means anyone can read or write to your database. You should // configure more secure rules before launching your app. $ruleSet = RuleSet::public(); // Private rules disable read and write access to your database by users. // With these rules, you can only access the database through the // Firebase console and the Admin SDKs. $ruleSet = RuleSet::private(); // You can define custom rules $ruleSet = RuleSet::fromArray(['rules' => [ '.read' => true, '.write' => false, 'users' => [ '$uid' => [ '.read' => '$uid === auth.uid', '.write' => '$uid === auth.uid', ] ] ]]); $database->updateRules($ruleSet); $freshRuleSet = $database->getRuleSet(); // Returns a new RuleSet instance $actualRules = $ruleSet->getRules(); // returns an array ``` -------------------------------- ### Get Factory Debug Information Source: https://github.com/kreait/firebase-php/blob/7.x/docs/troubleshooting.rst This PHP code snippet retrieves detailed configuration information about the Firebase SDK's factory, which can be helpful for debugging and verifying settings. ```php $factoryInfo = $factory->getDebugInfo(); ``` -------------------------------- ### Configure Caching Source: https://github.com/kreait/firebase-php/blob/7.x/docs/setup.rst Illustrates how to integrate PSR-6 compatible caching implementations with the Firebase SDK to improve performance by reducing API requests. It shows examples for default, auth token, key set, and verifier caches. ```php use Symfony\Component\Cache\Simple\FilesystemCache; // One Cache instance for all components $factory = $factory->withDefaultCache(new FilesystemCache()); // Cache used for authentication tokens, so that they requests don't have to be re-authenticated $factory = $factory->withAuthTokenCache(new FilesystemCache()); // Cache used to store JWKS (JSON Web Key Sets), so that they don't have to be fetched again $factory = $factory->withKeySetCache(new FilesystemCache()); // Cache used to store verified ID tokens and session cookies, so that they don't have to be verified again $factory = $factory->withVerifierCache(new FilesystemCache()); ``` -------------------------------- ### Database Snapshot Methods Source: https://github.com/kreait/firebase-php/blob/7.x/docs/realtime-database.rst Details the available methods on a Database Snapshot object for inspecting and accessing the data. These methods include checking existence, getting child data, retrieving keys, and more. ```php // exists(): returns true if the Snapshot contains any (non-null) data. // getChild(): returns another Snapshot for the location at the specified relative path. // getKey(): returns the key (last part of the path) of the location of the Snapshot. // getReference(): returns the Reference for the location that generated this Snapshot. // getValue(): returns the data contained in this Snapshot. // hasChild(): returns true if the specified child path has (non-null) data. // hasChildren(): returns true if the Snapshot has any child properties, i.e. if the value is an array. // numChildren(): returns the number of child properties of this Snapshot, if there are any. ``` -------------------------------- ### Create Custom Dynamic Link Source: https://github.com/kreait/firebase-php/blob/7.x/docs/dynamic-links.rst Provides an example of building a fully customized Dynamic Link using the `CreateDynamicLink` action. It demonstrates setting various options including dynamic link domain, suffix type, analytics information (Google Play and iTunes Connect), navigation info, iOS info, and Android info. ```php use Kreait\Firebase\DynamicLink\CreateDynamicLink; use Kreait\Firebase\DynamicLink\AnalyticsInfo; use Kreait\Firebase\DynamicLink\GooglePlayAnalytics; use Kreait\Firebase\DynamicLink\ITunesConnectAnalytics; use Kreait\Firebase\DynamicLink\NavigationInfo; use Kreait\Firebase\DynamicLink\IOSInfo; use Kreait\Firebase\DynamicLink\AndroidInfo; $action = CreateDynamicLink::forUrl($url) ->withDynamicLinkDomain('https://example.page.link') ->withUnguessableSuffix() // default // or ->withShortSuffix() ->withAnalyticsInfo( AnalyticsInfo::new() ->withGooglePlayAnalyticsInfo( GooglePlayAnalytics::new() ->withGclid('gclid') ->withUtmCampaign('utmCampaign') ->withUtmContent('utmContent') ->withUtmMedium('utmMedium') ->withUtmSource('utmSource') ->withUtmTerm('utmTerm') ) ->withItunesConnectAnalytics( ITunesConnectAnalytics::new() ->withAffiliateToken('affiliateToken') ->withCampaignToken('campaignToken') ->withMediaType('8') ->withProviderToken('providerToken') ) ) ->withNavigationInfo( NavigationInfo::new() ->withoutForcedRedirect() // default // or ->withForcedRedirect() ) ->withIOSInfo( IOSInfo::new() ->withAppStoreId('appStoreId') ->withBundleId('bundleId') ->withCustomScheme('customScheme') ->withFallbackLink('https://fallback.example.com') ->withIPadBundleId('iPadBundleId') ->withIPadFallbackLink('https://ipad-fallback.example.com') ) ->withAndroidInfo( AndroidInfo::new() ->withFallbackLink('https://fallback.example.com') ->withPackageName('packageName') ``` -------------------------------- ### Include Composer Autoloader in PHP Source: https://github.com/kreait/firebase-php/blob/7.x/docs/overview.rst Includes the Composer autoloader file in your PHP script to enable the use of classes installed via Composer, including the Firebase SDK. This is a standard practice for managing dependencies in PHP. ```php getUser('some-uid'); $user = $auth->getUserByEmail('user@example.com'); $user = $auth->getUserByPhoneNumber('+49-123-456789'); // For `getUserByProviderUid()` please see the section below. $user = $auth->getUserByProviderUid('google.com', 'google-uid'); } catch (Kreait\Firebase\Exception\Auth\UserNotFound $e) { echo $e->getMessage(); } ``` -------------------------------- ### Accessing Event Statistics Source: https://github.com/kreait/firebase-php/blob/7.x/docs/dynamic-links.rst Illustrates how to access and filter event statistics from a Dynamic Link. It shows how to get counts for clicks, redirects, app installs, first opens, and re-opens, and how to filter these events by platform (Android, Desktop, iOS) or custom criteria. ```php $eventStats = $stats->eventStatistics(); $allClicks = $eventStats->clicks(); $allRedirects = $eventStats->redirects(); $allAppInstalls = $eventStats->appInstalls(); $allAppFirstOpens = $eventStats->appFirstOpens(); $allAppReOpens = $eventStats->appReOpens(); $allAndroidEvents = $eventStats->onAndroid(); $allDesktopEvents = $eventStats->onDesktop(); $allIOSEvents = $eventStats->onIOS(); $clicksOnDesktop = $eventStats->clicks()->onDesktop(); $appInstallsOnAndroid = $eventStats->onAndroid()->appInstalls(); $appReOpensOnIOS = $eventStats->appReOpens()->onIOS(); $totalAmountOfClicks = count($eventStats->clicks()); $totalAmountOfAppFirstOpensOnAndroid = $eventStats->appFirstOpens()->onAndroid()->count(); $custom = $eventStats->filter(function (array $eventGroup) { return $eventGroup['platform'] === 'CUSTOM_PLATFORM_THAT_THE_SDK_DOES_NOT_KNOW_YET'; }); ``` -------------------------------- ### Initialize Firestore with SDK Source: https://github.com/kreait/firebase-php/blob/7.x/docs/cloud-firestore.rst Creates a Firestore client instance using the Firebase Factory. ```php $firestore = $factory->createFirestore(); ``` -------------------------------- ### Service Account Initialization (v4.x vs. Current) Source: https://github.com/kreait/firebase-php/blob/7.x/docs/troubleshooting.rst Illustrates the difference in initializing the Firebase service account between older v4.x tutorials and the current SDK versions. Highlights the change in method chaining for configuration. ```php $serviceAccount = ServiceAccount::fromJsonFile(__DIR__.'/google-service-account.json'); $firebase = (new Factory) ->withServiceAccount($serviceAccount) ->create(); $database = $firebase->getDatabase(); ``` ```php $factory = (new Factory)->withServiceAccount(__DIR__.'/google-service-account.json'); $database = $factory->createDatabase(); ``` -------------------------------- ### Initialize Firestore with Laravel app() helper Source: https://github.com/kreait/firebase-php/blob/7.x/docs/cloud-firestore.rst Retrieves the Firestore client instance using Laravel's global `app()` helper function. ```php $firestore = app('firebase.firestore'); ``` -------------------------------- ### Initialize Storage with Dependency Injection Source: https://github.com/kreait/firebase-php/blob/7.x/docs/cloud-storage.rst Shows how to inject the Storage component into a class using a dependency injection container, commonly used with frameworks like Symfony or Laravel. ```php use Kreait\Firebase\Contract\Storage; class MyService { public function __construct(Storage $storage) { $this->storage = $storage; } } ``` -------------------------------- ### Initialize Realtime Database Source: https://github.com/kreait/firebase-php/blob/7.x/docs/realtime-database.rst Demonstrates how to initialize the Realtime Database component using the Firebase PHP SDK. This can be done directly with the SDK factory or through dependency injection containers like Symfony or Laravel. ```php $database = $factory->createDatabase(); ``` ```php use Kreait\Firebase\Contract\Database; class MyService { public function __construct(Database $database) { $this->database = $database; } } ``` ```php $database = app('firebase.database'); ``` -------------------------------- ### Get Specific Remote Config Version Source: https://github.com/kreait/firebase-php/blob/7.x/docs/remote-config.rst Shows how to retrieve a specific Remote Config version by its version number. ```php $version = $remoteConfig->getVersion($versionNumber); ``` -------------------------------- ### Initialize Firestore with Dependency Injection Source: https://github.com/kreait/firebase-php/blob/7.x/docs/cloud-firestore.rst Demonstrates injecting the Firestore service into a class constructor, typically used with frameworks like Symfony or Laravel. ```php use Kreait\Firebase\Contract\Firestore; class MyService { public function __construct(Firestore $firestore) { $this->firestore = $firestore; } } ``` -------------------------------- ### Get Remote Config Template Source: https://github.com/kreait/firebase-php/blob/7.x/docs/remote-config.rst Shows how to retrieve the current Remote Config template or a specific version of the template. ```php $template = $remoteConfig->get(); // Returns a Kreait\Firebase\RemoteConfig\Template $version = $template->version(); // Returns a Kreait\Firebase\RemoteConfig\Version $template = $remoteConfig->get($version->versionNumber()); // Returns a Kreait\Firebase\RemoteConfig\Template with the specified version ``` -------------------------------- ### Get Child Keys Source: https://github.com/kreait/firebase-php/blob/7.x/docs/realtime-database.rst Provides a convenience method to retrieve an array of key names for the children of a given reference. ```php $database->getReference('currencies')->getChildKeys(); // returns an array of key names ``` -------------------------------- ### Initialize Auth Component Source: https://github.com/kreait/firebase-php/blob/7.x/docs/authentication.rst Demonstrates how to initialize the Firebase Auth component using the SDK directly or via dependency injection with frameworks like Symfony or Laravel. ```php $auth = $factory->createAuth(); ``` ```php use Kreait\Firebase\Contract\Auth; class MyService { public function __construct(Auth $auth) { $this->auth = $auth; } } ``` ```php $auth = app('firebase.auth'); ``` -------------------------------- ### Run SDK Tests Source: https://github.com/kreait/firebase-php/blob/7.x/docs/overview.rst Executes the unit tests for the Firebase PHP SDK using PHPUnit. This command is part of the Makefile and ensures the SDK's functionality and stability. ```bash make tests ``` -------------------------------- ### Get Multiple Users Source: https://github.com/kreait/firebase-php/blob/7.x/docs/user-management.rst Retrieves multiple user records by their UIDs. If a user does not exist, their corresponding entry in the result array will be null. ```php $users = $auth->getUsers(['some-uid', 'another-uid', 'non-existing-uid']); ``` -------------------------------- ### User Creation Properties API Documentation Source: https://github.com/kreait/firebase-php/blob/7.x/docs/user-management.rst Provides a detailed reference for the properties that can be set when creating a new Firebase user, including their types, descriptions, and constraints. ```APIDOC User Creation Properties: ================= ======= =========== Property Type Description ================= ======= =========== ``uid`` string The uid to assign to the newly created user. Must be a string between 1 and 128 characters long, inclusive. If not provided, a random uid will be automatically generated. ``email`` string The user's primary email. Must be a valid email address. ``emailVerified`` boolean Whether or not the user's primary email is verified. If not provided, the default is false. ``phoneNumber`` string The user's primary phone number. Must be a valid E.164 spec compliant phone number. ``password`` string The user's raw, unhashed password. Must be at least six characters long. ``displayName`` string The users' display name. ``photoURL`` string The user's photo URL. ``disabled`` boolean Whether or not the user is disabled. true for disabled; false for enabled. If not provided, the default is false. ================= ======= =========== Notes: - All properties are optional. If not specified, the value will be empty unless a default is mentioned. - If no properties are provided, an anonymous user will be created. ``` -------------------------------- ### Filter Results Starting At Value (PHP) Source: https://github.com/kreait/firebase-php/blob/7.x/docs/realtime-database.rst Retrieves children whose values are greater than or equal to a specified value. Requires prior ordering. ```php $database->getReference('people') ->orderByChild('height') ->startAt(1.68) ->getSnapshot(); ``` -------------------------------- ### Get Database Reference Source: https://github.com/kreait/firebase-php/blob/7.x/docs/realtime-database.rst Shows how to obtain a Reference to a specific location within the Firebase Realtime Database. Creating a reference does not trigger a network request. ```php $reference = $database->getReference('path/to/child/location'); ``` -------------------------------- ### Connect to Specific Firestore Databases Source: https://github.com/kreait/firebase-php/blob/7.x/docs/cloud-firestore.rst Shows how to create Firestore client instances for the default database and custom-named databases. ```php use Kreait\Firebase\Factory; $factory = new Factory(); $default = $factory->createFirestore(); $explicitDefault = $factory->createFirestore('(default)'); $custom = $factory->createFirestore('custom'); ``` -------------------------------- ### Configure Platform Independent FCM Options Source: https://github.com/kreait/firebase-php/blob/7.x/docs/cloud-messaging.rst Provides an example of how to set platform-independent FCM options for a message. It references the official Firebase REST API documentation for FCMOptions. ```php use Kreait\Firebase\Messaging\FcmOptions; // Example usage would follow here, referencing the REST Resource documentation. ``` -------------------------------- ### Add Firestore Client Configuration Options Source: https://github.com/kreait/firebase-php/blob/7.x/docs/cloud-firestore.rst Configures the Firestore client with additional options by passing an array to `withFirestoreClientConfig()`. ```php use Kreait\Firebase\Factory; $factory = new Factory(); $firestore = $factory ->withFirestoreClientConfig([...]) ->createFirestore(); ``` -------------------------------- ### List Remote Config Versions (Generator) Source: https://github.com/kreait/firebase-php/blob/7.x/docs/remote-config.rst Shows how to retrieve a list of Remote Config versions using a generator for efficiency. It provides examples of iterating through the versions or converting them to an array. ```php foreach ($auth->listVersions() as $version) { /** @var \Kreait\Firebase\RemoteConfig\Version $version */ // ... } // or array_map(function (\Kreait\Firebase\RemoteConfig\Version $version) { // ... }, iterator_to_array($auth->listVersions())); ``` -------------------------------- ### Initialize Dynamic Links Service Source: https://github.com/kreait/firebase-php/blob/7.x/docs/dynamic-links.rst Demonstrates how to initialize the Dynamic Links service with a specified domain, either directly or through dependency injection in frameworks like Laravel. ```php $dynamicLinksDomain = 'https://example.page.link'; $dynamicLinks = $factory->createDynamicLinksService($dynamicLinksDomain); ``` ```php use Kreait\Firebase\Contract\DynamicLinks; class MyService { public function __construct(DynamicLinks $dynamicLinks) { $this->dynamicLinks = $dynamicLinks; } } ``` ```php $dynamicLinks = app('firebase.dynamic_links'); ``` -------------------------------- ### Error Handling with Try-Catch Source: https://github.com/kreait/firebase-php/blob/7.x/docs/troubleshooting.rst Demonstrates how to handle Firebase-specific exceptions and general throwable errors using try-catch blocks. This is crucial for gracefully managing API rejections and other runtime issues. ```php use Kreait\Firebase\Exception\FirebaseException; use Throwable; try { // The operation you want to perform echo 'OK'; } catch (FirebaseException $e} { echo 'An error has occurred while working with the SDK: '.$e->getMessage; } catch (Throwable $e) { echo 'A not-Firebase specific error has occurred: '.$e->getMessage; } ``` -------------------------------- ### Initialize App Check Component Source: https://github.com/kreait/firebase-php/blob/7.x/docs/app-check.rst Demonstrates different ways to initialize the App Check component of the Firebase Admin SDK for PHP. This includes direct initialization, dependency injection with frameworks like Symfony or Laravel, and using the Laravel `app()` helper. ```php $appCheck = $factory->createAppCheck(); ``` ```php use Kreait\Firebase\Contract\AppCheck; class MyService { public function __construct(AppCheck $appCheck) { $this->appCheck = $appCheck; } } ``` ```php $appCheck = app('firebase.app_check'); ``` -------------------------------- ### Check cURL Version in PHP Source: https://github.com/kreait/firebase-php/blob/7.x/docs/troubleshooting.rst This PHP code snippet helps you determine the version of cURL installed with your PHP environment. This is useful for diagnosing issues related to outdated cURL versions. ```php echo curl_version()['version']; exit; ``` -------------------------------- ### Initialize Remote Config Source: https://github.com/kreait/firebase-php/blob/7.x/docs/remote-config.rst Demonstrates how to initialize the Firebase Remote Config component using the SDK, dependency injection, or the Laravel app helper. ```php $remoteConfig = $factory->createRemoteConfig(); ``` ```php use Kreait\Firebase\Contract\RemoteConfig; class MyService { public function __construct(RemoteConfig $remoteConfig) { $this->remoteConfig = $remoteConfig; } } ``` ```php $remoteConfig = app('firebase.remote_config'); ``` -------------------------------- ### Get Multiple Users Result Format Source: https://github.com/kreait/firebase-php/blob/7.x/docs/user-management.rst Illustrates the expected output format when retrieving multiple user records using `getUsers()`. Non-existent users are represented by `null`. ```text [ 'some-uid' => , 'another-uid' => , 'non-existing-uid' => null ] ``` -------------------------------- ### Retrieve Data Snapshot and Value Source: https://github.com/kreait/firebase-php/blob/7.x/docs/realtime-database.rst Illustrates how to fetch data from a Firebase Realtime Database location. You can get a Database Snapshot, which is an immutable copy of the data, or retrieve the value directly. ```php $snapshot = $reference->getSnapshot(); $value = $snapshot->getValue(); // or $value = $reference->getValue(); ``` -------------------------------- ### Configure Project ID and Database URI Source: https://github.com/kreait/firebase-php/blob/7.x/docs/setup.rst Shows how to manually set the Firebase project ID and Realtime Database URI when using credentials other than service accounts, or when auto-discovery is not desired. It also mentions environment variable configuration. ```php use Kreait\Firebase\Factory; $factory = (new Factory()) ->withProjectId('my-project') ->withDatabaseUri('https://my-project.firebaseio.com'); ``` -------------------------------- ### Firebase Authentication ActionCodeSettings Source: https://github.com/kreait/firebase-php/blob/7.x/docs/user-management.rst Defines settings for handling authentication actions, such as directing users to specific URLs or specifying app versions. The `androidInstallApp` field requires `androidPackageName` to be provided. ```php $actionCodeSettings = [ 'continueUrl' => 'https://www.example.com/checkout?cartId=1234', 'handleCodeInApp' => true, 'dynamicLinkDomain' => 'coolapp.page.link', 'androidPackageName' => 'com.example.android', 'androidMinimumVersion' => '12', 'androidInstallApp' => true, 'iOSBundleId' => 'com.example.ios', ]; ``` -------------------------------- ### Send Cloud Message to Topic Source: https://github.com/kreait/firebase-php/blob/7.x/docs/cloud-messaging.rst Provides examples for sending Cloud Messages to a specific FCM topic. It demonstrates constructing the message using both the fluent API and an array, and includes error handling. ```php use Kreait\Firebase\Exception\MessagingException; use Kreait\Firebase\Messaging\CloudMessage; $topic = 'a-topic'; $message = CloudMessage::new() ->withNotification($notification) // optional ->withData($data) // optional ->toTopic($topic); $message = CloudMessage::fromArray([ 'topic' => $topic, 'notification' => [/* Notification data as array */], // optional 'data' => [/* data array */], // optional ]); try { $result = $messaging->send($message); // $result = ['name' => 'projects//messages/6810356097230477954'] } catch (MessagingException $e) { // ... } ``` -------------------------------- ### Parameter Value Types Source: https://github.com/kreait/firebase-php/blob/7.x/docs/remote-config.rst Explains and shows examples of using different parameter value types (STRING, BOOL, NUMBER, JSON) for Remote Config parameters. Requires SDK version 7.4.0 or later. ```php use Kreait\Firebase\RemoteConfig\Parameter; use Kreait\Firebase\RemoteConfig\ParameterValueType; Parameter::named('string_parameter') ->withDefaultValue('Welcome!') ->withValueType(ParameterValueType::STRING); Parameter::named('boolean_parameter') ->withDefaultValue('true') ->withValueType(ParameterValueType::BOOL); Parameter::named('numeric_parameter') ->withDefaultValue('5') ->withValueType(ParameterValueType::NUMBER); Parameter::named('json_parameter') ->withDefaultValue('{"foo": "bar"}') ->withValueType(ParameterValueType::JSON); ``` -------------------------------- ### Get User by Provider UID Source: https://github.com/kreait/firebase-php/blob/7.x/docs/user-management.rst Retrieves a Firebase user record using their federated identity provider UID (e.g., Google, Facebook). Handles potential UserNotFound exceptions. ```php try { $googleUser = $auth->getUserByProviderUid('google.com', 'google-uid'); $facebookUser = $auth->getUserByProviderUid('facebook.com', 'facebook-uid'); } catch (KreaitFirebaseExceptionAuthUserNotFound $e) { echo $e->getMessage(); } ``` -------------------------------- ### Firebase Emulator Configuration (Realtime Database) Source: https://github.com/kreait/firebase-php/blob/7.x/docs/testing.rst Configuration for the Firebase Realtime Database emulator within the firebase.json file. This specifies the port for the emulator, recommended to avoid conflicts with PHP-FPM. ```js { "emulators": { "database": { "port": 9100 } } } ``` -------------------------------- ### Firebase Emulator Configuration (Auth) Source: https://github.com/kreait/firebase-php/blob/7.x/docs/testing.rst Configuration for the Firebase Auth emulator within the firebase.json file. This specifies the port the emulator will run on, allowing local development and testing. ```js { "emulators": { "auth": { "port": 9099 } } } ``` -------------------------------- ### Verify Firebase ID Token Source: https://github.com/kreait/firebase-php/blob/7.x/docs/authentication.rst Provides an example of how to verify a Firebase ID token to identify the currently signed-in user on your server. This method is intended for tokens originating from Firebase client SDKs. ```php use Kreait\Firebase\Exception\Auth\FailedToVerifyToken; // ... verification logic here ... ``` -------------------------------- ### Configure Service Account Source: https://github.com/kreait/firebase-php/blob/7.x/docs/setup.rst Demonstrates how to configure the Firebase SDK with a service account JSON key file for authentication. This is essential for server-side access to Firebase projects. ```php use Kreait\Firebase\Factory; $factory = (new Factory)->withServiceAccount('/path/to/firebase_credentials.json'); ``` -------------------------------- ### Check and Get User by Provider UID Source: https://github.com/kreait/firebase-php/blob/7.x/docs/user-management.rst Demonstrates how to check if the `getUserByProviderUid` method exists and retrieve a user if available. It shows checks using `method_exists` and instanceof checks against the `FederatedUserFetcher` interface. ```php use KreaitFirebaseContractTransitionalFederatedUserFetcher; use KreaitFirebaseFactory; $auth = (new Factory())->createAuth(); if (method_exists($auth, 'getUserByProviderUid')) { $user = $auth->getUserByProviderUid('google.com', 'google-uid'); } if ($auth instanceof KreaitFirebaseAuth) { // This is the implementation, not the interface $user = $auth->getUserByProviderUid('google.com', 'google-uid'); } if ($auth instanceof FederatedUserFetcher) { $user = $auth->getUserByProviderUid('google.com', 'google-uid'); } ``` -------------------------------- ### Removed Messaging AndroidConfig Methods Source: https://github.com/kreait/firebase-php/blob/7.x/UPGRADE-7.0.md Methods related to setting priority for `Kreait\Firebase\Messaging\AndroidConfig` have been removed: `withHighPriority()`, `withNormalPriority()`, and `withPriority()`. ```php REMOVED: Method Kreait\Firebase\Messaging\AndroidConfig#withHighPriority() was removed REMOVED: Method Kreait\Firebase\Messaging\AndroidConfig#withNormalPriority() was removed REMOVED: Method Kreait\Firebase\Messaging\AndroidConfig#withPriority() was removed ``` -------------------------------- ### Filter Results Starting After Value (PHP) Source: https://github.com/kreait/firebase-php/blob/7.x/docs/realtime-database.rst Retrieves children whose values are strictly greater than a specified value. Requires prior ordering. Note: May not work with Firebase REST API. ```php $database->getReference('people') ->orderByChild('height') ->startAfter(1.68) ->getSnapshot(); ``` -------------------------------- ### Sending Raw/Custom Messages Source: https://github.com/kreait/firebase-php/blob/7.x/docs/cloud-messaging.rst Explains how to send pre-compiled message payloads using RawMessageFromArray or by implementing the Message interface for custom message structures. Includes examples for notification, data, Android, APNS, and Webpush configurations. ```php use KreaitFirebaseMessagingRawMessageFromArray; $message = new RawMessageFromArray([ 'notification' => [ // https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#notification 'title' => 'Default title', 'body' => 'Default body', ], 'data' => [ 'key' => 'Value', ], 'android' => [ // https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#androidconfig 'notification' => [ 'title' => 'Android Title', 'body' => 'Android Body', ], ], 'apns' => [ // https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#apnsconfig 'payload' => [ 'aps' => [ 'alert' => [ 'title' => 'iOS Title', 'body' => 'iOS Body', ], ], ], ], 'webpush' => [ // https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages#webpushconfig 'notification' => [ 'title' => 'Webpush Title', 'body' => 'Webpush Body' ] ] ]); ``` -------------------------------- ### Setting Realtime Database Emulator Environment Variable Source: https://github.com/kreait/firebase-php/blob/7.x/docs/testing.rst Sets the FIREBASE_DATABASE_EMULATOR_HOST environment variable to enable Firebase Admin SDKs to connect to the local Realtime Database emulator. This is crucial for local testing of database interactions. ```bash $ export FIREBASE_DATABASE_EMULATOR_HOST="localhost:9100" ``` -------------------------------- ### Create Dynamic Links Source: https://github.com/kreait/firebase-php/blob/7.x/docs/dynamic-links.rst Shows how to create dynamic links using the SDK, supporting both unguessable and short suffixes. It also includes error handling for failed link creation. ```php use Kreait\Firebase\DynamicLink\CreateDynamicLink\FailedToCreateDynamicLink; $url = 'https://www.example.com/some/path'; try { $link = $dynamicLinks->createUnguessableLink($url); $link = $dynamicLinks->createDynamicLink($url, CreateDynamicLink::WITH_UNGUESSABLE_SUFFIX); $link = $dynamicLinks->createShortLink($url); $link = $dynamicLinks->createDynamicLink($url, CreateDynamicLink::WITH_SHORT_SUFFIX); } catch (FailedToCreateDynamicLink $e) { echo $e->getMessage(); exit; } ``` -------------------------------- ### Removed Auth UserInfo Methods Source: https://github.com/kreait/firebase-php/blob/7.x/UPGRADE-7.0.md The `jsonSerialize()` and `fromResponseData()` methods have been removed from the `Kreait\Firebase\Auth\UserInfo` class. Additionally, the `__get()` method has been removed from `Kreait\Firebase\Auth\UserRecord`. ```php REMOVED: Method Kreait\Firebase\Auth\UserInfo#jsonSerialize() was removed REMOVED: Method Kreait\Firebase\Auth\UserInfo::fromResponseData() was removed REMOVED: Method Kreait\Firebase\Auth\UserRecord#__get() was removed ``` -------------------------------- ### Database Reference Parameter Type Changes Source: https://github.com/kreait/firebase-php/blob/7.x/UPGRADE-7.0.md Updates to parameter types for methods in `Kreait\Firebase\Database\Reference`. The `$value` parameter for `endAt`, `endBefore`, `equalTo`, `startAfter`, and `startAt` now accepts `bool|string|int|float`. The `set` method's `$value` parameter now accepts `mixed`. ```php Kreait\Firebase\Database\Reference#endAt($value) // $value changed from no type to bool|string|int|float Kreait\Firebase\Database\Reference#endBefore($value) // $value changed from no type to bool|string|int|float Kreait\Firebase\Database\Reference#equalTo($value) // $value changed from no type to bool|string|int|float Kreait\Firebase\Database\Reference#set($value) // $value changed from no type to mixed Kreait\Firebase\Database\Reference#startAfter($value) // $value changed from no type to bool|string|int|float Kreait\Firebase\Database\Reference#startAt($value) // $value changed from no type to bool|string|int|float ``` -------------------------------- ### Create Dynamic Link with Method Chaining Source: https://github.com/kreait/firebase-php/blob/7.x/docs/dynamic-links.rst Demonstrates creating a Firebase Dynamic Link by configuring various options using method chaining on the DynamicLinks client. This approach is suitable when SDK support for all desired options is available. ```php $dynamicLinks = $firebase->getDynamicLinks(); $action = $dynamicLinks->createActionLinksConfiguration() ->withAndroidInfo( AndroidInfo::new() ->withPackageName('com.example.android') ->withLink('https://example.com/path/to/page') ->withMinPackageVersionCode('minPackageVersionCode') ) ->withSocialMetaTagInfo( SocialMetaTagInfo::new() ->withDescription('Social Meta Tag description') ->withTitle('Social Meta Tag title') ->withImageLink('https://example.com/image.jpg') ); $link = $dynamicLinks->createDynamicLink($action); ``` -------------------------------- ### Get Link Statistics Source: https://github.com/kreait/firebase-php/blob/7.x/docs/dynamic-links.rst Explains how to retrieve statistics for a short Dynamic Link using the Firebase PHP SDK. It covers fetching statistics for a default period (past 7 days) or a custom duration. The returned object provides access to event statistics. ```php use Kreait\Firebase\DynamicLink\GetStatisticsForDynamicLink\FailedToGetStatisticsForDynamicLink; try { $stats = $dynamicLinks->getStatistics('https://example.page.link/wXYZ'); $stats = $dynamicLinks->getStatistics('https://example.page.link/wXYZ', 14); // duration in days } catch (FailedToGetStatisticsForDynamicLink $e) { echo $e->getMessage(); exit; } ``` -------------------------------- ### Setting Auth Emulator Environment Variable Source: https://github.com/kreait/firebase-php/blob/7.x/docs/testing.rst Sets the FIREBASE_AUTH_EMULATOR_HOST environment variable to enable Firebase Admin SDKs to connect to the local Authentication emulator. This facilitates testing with unsigned ID tokens. ```bash $ export FIREBASE_AUTH_EMULATOR_HOST="localhost:9099" ``` -------------------------------- ### Firebase Dynamic Links REST API - Get Link Statistics Source: https://github.com/kreait/firebase-php/blob/7.x/docs/dynamic-links.rst This section details the REST API endpoint for retrieving analytics data for short Dynamic Links. It specifies that statistics might not include events logged within the last 36 hours. The API allows fetching statistics for a specific link, optionally with a duration in days. ```APIDOC REST API: Get Link Statistics Endpoint: (Not explicitly provided, but implied to be used with the SDK method) Purpose: Retrieve analytics data for short Dynamic Links. Note: Statistics might not include events logged within the last 36 hours. Methods: getStatistics(shortLink: string, durationDays?: number): DynamicLinkStatistics - shortLink: The short Dynamic Link URL (e.g., 'https://example.page.link/wXYZ'). - durationDays: Optional. The duration in days for which to retrieve statistics. Defaults to 7 days if not provided. Return Value: An instance of Kreait\Firebase\DynamicLink\DynamicLinkStatistics, containing event statistics. - rawData(): Access the raw returned data. - eventStatistics(): Access filtered event statistics. Event Statistics Object: Supports filtering by clicks, redirects, app installs, app first-opens, app re-opens, and platform (Android, Desktop, iOS). Methods include: - clicks(): Returns statistics for clicks. - redirects(): Returns statistics for redirects. - appInstalls(): Returns statistics for app installs. - appFirstOpens(): Returns statistics for app first opens. - appReOpens(): Returns statistics for app re-opens. - onAndroid(): Filters events on Android. - onDesktop(): Filters events on Desktop. - onIOS(): Filters events on iOS. - filter(callback): Allows custom filtering of event groups. - count(): Returns the total count of filtered events. ``` -------------------------------- ### Apply Coding Standards Source: https://github.com/kreait/firebase-php/blob/7.x/docs/overview.rst Applies coding standard fixes to the project using the PHP Coding Standards Fixer. This command ensures a uniform coding style across the SDK, as defined by the project's guidelines. ```bash make cs ``` -------------------------------- ### Firebase Dynamic Links API Reference Source: https://github.com/kreait/firebase-php/blob/7.x/docs/dynamic-links.rst Provides an overview of the Firebase Dynamic Links API for creating short links. It details the `createDynamicLink` method and its parameters, including `dynamicLinkInfo` and `suffix`, and references the official API documentation for comprehensive details. ```APIDOC DynamicLinksClient: createDynamicLink(array $parameters): string Creates a dynamic link. Parameters: parameters (array): An associative array containing the dynamic link configuration. dynamicLinkInfo (array): Information about the dynamic link. domainUriPrefix (string): The domain prefix for the dynamic link (e.g., 'https://example.page.link'). link (string): The target URL for the dynamic link. androidInfo (array, optional): Information for Android apps. packageName (string): The Android package name. link (string, optional): The deep link for Android. minPackageVersionCode (string, optional): Minimum version code for the Android app. socialMetaTagInfo (array, optional): Social meta tag information. description (string): Description for social media sharing. title (string): Title for social media sharing. imageLink (string): Image URL for social media sharing. suffix (array, optional): Suffix configuration for the dynamic link. option (string): Suffix option ('SHORT' or 'UNSPECIFIED'). Returns: string: The generated dynamic link URL. Throws: FailedToCreateDynamicLink: If the dynamic link creation fails. API Reference Documentation: https://firebase.google.com/docs/reference/dynamic-links/link-shortener ```